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

feat(media): auto-file series cover renders + lock universe collections (#273)

[._.]/ Adam Eivy6bcc5387c69c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7091b2b2c3..39e7eb54ef 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -11,6 +11,7 @@
- **Universe canon now lives inside Universe Builder.** Characters, places, and objects are managed inline on the universe page — no separate canon page to navigate to. The old canon URL still works as a redirect, and the Series Pipeline link lands you on the same combined view. Pending edits to other universe fields are no longer lost when canon changes are saved.
- **Locking a canon entry now also blocks new reference renders.** Locked characters/places/objects already prevented AI rewrites; they now prevent new reference and clean-plate image renders too, so a locked entry's identity stays frozen across both text and visuals. Disabled buttons explain the lock in their tooltips.
- **Universe Builder categories now carry a canon trunk (`kind`)** so each bucket knows whether it belongs under Cast, Places, Objects, or Other. Built-in defaults are pre-tagged (landscapes/environments/structures → Places, vehicles → Objects); custom buckets default to Other until you sort them. The default `characters` category was retired — canon owns characters now, and any pre-existing character variations get folded into universe canon on upgrade. Foundation for the upcoming tabbed-trunk Universe Builder redesign.
+- **Series cover renders auto-file into the universe's media collection, and universe-linked collections are now name-locked.** Volume (season) and issue cover/back-cover renders now drop into the same `Universe: <name>` bucket that Universe Builder fills with concept art — no more orphan covers floating in the gallery. The collection's name is locked while it's linked to a universe: rename attempts are blocked server-side and the UI shows a lock icon instead of the rename pencil. Renaming the universe itself cascades to the linked collection's name automatically.
- **TUI providers now return clean responses via a per-run output file.** Claude Code TUI / Codex TUI runs are now instructed to write their final response to `data/runs/<runId>/tui-response.txt`, which the runner reads back instead of scraping the PTY screen — no more banner art, "5% cost" meters, or "bypass permissions on" hints leaking into stage outputs. Falls back to the existing screen-scrape cleanup when the file isn't written.
- **"From proof" final renders now work with the Codex (gpt-image-2) backend.** Codex CLI's `-i <file>` flag attaches the proof PNG so gpt-image-2 runs in image-edit mode and preserves composition while upscaling, instead of redrawing from scratch. The pipeline UI's "from proof" toggle on covers, back covers, and pages is no longer disabled when Codex is the selected backend; the dispatcher only strips `initImagePath` for the external SD-API backend (which has no i2i wiring). `initImageStrength` is mapped to a natural-language fidelity phrase in the prompt so low strengths keep the proof's layout intact and high strengths leave room for reinterpretation.
- **Generate From Idea now seeds named canon (characters/places/objects) alongside category variations.** The expand LLM call returns rich first-class entities — a protagonist gets a `physicalDescription`, a recurring location gets a `slugline` + `palette` — that merge directly into universe canon. Existing canon entries always win on name collision so a re-expand can't clobber hand-authored records.
@@ -23,3 +24,4 @@
- **Volume cover-concept generation no longer 500s on upgraded installs.** The per-season "generate volume cover concepts" LLM step was shipped with its prompt template but missing from `stage-config.json`, so existing installs hit `Stage pipeline-volume-cover-concepts not found`. Added the config entry and a migration that seeds both the template and the config on next launch — fresh installs were already fine.
- **Pending data migrations now apply automatically on every server start.** Previously only `update.sh` ran `scripts/run-migrations.js`, so a plain pull-and-restart (or `pm2 restart` after manual git pull) left shipped migrations un-applied — new prompt stages, settings renames, and seed data sat in the queue until the user explicitly ran update or `npm run migrations`. The server now invokes the migration runner during boot, before the AI toolkit loads `stage-config.json`, and continues on failure with an error log instead of refusing to start.
- **Pipeline prose stage now honors the per-series provider/model override.** "Draft prose" was dropping the series LLM override and falling back to the default provider — fixed; the override (e.g. Codex on a series-by-series basis) is now respected on the prose stage the same way it already was on idea, comic script, and teleplay.
+- **Universe collection provisioning is now atomic and universeId-first.** The Universe Builder render route and the pipeline cover filer both resolve the universe's bucket by `universeId` (not by name) through a new shared helper, so a universe rename, a name-collision with another universe, or two simultaneous first-time filings can no longer fork the bucket or drop a render. Two universes that happen to share a display name keep separate, properly-stamped collections instead of one hijacking the other's.
diff --git a/client/src/pages/MediaCollectionDetail.jsx b/client/src/pages/MediaCollectionDetail.jsx
index 98417f2c0a..77384ab193 100644
--- a/client/src/pages/MediaCollectionDetail.jsx
+++ b/client/src/pages/MediaCollectionDetail.jsx
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
-import { ArrowLeft, CheckSquare, Copy, FolderInput, Inbox, Pencil, Star, StarOff, Trash2, X } from 'lucide-react';
+import { ArrowLeft, CheckSquare, Copy, FolderInput, Inbox, Lock, Pencil, Star, StarOff, Trash2, X } from 'lucide-react';
import ShareToButton from '../components/sharing/ShareToButton';
import toast from '../components/ui/Toast';
import MediaCard from '../components/media/MediaCard';
@@ -299,6 +299,29 @@ export default function MediaCollectionDetail() {
{collection.name}
</h1>
);
+ // Universe-linked collections own their visible name — the user-facing
+ // identity follows the universe (renaming the universe cascades here).
+ // Routing is by `universeId` server-side regardless of name; this lock
+ // exists to keep the displayed name consistent with the universe. The
+ // server enforces it independently via the rename-lock in
+ // updateCollection. The lock state is exposed visually (icon + title
+ // tooltip for sighted users) and programmatically via the `sr-only`
+ // span — real text content screen readers announce after the
+ // collection name. An `aria-label` on the heading would override the
+ // visible name; the `sr-only` text adds context without clobbering it.
+ if (collection.universeId) {
+ const lockMsg = 'Linked to a Universe — rename the universe to rename this collection.';
+ return (
+ <h1
+ className="text-xl font-semibold text-white flex items-center gap-2"
+ title={lockMsg}
+ >
+ {collection.name}
+ <Lock className="w-4 h-4 text-gray-500" aria-hidden="true" />
+ <span className="sr-only">{lockMsg}</span>
+ </h1>
+ );
+ }
if (editingName) return (
<input
autoFocus
diff --git a/scripts/migrations/021-link-orphan-universe-collections.js b/scripts/migrations/021-link-orphan-universe-collections.js
new file mode 100644
index 0000000000..77ae747c56
--- /dev/null
+++ b/scripts/migrations/021-link-orphan-universe-collections.js
@@ -0,0 +1,159 @@
+/**
+ * Link pre-existing "Universe: <name>" media collections to their universes
+ * by name match.
+ *
+ * Background:
+ * The cover-auto-file feature (PR #273) routes universe-owned collection
+ * provisioning through `findOrCreateUniverseCollection`, which resolves
+ * by `universeId` and DOES NOT adopt a same-name unlinked collection at
+ * runtime — that path can't tell a true pre-link legacy bucket apart
+ * from a post-`deleteUniverse` orphan, so adopting either would risk
+ * silently mixing renders across universes.
+ *
+ * Upgraded installs that have an existing unlinked `Universe: <name>`
+ * bucket (filed manually before universeId stamping existed) would
+ * otherwise get a duplicate bucket on the next render, with new covers
+ * landing in the fresh bucket and the legacy renders stranded.
+ *
+ * What this does:
+ * 1. Forward-link: index universes by the *canonical collection name*
+ * they'd produce (`"Universe: " + name`, truncated to 80 chars — the
+ * same transform the runtime helper uses). For each unlinked
+ * collection whose name matches exactly one universe's canonical name
+ * (case-insensitive), stamp the `universeId` AND canonicalize the
+ * visible name to the freshly-computed canonical form. Skip zero or
+ * multi matches — the ambiguous case is the same risk this PR
+ * shipped to avoid.
+ * 2. Stale-link cleanup: clear `universeId` on any collection whose
+ * stamp doesn't correspond to a current universe. The old
+ * `deleteUniverse` didn't unlink linked collections, so upgraded
+ * installs can have stamped buckets whose universes are long gone —
+ * with this PR's new rename-lock, those would be permanently stuck
+ * under their old name. Unlinking releases the lock so the user can
+ * rename or delete the orphan via normal flows.
+ *
+ * Indexing by canonical (truncated) name closes two upgrade-path gaps:
+ * 1. Long universe names: the runtime truncates the collection name to
+ * 80 chars, so an install with a 100-char universe name has a
+ * collection holding only the truncated suffix. Comparing against
+ * the raw universe name would miss it.
+ * 2. Casing/whitespace drift: a legacy bucket named `universe: bar`
+ * (lowercase) gets relinked AND its display name is canonicalized
+ * to `Universe: bar` in the same write — without canonicalization
+ * the rename-lock kicks in immediately and the user is stuck with
+ * the bad-casing name forever.
+ *
+ * Idempotent: re-runs skip collections that already carry a `universeId`,
+ * so this is safe to leave in place forever.
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+
+const COLLECTION_NAME_MAX = 80;
+
+const readJson = async (path, fallback) => {
+ const raw = await readFile(path, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) return fallback;
+ return JSON.parse(raw);
+};
+
+const writeJson = (path, value) =>
+ writeFile(path, JSON.stringify(value, null, 2) + '\n');
+
+// Mirrors `universeCollectionNameFor` in server/services/mediaCollections.js
+// — duplicated inline so this one-shot migration's contract is frozen
+// against future runtime changes to the naming convention.
+const canonicalCollectionName = (universeName) =>
+ `Universe: ${typeof universeName === 'string' ? universeName : ''}`.slice(0, COLLECTION_NAME_MAX);
+
+const norm = (s) => (typeof s === 'string' ? s.trim().toLowerCase() : '');
+
+export default {
+ async up({ rootDir }) {
+ const collectionsPath = join(rootDir, 'data', 'media-collections.json');
+ const universesPath = join(rootDir, 'data', 'universe-builder.json');
+
+ const collectionsDoc = await readJson(collectionsPath, null);
+ const universesDoc = await readJson(universesPath, null);
+ if (!collectionsDoc || !Array.isArray(collectionsDoc.collections)) {
+ return { linked: 0, reason: 'no-collections' };
+ }
+ if (!universesDoc || !Array.isArray(universesDoc.universes)) {
+ return { linked: 0, reason: 'no-universes' };
+ }
+
+ // Index universes by the canonical collection-name they'd produce, so
+ // long names (truncated) and short names match through the same path.
+ // Value is a list — multi-match means ambiguous, skip.
+ const universesByCanonicalName = new Map();
+ for (const u of universesDoc.universes) {
+ const canonical = canonicalCollectionName(u?.name);
+ const key = norm(canonical);
+ if (!key || key === norm('Universe: ')) continue; // skip universes with empty/whitespace names
+ const bucket = universesByCanonicalName.get(key) || [];
+ bucket.push(u);
+ universesByCanonicalName.set(key, bucket);
+ }
+
+ // Set of all current universe ids so we can detect stale stamps
+ // (collection.universeId pointing at a universe that no longer exists).
+ const currentUniverseIds = new Set(
+ universesDoc.universes
+ .map((u) => (typeof u?.id === 'string' ? u.id : null))
+ .filter(Boolean),
+ );
+
+ let linked = 0;
+ let unlinkedStale = 0;
+ let ambiguous = 0;
+ const now = new Date().toISOString();
+ for (const c of collectionsDoc.collections) {
+ if (c?.universeId) {
+ // Stale-link cleanup: pre-PR `deleteUniverse` didn't unlink, and
+ // the new rename-lock now strands those orphans permanently. Clear
+ // the stamp so the user can rename or delete them via normal flows.
+ if (!currentUniverseIds.has(c.universeId)) {
+ c.universeId = null;
+ c.updatedAt = now;
+ unlinkedStale += 1;
+ }
+ continue;
+ }
+ if (typeof c?.name !== 'string') continue;
+ const key = norm(c.name);
+ const matches = universesByCanonicalName.get(key);
+ if (!matches || matches.length === 0) continue;
+ if (matches.length > 1) {
+ ambiguous += 1;
+ console.warn(`⚠️ migration 021: collection "${c.name}" matches ${matches.length} universes — skipping (ambiguous link).`);
+ continue;
+ }
+ const universe = matches[0];
+ c.universeId = universe.id;
+ // Canonicalize the visible name in the same write. After link the
+ // rename-lock takes effect, so this is the user's last chance to
+ // get the correct casing/whitespace without hand-editing JSON.
+ c.name = canonicalCollectionName(universe.name);
+ c.updatedAt = now;
+ linked += 1;
+ }
+
+ if (linked > 0 || unlinkedStale > 0) {
+ await writeJson(collectionsPath, collectionsDoc);
+ }
+ if (linked > 0) {
+ console.log(`🔗 migration 021: linked ${linked} legacy "Universe: <name>" collection(s) by canonical-name match.`);
+ }
+ if (unlinkedStale > 0) {
+ console.log(`🔓 migration 021: unlinked ${unlinkedStale} collection(s) whose universe no longer exists (releases rename-lock).`);
+ }
+ if (ambiguous > 0) {
+ console.log(`ℹ️ migration 021: ${ambiguous} collection(s) skipped due to multiple same-named universes.`);
+ }
+ return { linked, unlinkedStale, ambiguous };
+ },
+};
diff --git a/scripts/migrations/021-link-orphan-universe-collections.test.js b/scripts/migrations/021-link-orphan-universe-collections.test.js
new file mode 100644
index 0000000000..d2d5870c38
--- /dev/null
+++ b/scripts/migrations/021-link-orphan-universe-collections.test.js
@@ -0,0 +1,163 @@
+/**
+ * Test for migration 021 — link orphan "Universe: <name>" collections to
+ * their universes by name match.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration from './021-link-orphan-universe-collections.js';
+
+const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));
+
+describe('migration 021 — link orphan universe collections', () => {
+ let rootDir;
+ let dataDir;
+ let collectionsPath;
+ let universesPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-021-'));
+ dataDir = join(rootDir, 'data');
+ mkdirSync(dataDir, { recursive: true });
+ collectionsPath = join(dataDir, 'media-collections.json');
+ universesPath = join(dataDir, 'universe-builder.json');
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ it('links a single unlinked "Universe: <name>" collection to the matching universe', async () => {
+ writeJson(universesPath, { universes: [{ id: 'u-1', name: 'Foo' }] });
+ writeJson(collectionsPath, {
+ collections: [
+ { id: 'c-1', name: 'Universe: Foo', universeId: null, items: [] },
+ ],
+ });
+ const result = await migration.up({ rootDir });
+ expect(result.linked).toBe(1);
+ const after = readJson(collectionsPath);
+ expect(after.collections[0].universeId).toBe('u-1');
+ });
+
+ it('is idempotent — already-linked collections are skipped on re-run', async () => {
+ writeJson(universesPath, { universes: [{ id: 'u-1', name: 'Foo' }] });
+ writeJson(collectionsPath, {
+ collections: [
+ { id: 'c-1', name: 'Universe: Foo', universeId: 'u-1', items: [] },
+ ],
+ });
+ const result = await migration.up({ rootDir });
+ expect(result.linked).toBe(0);
+ expect(result.unlinkedStale).toBe(0);
+ });
+
+ it('unlinks a stale stamp — collection.universeId points at a universe that no longer exists', async () => {
+ // Pre-PR `deleteUniverse` didn't unlink, so an upgraded install can
+ // carry a stamped bucket whose universe is gone. With the new
+ // rename-lock, that bucket is permanently stuck under its old name
+ // unless this migration releases it.
+ writeJson(universesPath, { universes: [{ id: 'u-1', name: 'Foo' }] });
+ writeJson(collectionsPath, {
+ collections: [
+ { id: 'c-orphan', name: 'Universe: Ghost', universeId: 'u-ghost-deleted', items: [] },
+ ],
+ });
+ const result = await migration.up({ rootDir });
+ expect(result.unlinkedStale).toBe(1);
+ expect(result.linked).toBe(0);
+ const after = readJson(collectionsPath);
+ expect(after.collections[0].universeId).toBeNull();
+ // Name preserved — the user can now rename or delete it via normal flows.
+ expect(after.collections[0].name).toBe('Universe: Ghost');
+ });
+
+ it('skips ambiguous matches (two universes share the same display name)', async () => {
+ writeJson(universesPath, {
+ universes: [
+ { id: 'u-A', name: 'Twin' },
+ { id: 'u-B', name: 'Twin' },
+ ],
+ });
+ writeJson(collectionsPath, {
+ collections: [
+ { id: 'c-1', name: 'Universe: Twin', universeId: null, items: [] },
+ ],
+ });
+ const result = await migration.up({ rootDir });
+ expect(result.linked).toBe(0);
+ expect(result.ambiguous).toBe(1);
+ const after = readJson(collectionsPath);
+ expect(after.collections[0].universeId).toBeNull();
+ });
+
+ it('ignores collections whose name does not match the "Universe: <X>" pattern', async () => {
+ writeJson(universesPath, { universes: [{ id: 'u-1', name: 'Foo' }] });
+ writeJson(collectionsPath, {
+ collections: [
+ { id: 'c-1', name: 'My Custom Bucket', universeId: null, items: [] },
+ ],
+ });
+ const result = await migration.up({ rootDir });
+ expect(result.linked).toBe(0);
+ const after = readJson(collectionsPath);
+ expect(after.collections[0].universeId).toBeNull();
+ });
+
+ it('matches case-insensitively AND canonicalizes the visible name on link', async () => {
+ writeJson(universesPath, { universes: [{ id: 'u-1', name: 'bar' }] });
+ writeJson(collectionsPath, {
+ collections: [
+ { id: 'c-1', name: 'universe: BAR', universeId: null, items: [] },
+ ],
+ });
+ const result = await migration.up({ rootDir });
+ expect(result.linked).toBe(1);
+ const after = readJson(collectionsPath);
+ expect(after.collections[0].universeId).toBe('u-1');
+ // Canonicalized — the rename-lock now activates, so this is the user's
+ // last chance to get the right casing without hand-editing the JSON.
+ expect(after.collections[0].name).toBe('Universe: bar');
+ });
+
+ it('links a long-name universe whose canonical collection name is truncated to 80 chars', async () => {
+ // 100-char universe name — `Universe: <100-char>` truncates to
+ // "Universe: " + first 70 chars. The migration must match on the
+ // truncated canonical name, not the raw universe name.
+ const longName = 'x'.repeat(100);
+ const expectedCanonical = ('Universe: ' + longName).slice(0, 80);
+ writeJson(universesPath, { universes: [{ id: 'u-long', name: longName }] });
+ writeJson(collectionsPath, {
+ collections: [
+ // The collection on disk has the truncated name (that's what the
+ // sanitizer would have written when the bucket was originally
+ // created pre-link).
+ { id: 'c-long', name: expectedCanonical, universeId: null, items: [] },
+ ],
+ });
+ const result = await migration.up({ rootDir });
+ expect(result.linked).toBe(1);
+ const after = readJson(collectionsPath);
+ expect(after.collections[0].universeId).toBe('u-long');
+ expect(after.collections[0].name).toBe(expectedCanonical);
+ });
+
+ it('no-ops when the media-collections file does not exist', async () => {
+ writeJson(universesPath, { universes: [{ id: 'u-1', name: 'Foo' }] });
+ const result = await migration.up({ rootDir });
+ expect(result.linked).toBe(0);
+ expect(result.reason).toBe('no-collections');
+ });
+
+ it('no-ops when the universe-builder file does not exist', async () => {
+ writeJson(collectionsPath, {
+ collections: [{ id: 'c-1', name: 'Universe: Foo', universeId: null, items: [] }],
+ });
+ const result = await migration.up({ rootDir });
+ expect(result.linked).toBe(0);
+ expect(result.reason).toBe('no-universes');
+ });
+});
diff --git a/server/routes/apps.test.js b/server/routes/apps.test.js
index 72d5a6cff3..bb5dd58eae 100644
--- a/server/routes/apps.test.js
+++ b/server/routes/apps.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
import express from 'express';
import { request } from '../lib/testHelper.js';
import appsRoutes from './apps.js';
diff --git a/server/routes/sharing.js b/server/routes/sharing.js
index feeb07b8fa..982ea8dc50 100644
--- a/server/routes/sharing.js
+++ b/server/routes/sharing.js
@@ -56,6 +56,7 @@ const SHARING_ERROR_STATUS = {
SHARING_SUBSCRIPTION_VALIDATION: 400,
SHARING_RECORDS_PENDING: 409,
SHARING_ASSETS_PENDING: 409,
+ SHARING_UNIVERSE_PENDING: 409,
};
const mapSharingError = (err) => {
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index b7e54c4055..973188e08d 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -24,7 +24,7 @@ import { expandWorldTemplate, generateCategoryVariations } from '../services/uni
import { refineWorldPrompts } from '../services/universeBuilderRefine.js';
import { enqueueJob } from '../services/mediaJobQueue/index.js';
import { getSettings } from '../services/settings.js';
-import { findOrCreateCollectionByName, NAME_MAX_LENGTH as COLLECTION_NAME_MAX } from '../services/mediaCollections.js';
+import { findOrCreateUniverseCollection } from '../services/mediaCollections.js';
import { registerUniverseBuilderRun } from '../services/universeBuilderCollectionHook.js';
import { getImageModels, isFlux2, isZImage, isErnie } from '../lib/mediaModels.js';
@@ -238,9 +238,12 @@ const selectionSchema = z.record(
});
const renderSchema = z.object({
- // Optional friendly name for the resulting collection. If omitted, server
- // synthesizes "Universe: <name> (timestamp)".
- collectionName: z.string().trim().min(1).max(COLLECTION_NAME_MAX).optional(),
+ // Removed: callers that still send `collectionName` get an explicit 400
+ // (see the .refine() below) instead of a confusing silent no-op. The
+ // canonical "Universe: <name>" identity is owned by the universe and
+ // enforced by the rename-lock — per-render overrides have no semantic
+ // home in that model.
+ collectionName: z.unknown().optional(),
// Image-gen knobs — these mirror /api/image-gen/generate so the user can
// pick mode/size/steps without bouncing to the Image page first.
mode: z.enum(['external', 'local', 'codex']).optional(),
@@ -256,6 +259,9 @@ const renderSchema = z.object({
batchPerVariation: z.number().int().min(1).max(20).optional().default(1),
selection: selectionSchema.optional(),
sheetSelection: z.union([z.literal('all'), z.array(z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX)).max(svc.COMPOSITE_SHEETS_MAX)]).optional(),
+}).refine((body) => body.collectionName === undefined, {
+ message: 'collectionName is no longer supported — the linked collection follows the universe name automatically. Remove this field.',
+ path: ['collectionName'],
});
router.get('/', asyncHandler(async (_req, res) => {
@@ -365,16 +371,16 @@ router.post('/:id/render', asyncHandler(async (req, res) => {
// Provision the collection up front so renders can be tagged as they
// complete. The completion hook (universeBuilderCollectionHook) will add
- // each finished image's filename to this collection. Repeat renders of
- // the same universe reuse the existing `Universe: <name>` bucket so per-universe
- // output accumulates in one place instead of fragmenting into a fresh
- // date-suffixed collection per run.
- const collectionName = body.collectionName?.trim()
- || `Universe: ${universe.name}`;
- const collection = await findOrCreateCollectionByName({
- name: collectionName.slice(0, COLLECTION_NAME_MAX),
- description: `Universe Builder renders for "${universe.name}"`,
+ // each finished image's filename to this collection. Resolution is
+ // universeId-first (not name-first) so a re-render finds the existing
+ // linked bucket even if the universe was hand-renamed or another
+ // universe happens to share the same display name. Name-only matching
+ // would either fork the bucket on rename or hijack a foreign universe's
+ // collection — the atomic helper rules out both.
+ const collection = await findOrCreateUniverseCollection({
universeId: universe.id,
+ universeName: universe.name,
+ description: `Universe Builder renders for "${universe.name}"`,
});
const runId = randomUUID();
diff --git a/server/routes/universeBuilder.test.js b/server/routes/universeBuilder.test.js
index fe1d1c6ea5..7e7ee063c6 100644
--- a/server/routes/universeBuilder.test.js
+++ b/server/routes/universeBuilder.test.js
@@ -59,12 +59,35 @@ const mockCreateRec = (name) => {
collectionsByName.set(name.toLowerCase(), rec);
return rec;
};
+// Mirrors the production helper's universeId-first resolution so repeat-
+// render tests verify the new contract (same `universeId` → same collection
+// id) rather than the old name-only contract.
+const collectionsByUniverseId = new Map();
+const upsertUniverseRec = ({ universeId, universeName }) => {
+ if (collectionsByUniverseId.has(universeId)) return collectionsByUniverseId.get(universeId);
+ const name = `Universe: ${universeName || ''}`.slice(0, 80);
+ const rec = mockCreateRec(name);
+ rec.universeId = universeId;
+ collectionsByUniverseId.set(universeId, rec);
+ return rec;
+};
vi.mock('../services/mediaCollections.js', () => ({
createCollection: vi.fn(async ({ name }) => mockCreateRec(name)),
findOrCreateCollectionByName: vi.fn(async ({ name }) => {
return collectionsByName.get(name.toLowerCase()) ?? mockCreateRec(name);
}),
+ findOrCreateUniverseCollection: vi.fn(async ({ universeId, universeName }) =>
+ upsertUniverseRec({ universeId, universeName })),
addItem: vi.fn(),
+ // Universe rename → collection rename cascade calls this from updateUniverse.
+ // No-op here is fine: the routes test cares about the universe PATCH itself,
+ // not the bookkeeping side-effect (covered in mediaCollections.test.js).
+ renameCollectionForUniverse: vi.fn(async () => null),
+ // Universe delete → unlink linked collections so the orphaned bucket
+ // becomes a normal user-owned collection. No-op stub mirrors the rename
+ // cascade pattern above (behavior is covered in mediaCollections.test.js).
+ unlinkCollectionsForUniverse: vi.fn(async () => []),
+ universeCollectionNameFor: (name) => `Universe: ${name || ''}`.slice(0, 80),
ERR_DUPLICATE: 'DUPLICATE',
NAME_MAX_LENGTH: 80,
}));
@@ -91,6 +114,7 @@ describe('universe-builder routes', () => {
fileStore.clear();
uuidCounter = 0;
collectionsByName.clear();
+ collectionsByUniverseId.clear();
});
it('GET / returns []', async () => {
@@ -365,21 +389,19 @@ describe('universe-builder routes', () => {
expect(second.body.collectionName).not.toMatch(/\d{4}-\d{2}-\d{2}/);
});
- it('POST /:id/render reuses an existing collection when collectionName matches', async () => {
+ it('POST /:id/render rejects body.collectionName with a clear error (deprecated field)', async () => {
const app = buildApp();
const created = await request(app).post('/api/universe-builder').send({
- name: 'Custom Bucket Universe',
+ name: 'Reject CollectionName Universe',
categories: {
landscapes: { variations: [{ label: 'A', prompt: 'a' }] },
},
});
- const first = await request(app)
+ const res = await request(app)
.post(`/api/universe-builder/${created.body.id}/render`)
.send({ mode: 'local', collectionName: 'Shared Bucket' });
- const second = await request(app)
- .post(`/api/universe-builder/${created.body.id}/render`)
- .send({ mode: 'local', collectionName: ' shared bucket ' });
- expect(second.body.collectionId).toBe(first.body.collectionId);
+ expect(res.status).toBe(400);
+ expect(JSON.stringify(res.body)).toMatch(/collectionName/i);
});
it('POST /:id/render rejects when no variations exist', async () => {
diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.js
index ca507a5333..d4c0301db0 100644
--- a/server/services/mediaCollections.js
+++ b/server/services/mediaCollections.js
@@ -8,6 +8,15 @@
* An item is identified by `{ kind: 'image'|'video', ref: <filename|videoId> }`.
* A collection's `coverKey` is `null` (auto: newest item) or `"<kind>:<ref>"`
* to pin a specific item as the cover thumbnail.
+ *
+ * **Concurrency.** Every public mutator routes through `serializeFileWrite`
+ * (a single-tail queue keyed on the shared media-collections.json file).
+ * Without it, parallel write paths — e.g. the pipeline cover filer's
+ * `addItem` running alongside Universe Builder's completion-hook `addItem`,
+ * or a `deleteUniverse` unlink racing with an in-flight cover completion —
+ * each do a `listCollections → modify → atomicWrite(entire array)` round
+ * and the second write silently clobbers the first. Mirrors the
+ * `issueWriteTail` pattern in `server/services/pipeline/issues.js`.
*/
import { join } from 'path';
@@ -17,7 +26,10 @@ import { ITEM_KIND, REF_MAX_LENGTH, itemKey } from '../lib/mediaItemKey.js';
import { sanitizeOrigin } from '../lib/sharingOrigin.js';
import { emitRecordUpdated } from './sharing/recordEvents.js';
-const STATE_PATH = join(PATHS.data, 'media-collections.json');
+// Lazy resolution — PATHS.data may not be available at module-load time
+// (e.g. tests that swap it through a Proxy mock so different cases get
+// different temp roots). See universeBuilder.js for the same pattern.
+const statePath = () => join(PATHS.data, 'media-collections.json');
export const ERR_NOT_FOUND = 'NOT_FOUND';
export const ERR_DUPLICATE = 'DUPLICATE';
@@ -96,7 +108,7 @@ const sanitizeCollection = (raw) => {
export async function listCollections() {
await ensureDir(PATHS.data);
- const raw = await readJSONFile(STATE_PATH, DEFAULT_STATE, { logError: false });
+ const raw = await readJSONFile(statePath(), DEFAULT_STATE, { logError: false });
if (!Array.isArray(raw.collections)) return [];
const seen = new Set();
const out = [];
@@ -116,8 +128,29 @@ export async function getCollection(id) {
return c;
}
+// File-level write tail. Every public mutator wraps its read-modify-write
+// in `serializeFileWrite` so the read always sees the freshest persisted
+// state and the write completes before the next task's read begins.
+// `writeAll` is the only persistence call and must only be invoked from
+// inside a serialized task.
+let fileWriteTail = Promise.resolve();
+const serializeFileWrite = (task) => {
+ const next = fileWriteTail.then(task, task);
+ // Silence the tail so a rejection doesn't poison subsequent waiters.
+ // Mirror the issueWriteTail / seriesWriteTail pattern: when this write
+ // is still the tail after it settles, reset to a fresh Promise.resolve()
+ // so the chain doesn't retain settled promises (and their resolved
+ // payloads) for the life of the process. If another write enqueues
+ // first, it becomes the tail and we drop our reference.
+ const silenced = next.catch(() => {});
+ fileWriteTail = silenced;
+ silenced.finally(() => {
+ if (fileWriteTail === silenced) fileWriteTail = Promise.resolve();
+ });
+ return next;
+};
const writeAll = async (collections) => {
- await atomicWrite(STATE_PATH, { collections });
+ await atomicWrite(statePath(), { collections });
return collections;
};
@@ -132,29 +165,35 @@ export async function createCollection({ name, description = '' }) {
const trimmedDescription = typeof description === 'string'
? description.trim().slice(0, DESCRIPTION_MAX_LENGTH)
: '';
- const all = await listCollections();
- const now = new Date().toISOString();
- const next = {
- id: randomUUID(),
- name: trimmedName,
- description: trimmedDescription,
- coverKey: null,
- items: [],
- createdAt: now,
- updatedAt: now,
- };
- await writeAll([...all, next]);
- return next;
+ return serializeFileWrite(async () => {
+ const all = await listCollections();
+ const now = new Date().toISOString();
+ const next = {
+ id: randomUUID(),
+ name: trimmedName,
+ description: trimmedDescription,
+ coverKey: null,
+ items: [],
+ createdAt: now,
+ updatedAt: now,
+ };
+ await writeAll([...all, next]);
+ return next;
+ });
}
// Find an existing collection by case-insensitive trimmed name, else create
-// a fresh one. Lets repeat-render callers (Universe Builder) append into a
-// single per-world bucket without growing a new collection on every run.
+// a fresh one. The non-universe-aware upsert — used by user-driven flows
+// where the bucket is identified by visible name (e.g. tests, ad-hoc CLI
+// scripts).
//
-// `universeId`, when provided, stamps the collection so share-bucket
-// subscriptions know which universe-record to notify when items change.
-// If the matched existing collection lacks `universeId`, it's backfilled
-// from the caller's value so the link is established on next access.
+// **Universe-owned paths must use `findOrCreateUniverseCollection`.**
+// This helper is name-first and will return any same-name collection,
+// including one already linked to a different universe, so it can route
+// renders into the wrong bucket when two universes share a display name.
+// The legacy `universeId` parameter remains for callers that need the
+// best-effort backfill of an unlinked legacy bucket, but new code should
+// prefer the universeId-first helper.
export async function findOrCreateCollectionByName({ name, description = '', universeId = null }) {
const trimmed = typeof name === 'string' ? name.trim() : '';
if (!trimmed || trimmed.length > NAME_MAX_LENGTH) {
@@ -163,63 +202,244 @@ export async function findOrCreateCollectionByName({ name, description = '', uni
const trimmedDescription = typeof description === 'string'
? description.trim().slice(0, DESCRIPTION_MAX_LENGTH)
: '';
- const all = await listCollections();
- const needle = trimmed.toLowerCase();
- const existing = all.find((c) => c.name.toLowerCase() === needle);
- if (existing) {
- if (universeId && !existing.universeId) {
- // Lazy backfill so legacy "Universe: <name>" collections gain the
- // link the first time a universe-builder render references them.
- const idx = all.findIndex((c) => c.id === existing.id);
- all[idx] = { ...existing, universeId, updatedAt: new Date().toISOString() };
- await writeAll(all);
- return all[idx];
+ return serializeFileWrite(async () => {
+ const all = await listCollections();
+ const needle = trimmed.toLowerCase();
+ const existing = all.find((c) => c.name.toLowerCase() === needle);
+ if (existing) {
+ if (universeId && !existing.universeId) {
+ // Lazy backfill so legacy "Universe: <name>" collections gain the
+ // link the first time a universe-builder render references them.
+ const idx = all.findIndex((c) => c.id === existing.id);
+ all[idx] = { ...existing, universeId, updatedAt: new Date().toISOString() };
+ await writeAll(all);
+ return all[idx];
+ }
+ return existing;
}
- return existing;
- }
- const now = new Date().toISOString();
- const next = {
- id: randomUUID(),
- name: trimmed,
- description: trimmedDescription,
- coverKey: null,
- universeId: universeId || null,
- items: [],
- createdAt: now,
- updatedAt: now,
- };
- await writeAll([...all, next]);
- return next;
+ const now = new Date().toISOString();
+ const next = {
+ id: randomUUID(),
+ name: trimmed,
+ description: trimmedDescription,
+ coverKey: null,
+ universeId: universeId || null,
+ items: [],
+ createdAt: now,
+ updatedAt: now,
+ };
+ await writeAll([...all, next]);
+ return next;
+ });
}
-export async function updateCollection(id, patch) {
+// Naming convention for the auto-managed universe collection. Single source
+// of truth so the upsert path, the rename cascade (updateUniverse), and any
+// caller that needs to display the name stay aligned. Truncated to
+// NAME_MAX_LENGTH because long universe names would otherwise overflow
+// sanitizeCollection's slice and silently mismatch.
+export const universeCollectionNameFor = (universeName) =>
+ `Universe: ${typeof universeName === 'string' ? universeName : ''}`.slice(0, NAME_MAX_LENGTH);
+
+// Look up an existing collection by its universeId stamp. Returns null if no
+// collection has ever been linked to this universe — callers fall back to
+// `findOrCreateUniverseCollection` (the universeId-first upsert) to provision
+// on first use. Do NOT fall back to `findOrCreateCollectionByName` here —
+// that path is name-first and would adopt a same-named foreign-universe
+// bucket. The argument is sliced to the same limit storage uses so passing
+// an overlong id (e.g. from a malformed share manifest) matches whatever
+// the upsert helper would have persisted.
+export async function findCollectionByUniverseId(universeId) {
+ if (typeof universeId !== 'string' || !universeId) return null;
+ const needle = universeId.slice(0, UNIVERSE_ID_MAX);
const all = await listCollections();
- const idx = all.findIndex((c) => c.id === id);
- if (idx < 0) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);
- const cur = all[idx];
- // 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.
- if (patch.coverKey != null && !cur.items.find((it) => itemKey(it) === patch.coverKey)) {
- throw makeErr('coverKey must reference an item in this collection', ERR_VALIDATION);
+ return all.find((c) => c.universeId === needle) || null;
+}
+
+/**
+ * Atomic universeId-first upsert for a universe's auto-managed collection.
+ *
+ * Resolution order (serialized via the shared file write tail):
+ * 1. universeId stamp wins. Returned as-is — the caller's `universeName`
+ * can be stale (it was a snapshot taken before this call entered the
+ * write tail), so reconciling the name here could ping-pong a fresh
+ * cascade rename back to an old name. `renameCollectionForUniverse`
+ * is the canonical path for name changes; if its best-effort cascade
+ * fails, the surviving stale name is acceptable until the user
+ * retriggers it (the lock blocks `updateCollection` but the cascade
+ * itself is unrestricted).
+ * 2. Otherwise a fresh collection is created and stamped with `universeId`,
+ * even when the canonical name is already taken by another collection
+ * (a different universe's bucket, OR a previously-unlinked orphan from
+ * a deleted universe). Adopting either would silently mix renders
+ * across universes; two same-named collections is the user-correctable
+ * case.
+ *
+ * Callers (pipeline cover filer, Universe Builder render route) all funnel
+ * through this so the universe → collection identity stays consistent across
+ * both auto-filing and explicit-render paths.
+ */
+export async function findOrCreateUniverseCollection({ universeId, universeName, description = '' }) {
+ if (!universeId || typeof universeId !== 'string') {
+ throw makeErr('universeId is required', ERR_VALIDATION);
}
- const merged = {
- ...cur,
- ...('name' in patch ? { name: patch.name } : {}),
- ...('description' in patch ? { description: patch.description } : {}),
- ...('coverKey' in patch ? { coverKey: patch.coverKey } : {}),
- updatedAt: new Date().toISOString(),
- };
- const next = [...all];
- next[idx] = merged;
- await writeAll(next);
- return merged;
+ if (typeof universeName !== 'string' || !universeName.trim()) {
+ throw makeErr('universeName is required', ERR_VALIDATION);
+ }
+ // Normalize the universeId once so lookup and storage both key on the
+ // same string. Without this, an overlong id (e.g. from a malformed
+ // share manifest) would not match the row it just created — the lookup
+ // compares the raw value but persistence sliced — and retries would
+ // pile up duplicate stamped collections.
+ const normalizedUniverseId = universeId.slice(0, UNIVERSE_ID_MAX);
+ const desiredName = universeCollectionNameFor(universeName);
+ 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.universeId === normalizedUniverseId);
+ if (linked) return linked;
+ // No universeId match — always create fresh. The runtime intentionally
+ // does NOT adopt a same-named unlinked collection here: it can't tell
+ // a true pre-link legacy bucket apart from a post-`deleteUniverse`
+ // orphan, and adopting the orphan would silently mix the deleted
+ // universe's renders into the new same-named universe.
+ //
+ // Upgrade path for pre-link installs: migration 021
+ // (`scripts/migrations/021-link-orphan-universe-collections.js`) does
+ // a one-shot name-match link at boot — safe because at install/upgrade
+ // time the orphan case doesn't exist yet. New collisions after the
+ // migration belong to "ambiguous, leave it" rather than "auto-adopt."
+ const now = new Date().toISOString();
+ const next = {
+ id: randomUUID(),
+ name: desiredName,
+ description: trimmedDescription,
+ coverKey: null,
+ universeId: normalizedUniverseId,
+ items: [],
+ createdAt: now,
+ updatedAt: now,
+ };
+ await writeAll([...all, next]);
+ return next;
+ });
+}
+
+// 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
+// items themselves are preserved — the user may still want the renders.
+// Returns the list of unlinked collection ids (empty when none matched).
+export async function unlinkCollectionsForUniverse(universeId) {
+ if (typeof universeId !== 'string' || !universeId) return [];
+ const needle = universeId.slice(0, UNIVERSE_ID_MAX);
+ return serializeFileWrite(async () => {
+ const all = await listCollections();
+ const matches = all
+ .map((c, i) => (c.universeId === 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], universeId: null, updatedAt: now };
+ unlinkedIds.push(all[i].id);
+ }
+ await writeAll(next);
+ return unlinkedIds;
+ });
+}
+
+// Cascade a universe rename to its linked collection(s). Skips the
+// rename-lock guard in updateCollection by writing the name directly — the
+// lock exists to block user-driven renames, not system-driven cascades from
+// the universe rename itself. Renames EVERY collection linked to this
+// universe, not just the first match: hand-edited state or a pre-
+// serialization race could have left duplicate linked rows behind, and the
+// stragglers would otherwise stay rename-locked under the old name forever.
+// Returns the first updated collection (back-compat) — callers that need the
+// full list can re-read after.
+export async function renameCollectionForUniverse(universeId, newUniverseName) {
+ if (typeof universeId !== 'string' || !universeId) return null;
+ const needle = universeId.slice(0, UNIVERSE_ID_MAX);
+ return serializeFileWrite(async () => {
+ const all = await listCollections();
+ const matchIdxs = all
+ .map((c, i) => (c.universeId === needle ? i : -1))
+ .filter((i) => i >= 0);
+ if (!matchIdxs.length) return null;
+ const desired = universeCollectionNameFor(newUniverseName);
+ 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]];
+ });
+}
+
+export async function updateCollection(id, patch) {
+ return serializeFileWrite(async () => {
+ const all = await listCollections();
+ const idx = all.findIndex((c) => c.id === id);
+ if (idx < 0) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);
+ const cur = all[idx];
+ // Product/UI constraint: universe-linked collections own their visible
+ // name. The name is the user-facing identity of a universe's bucket, so
+ // renaming it independent of the universe is confusing — the supported
+ // workflow is renaming the universe (which cascades down via
+ // renameCollectionForUniverse). Routing is by `universeId` regardless;
+ // this lock exists to keep what the user sees consistent with the
+ // universe's name, not to prevent routing forks.
+ if ('name' in patch && cur.universeId && patch.name !== cur.name) {
+ throw makeErr(
+ 'This collection is linked to a Universe — rename the universe 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.
+ if (patch.coverKey != null && !cur.items.find((it) => itemKey(it) === patch.coverKey)) {
+ throw makeErr('coverKey must reference an item in this collection', ERR_VALIDATION);
+ }
+ const merged = {
+ ...cur,
+ ...('name' in patch ? { name: patch.name } : {}),
+ ...('description' in patch ? { description: patch.description } : {}),
+ ...('coverKey' in patch ? { coverKey: patch.coverKey } : {}),
+ updatedAt: new Date().toISOString(),
+ };
+ const next = [...all];
+ next[idx] = merged;
+ await writeAll(next);
+ return merged;
+ });
}
export async function deleteCollection(id) {
- const all = await listCollections();
- if (!all.find((c) => c.id === id)) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);
- await writeAll(all.filter((c) => c.id !== id));
+ const deletedUniverseId = 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;
+ });
+ // Mirror addItem/removeItem/bulkUpdateCollectionItems — universe-linked
+ // shares need to know membership changed so the subscriber doesn't keep
+ // publishing the deleted collection's contents until an unrelated edit
+ // fires. Emit outside the serialized critical section so subscribers'
+ // own reads don't deadlock the tail.
+ if (deletedUniverseId) emitRecordUpdated('universe', deletedUniverseId);
return { id };
}
@@ -239,25 +459,30 @@ const validateItemInput = (item) => {
export async function addItem(id, item) {
const { kind, ref } = validateItemInput(item);
- const all = await listCollections();
- const idx = all.findIndex((c) => c.id === id);
- if (idx < 0) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);
- const cur = all[idx];
- const key = `${kind}:${ref}`;
- if (cur.items.find((it) => itemKey(it) === key)) {
- throw makeErr(`Item already in collection: ${key}`, ERR_DUPLICATE);
- }
- if (cur.items.length >= ITEMS_MAX) {
- throw makeErr(`Collection full (limit ${ITEMS_MAX})`, ERR_VALIDATION);
- }
- const merged = {
- ...cur,
- items: [...cur.items, { kind, ref, addedAt: new Date().toISOString() }],
- updatedAt: new Date().toISOString(),
- };
- const next = [...all];
- next[idx] = merged;
- await writeAll(next);
+ const merged = await serializeFileWrite(async () => {
+ const all = await listCollections();
+ const idx = all.findIndex((c) => c.id === id);
+ if (idx < 0) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);
+ const cur = all[idx];
+ const key = `${kind}:${ref}`;
+ if (cur.items.find((it) => itemKey(it) === key)) {
+ throw makeErr(`Item already in collection: ${key}`, ERR_DUPLICATE);
+ }
+ if (cur.items.length >= ITEMS_MAX) {
+ throw makeErr(`Collection full (limit ${ITEMS_MAX})`, ERR_VALIDATION);
+ }
+ const updated = {
+ ...cur,
+ items: [...cur.items, { kind, ref, addedAt: new Date().toISOString() }],
+ updatedAt: new Date().toISOString(),
+ };
+ const next = [...all];
+ next[idx] = updated;
+ await writeAll(next);
+ return updated;
+ });
+ // 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);
return merged;
}
@@ -293,73 +518,79 @@ export async function bulkUpdateCollectionItems(id, { add = [], remove = [] } =
}
}
- const all = await listCollections();
- const idx = all.findIndex((c) => c.id === id);
- if (idx < 0) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);
- const cur = all[idx];
-
- const removeSet = new Set(remove);
- const remainingItems = cur.items.filter((it) => !removeSet.has(itemKey(it)));
- const removed = cur.items.length - remainingItems.length;
-
- // Dedupe `add` against itself AND against items that survived the removal.
- // This is intentionally tolerant — re-adding an existing item is a no-op
- // rather than an error, so a multi-select Move that overlaps with prior
- // membership stays idempotent.
- const presentKeys = new Set(remainingItems.map(itemKey));
- const now = new Date().toISOString();
- const additions = [];
- for (const { kind, ref } of cleanAdd) {
- const key = `${kind}:${ref}`;
- if (presentKeys.has(key)) continue;
- presentKeys.add(key);
- additions.push({ kind, ref, addedAt: now });
- }
+ const result = await serializeFileWrite(async () => {
+ const all = await listCollections();
+ const idx = all.findIndex((c) => c.id === id);
+ if (idx < 0) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);
+ const cur = all[idx];
- const nextItems = [...remainingItems, ...additions];
- if (nextItems.length > ITEMS_MAX) {
- throw makeErr(`Collection full (limit ${ITEMS_MAX})`, ERR_VALIDATION);
- }
+ const removeSet = new Set(remove);
+ const remainingItems = cur.items.filter((it) => !removeSet.has(itemKey(it)));
+ const removed = cur.items.length - remainingItems.length;
- // Drop a cover that pointed at a now-removed item — matches the
- // single-item removeItem path so the cover never dangles after a batch.
- const coverKey = cur.coverKey && removeSet.has(cur.coverKey) ? null : cur.coverKey;
-
- const merged = {
- ...cur,
- items: nextItems,
- coverKey,
- updatedAt: now,
- };
- const next = [...all];
- next[idx] = merged;
- await writeAll(next);
- if (merged.universeId && (additions.length || removed)) {
- emitRecordUpdated('universe', merged.universeId);
+ // Dedupe `add` against itself AND against items that survived the removal.
+ // This is intentionally tolerant — re-adding an existing item is a no-op
+ // rather than an error, so a multi-select Move that overlaps with prior
+ // membership stays idempotent.
+ const presentKeys = new Set(remainingItems.map(itemKey));
+ const now = new Date().toISOString();
+ const additions = [];
+ for (const { kind, ref } of cleanAdd) {
+ const key = `${kind}:${ref}`;
+ if (presentKeys.has(key)) continue;
+ presentKeys.add(key);
+ additions.push({ kind, ref, addedAt: now });
+ }
+
+ const nextItems = [...remainingItems, ...additions];
+ if (nextItems.length > ITEMS_MAX) {
+ throw makeErr(`Collection full (limit ${ITEMS_MAX})`, ERR_VALIDATION);
+ }
+
+ // Drop a cover that pointed at a now-removed item — matches the
+ // single-item removeItem path so the cover never dangles after a batch.
+ const coverKey = cur.coverKey && removeSet.has(cur.coverKey) ? null : cur.coverKey;
+
+ const merged = {
+ ...cur,
+ items: nextItems,
+ coverKey,
+ updatedAt: now,
+ };
+ const next = [...all];
+ next[idx] = merged;
+ await writeAll(next);
+ return { collection: merged, added: additions.length, removed };
+ });
+ if (result.collection.universeId && (result.added || result.removed)) {
+ emitRecordUpdated('universe', result.collection.universeId);
}
- return { collection: merged, added: additions.length, removed };
+ return result;
}
export async function removeItem(id, key) {
- const all = await listCollections();
- const idx = all.findIndex((c) => c.id === id);
- if (idx < 0) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);
- const cur = all[idx];
- const before = cur.items.length;
- const items = cur.items.filter((it) => itemKey(it) !== key);
- if (items.length === before) throw makeErr(`Item not in collection: ${key}`, ERR_NOT_FOUND);
- const merged = {
- ...cur,
- items,
- // Drop the cover if it pointed at the removed item — sanitizeCollection
- // would do this on the next read, but doing it here keeps the in-memory
- // return consistent with what's persisted.
- coverKey: cur.coverKey === key ? null : cur.coverKey,
- updatedAt: new Date().toISOString(),
- };
- const next = [...all];
- next[idx] = merged;
- await writeAll(next);
+ const merged = await serializeFileWrite(async () => {
+ const all = await listCollections();
+ const idx = all.findIndex((c) => c.id === id);
+ if (idx < 0) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);
+ const cur = all[idx];
+ const before = cur.items.length;
+ const items = cur.items.filter((it) => itemKey(it) !== key);
+ if (items.length === before) throw makeErr(`Item not in collection: ${key}`, ERR_NOT_FOUND);
+ const updated = {
+ ...cur,
+ items,
+ // Drop the cover if it pointed at the removed item — sanitizeCollection
+ // would do this on the next read, but doing it here keeps the in-memory
+ // return consistent with what's persisted.
+ coverKey: cur.coverKey === key ? null : cur.coverKey,
+ updatedAt: new Date().toISOString(),
+ };
+ const next = [...all];
+ next[idx] = updated;
+ await writeAll(next);
+ return updated;
+ });
if (merged.universeId) emitRecordUpdated('universe', merged.universeId);
return merged;
}
diff --git a/server/services/mediaCollections.test.js b/server/services/mediaCollections.test.js
index bc5cc67d13..a1505939e4 100644
--- a/server/services/mediaCollections.test.js
+++ b/server/services/mediaCollections.test.js
@@ -74,6 +74,38 @@ describe('mediaCollections service', () => {
expect(await svc.listCollections()).toEqual([]);
});
+ it('deleteCollection emits recordUpdated on the universe when the deleted collection was 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.findOrCreateUniverseCollection({
+ universeId: 'u-1', universeName: 'Foo',
+ });
+ events.length = 0; // ignore the create-time emit
+ await svc.deleteCollection(linked.id);
+ expect(events).toContainEqual(expect.objectContaining({ recordKind: 'universe', recordId: 'u-1' }));
+ } finally {
+ recordEvents.off('updated', listener);
+ }
+ });
+
+ it('deleteCollection does NOT emit when the deleted collection was unlinked', async () => {
+ const events = [];
+ const { recordEvents } = await import('./sharing/recordEvents.js');
+ const listener = (evt) => events.push(evt);
+ recordEvents.on('updated', listener);
+ try {
+ const c = await svc.createCollection({ name: 'Orphan' });
+ events.length = 0;
+ await svc.deleteCollection(c.id);
+ expect(events).toEqual([]);
+ } finally {
+ recordEvents.off('updated', listener);
+ }
+ });
+
it('findOrCreateCollectionByName returns the existing collection on case-insensitive match', async () => {
const a = await svc.createCollection({ name: 'World: Foo' });
const reused = await svc.findOrCreateCollectionByName({ name: ' world: foo ' });
@@ -180,6 +212,289 @@ describe('mediaCollections service', () => {
});
});
+ describe('universe-linked collections', () => {
+ it('updateCollection rejects a name change when the collection is universe-linked', async () => {
+ const linked = await svc.findOrCreateCollectionByName({
+ name: 'Universe: Foo', universeId: 'u-1',
+ });
+ await expect(svc.updateCollection(linked.id, { name: 'Renamed' }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ // Other patches (coverKey, description) still go through.
+ const updated = await svc.updateCollection(linked.id, { description: 'new desc' });
+ expect(updated.description).toBe('new desc');
+ });
+
+ it('updateCollection allows a same-name PATCH (no-op) on universe-linked collections', async () => {
+ const linked = await svc.findOrCreateCollectionByName({
+ name: 'Universe: Foo', universeId: 'u-1',
+ });
+ const result = await svc.updateCollection(linked.id, { name: linked.name });
+ expect(result.name).toBe('Universe: Foo');
+ });
+
+ it('universeCollectionNameFor produces the canonical "Universe: <name>" string and truncates', () => {
+ expect(svc.universeCollectionNameFor('Foo')).toBe('Universe: Foo');
+ const long = 'x'.repeat(200);
+ expect(svc.universeCollectionNameFor(long).length).toBe(svc.NAME_MAX_LENGTH);
+ });
+
+ it('findCollectionByUniverseId locates the linked collection (or returns null)', async () => {
+ expect(await svc.findCollectionByUniverseId('u-ghost')).toBeNull();
+ const linked = await svc.findOrCreateCollectionByName({
+ name: 'Universe: Foo', universeId: 'u-1',
+ });
+ const found = await svc.findCollectionByUniverseId('u-1');
+ expect(found?.id).toBe(linked.id);
+ });
+
+ it('renameCollectionForUniverse cascades a new name onto the linked collection', async () => {
+ const linked = await svc.findOrCreateCollectionByName({
+ name: 'Universe: Foo', universeId: 'u-1',
+ });
+ const updated = await svc.renameCollectionForUniverse('u-1', 'Bar');
+ expect(updated.id).toBe(linked.id);
+ expect(updated.name).toBe('Universe: Bar');
+ const fresh = await svc.getCollection(linked.id);
+ expect(fresh.name).toBe('Universe: Bar');
+ });
+
+ it('renameCollectionForUniverse is a no-op when no linked collection exists', async () => {
+ const result = await svc.renameCollectionForUniverse('u-nope', 'Bar');
+ expect(result).toBeNull();
+ });
+
+ it('renameCollectionForUniverse no-ops when the name already matches', async () => {
+ const linked = await svc.findOrCreateCollectionByName({
+ name: 'Universe: Foo', universeId: 'u-1',
+ });
+ const result = await svc.renameCollectionForUniverse('u-1', 'Foo');
+ expect(result.name).toBe(linked.name);
+ expect(result.updatedAt).toBe(linked.updatedAt);
+ });
+
+ it('renameCollectionForUniverse updates ALL matching collections (handles hand-edited duplicates)', async () => {
+ // Two linked collections with the same universeId — could happen from
+ // a pre-serialization race or a hand-edited file. Both must be
+ // renamed; otherwise the straggler stays rename-locked under the
+ // stale name.
+ const a = await svc.findOrCreateCollectionByName({
+ name: 'Universe: OldName', universeId: 'u-1',
+ });
+ fileStore.set('/mock/data/media-collections.json', {
+ collections: [
+ a,
+ { ...a, id: 'dup-id', name: 'Universe: OldName' },
+ ],
+ });
+ await svc.renameCollectionForUniverse('u-1', 'NewName');
+ const all = await svc.listCollections();
+ const linked = all.filter((c) => c.universeId === 'u-1');
+ expect(linked).toHaveLength(2);
+ expect(linked.map((c) => c.name).sort()).toEqual([
+ 'Universe: NewName', 'Universe: NewName',
+ ]);
+ });
+
+ it('unlinkCollectionsForUniverse clears the universeId on linked collections (preserves items)', async () => {
+ const linked = await svc.findOrCreateCollectionByName({
+ name: 'Universe: Foo', universeId: 'u-1',
+ });
+ await svc.addItem(linked.id, { kind: 'image', ref: 'art.png' });
+ const cleared = await svc.unlinkCollectionsForUniverse('u-1');
+ expect(cleared).toEqual([linked.id]);
+ const fresh = await svc.getCollection(linked.id);
+ expect(fresh.universeId).toBeNull();
+ expect(fresh.items).toHaveLength(1);
+ // Lock released — renames now succeed.
+ const renamed = await svc.updateCollection(linked.id, { name: 'Orphan Bucket' });
+ expect(renamed.name).toBe('Orphan Bucket');
+ });
+
+ it('unlinkCollectionsForUniverse is a no-op when no collection is linked', async () => {
+ expect(await svc.unlinkCollectionsForUniverse('ghost')).toEqual([]);
+ expect(await svc.unlinkCollectionsForUniverse(null)).toEqual([]);
+ });
+
+ describe('findOrCreateUniverseCollection', () => {
+ it('returns the existing universeId-linked collection on second call', async () => {
+ const first = await svc.findOrCreateUniverseCollection({
+ universeId: 'u-1', universeName: 'Foo',
+ });
+ const second = await svc.findOrCreateUniverseCollection({
+ universeId: 'u-1', universeName: 'Foo',
+ });
+ expect(second.id).toBe(first.id);
+ expect(await svc.listCollections()).toHaveLength(1);
+ });
+
+ it('does NOT adopt an unlinked same-name collection — creates a fresh stamped bucket', async () => {
+ // The unlinked legacy bucket might be (a) a true pre-link legacy
+ // collection OR (b) an orphan left behind by deleteUniverse. We
+ // can't tell them apart, and adopting (b) would silently mix the
+ // deleted universe's renders into the new same-named universe.
+ const legacy = await svc.createCollection({ name: 'Universe: Foo' });
+ const linked = await svc.findOrCreateUniverseCollection({
+ universeId: 'u-1', universeName: 'Foo',
+ });
+ expect(linked.id).not.toBe(legacy.id);
+ expect(linked.universeId).toBe('u-1');
+ // Both collections exist independently.
+ expect(await svc.listCollections()).toHaveLength(2);
+ });
+
+ it('does NOT re-adopt a post-deleteUniverse orphan when a new same-named universe arrives', async () => {
+ // Stand in for the deleteUniverse flow: link, fill, then unlink.
+ const first = await svc.findOrCreateUniverseCollection({
+ universeId: 'u-A', universeName: 'Cosmos',
+ });
+ await svc.addItem(first.id, { kind: 'image', ref: 'oldA.png' });
+ await svc.unlinkCollectionsForUniverse('u-A');
+ // A brand-new universe with the same display name renders for the
+ // first time. The orphan still carries the canonical name, but
+ // must NOT be adopted — otherwise oldA.png would silently appear
+ // in the new universe's bucket.
+ const fresh = await svc.findOrCreateUniverseCollection({
+ universeId: 'u-B', universeName: 'Cosmos',
+ });
+ expect(fresh.id).not.toBe(first.id);
+ expect(fresh.universeId).toBe('u-B');
+ expect(fresh.items).toEqual([]);
+ // The orphan kept its items — user can manually relink or rename.
+ const orphan = await svc.getCollection(first.id);
+ expect(orphan.universeId).toBeNull();
+ expect(orphan.items.map((it) => it.ref)).toEqual(['oldA.png']);
+ });
+
+ it('refuses to adopt a same-name collection already linked to a different universe', async () => {
+ const owned = await svc.findOrCreateUniverseCollection({
+ universeId: 'u-A', universeName: 'Twin',
+ });
+ const own = await svc.findOrCreateUniverseCollection({
+ universeId: 'u-B', universeName: 'Twin',
+ });
+ expect(own.id).not.toBe(owned.id);
+ expect(own.universeId).toBe('u-B');
+ expect(await svc.listCollections()).toHaveLength(2);
+ });
+
+ it('survives a universe rename — same universeId still resolves to the linked bucket', async () => {
+ const first = await svc.findOrCreateUniverseCollection({
+ universeId: 'u-1', universeName: 'OldName',
+ });
+ const reuse = await svc.findOrCreateUniverseCollection({
+ universeId: 'u-1', universeName: 'NewName',
+ });
+ expect(reuse.id).toBe(first.id);
+ });
+
+ it('does NOT reconcile a drifted name on universeId-match path', async () => {
+ // The caller-supplied universeName can be stale (a snapshot taken
+ // before this call entered the write tail), so reconciling here
+ // could revert a concurrent rename cascade. The cascade itself
+ // (renameCollectionForUniverse) is the canonical path for name
+ // updates; a stale name from a failed cascade survives until the
+ // user re-triggers it.
+ const first = await svc.findOrCreateUniverseCollection({
+ universeId: 'u-1', universeName: 'NewName',
+ });
+ const current = await svc.listCollections();
+ current[0] = { ...current[0], name: 'Universe: SomeOtherName' };
+ fileStore.set('/mock/data/media-collections.json', { collections: current });
+ const found = await svc.findOrCreateUniverseCollection({
+ universeId: 'u-1', universeName: 'NewName',
+ });
+ expect(found.id).toBe(first.id);
+ // The drifted name is preserved — caller doesn't get to reconcile.
+ expect(found.name).toBe('Universe: SomeOtherName');
+ });
+
+ it('serializes concurrent first-time filings (no race-induced duplicate or orphan)', async () => {
+ // Same-universe race: cover + back-cover for the first time.
+ await Promise.all([
+ svc.findOrCreateUniverseCollection({ universeId: 'u-1', universeName: 'Race' }),
+ svc.findOrCreateUniverseCollection({ universeId: 'u-1', universeName: 'Race' }),
+ ]);
+ const linked = await svc.findCollectionByUniverseId('u-1');
+ expect(linked).not.toBeNull();
+ expect(await svc.listCollections()).toHaveLength(1);
+ });
+
+ it('serializes concurrent first-time filings for two universes that share a display name', async () => {
+ // Both universes named "Twin" but with different ids. Without the
+ // mutex, both first-time creates would observe pre-create state and
+ // the second writeAll would clobber the first.
+ await Promise.all([
+ svc.findOrCreateUniverseCollection({ universeId: 'u-A', universeName: 'Twin' }),
+ svc.findOrCreateUniverseCollection({ universeId: 'u-B', universeName: 'Twin' }),
+ ]);
+ const a = await svc.findCollectionByUniverseId('u-A');
+ const b = await svc.findCollectionByUniverseId('u-B');
+ expect(a).not.toBeNull();
+ expect(b).not.toBeNull();
+ expect(a.id).not.toBe(b.id);
+ expect(await svc.listCollections()).toHaveLength(2);
+ });
+
+ it('requires universeId and universeName', async () => {
+ await expect(svc.findOrCreateUniverseCollection({ universeName: 'X' }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ await expect(svc.findOrCreateUniverseCollection({ universeId: 'u-1' }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('normalizes an overlong universeId once — lookup and storage agree (no duplicate-on-retry)', async () => {
+ // Caller passes a universeId longer than UNIVERSE_ID_MAX (80).
+ // Without the normalize-once fix, the create path slices for
+ // storage but the lookup compares the raw value — so the second
+ // call wouldn't find the row it just created and would mint a
+ // duplicate.
+ const overlong = 'u-' + 'x'.repeat(200);
+ const first = await svc.findOrCreateUniverseCollection({
+ universeId: overlong, universeName: 'Foo',
+ });
+ const second = await svc.findOrCreateUniverseCollection({
+ universeId: overlong, universeName: 'Foo',
+ });
+ expect(second.id).toBe(first.id);
+ expect(await svc.listCollections()).toHaveLength(1);
+ // The stamped id is the sliced value, not the raw overlong input.
+ expect(first.universeId.length).toBeLessThanOrEqual(80);
+ });
+ });
+
+ describe('cross-path write serialization', () => {
+ it('addItem racing unlinkCollectionsForUniverse — neither drops items', async () => {
+ // Two completely different write paths racing on the same file.
+ // Without the file-level write tail, unlink's stale snapshot would
+ // clobber the in-flight addItem that completed first.
+ const linked = await svc.findOrCreateUniverseCollection({
+ universeId: 'u-1', universeName: 'Foo',
+ });
+ await Promise.all([
+ svc.addItem(linked.id, { kind: 'image', ref: 'race-1.png' }),
+ svc.unlinkCollectionsForUniverse('u-1'),
+ svc.addItem(linked.id, { kind: 'image', ref: 'race-2.png' }),
+ ]);
+ const fresh = await svc.getCollection(linked.id);
+ const refs = fresh.items.map((it) => it.ref).sort();
+ expect(refs).toEqual(['race-1.png', 'race-2.png']);
+ });
+
+ it('rename + addItem from two paths — both end states persist', async () => {
+ const linked = await svc.findOrCreateUniverseCollection({
+ universeId: 'u-1', universeName: 'Old',
+ });
+ await Promise.all([
+ svc.addItem(linked.id, { kind: 'image', ref: 'cover.png' }),
+ svc.renameCollectionForUniverse('u-1', 'New'),
+ ]);
+ const fresh = await svc.getCollection(linked.id);
+ expect(fresh.name).toBe('Universe: New');
+ expect(fresh.items.map((it) => it.ref)).toEqual(['cover.png']);
+ });
+ });
+ });
+
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.js
index 609743c894..54cb4b6712 100644
--- a/server/services/pipeline/comicPagesFilenameHook.js
+++ b/server/services/pipeline/comicPagesFilenameHook.js
@@ -16,6 +16,8 @@
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';
// Slot record for a legacy in-flight completion (job enqueued before the
// proof/final split). `job.params` carries the originally-requested width
@@ -100,7 +102,27 @@ const hook = createFilenameHook({
}
return null;
},
+ // Post-stamp side effect: when an issue COVER or BACK-COVER render
+ // commits, file the image into the owning universe's media collection.
+ // Panels are excluded — the universe bucket is for poster-style artwork,
+ // not every interior frame. Gating on `onStamped` (rather than a parallel
+ // mediaJobEvents listener) means stale renders that the `applyFilename`
+ // skipped because the slot's active jobId changed AND failed writes both
+ // skip filing automatically — there's a single success path.
+ onStamped: async ({ parsed, filename }) => {
+ 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 });
+ },
});
-export const initComicPagesFilenameHook = hook.init;
-export const __testing = hook.__testing;
+export function initComicPagesFilenameHook() {
+ hook.init();
+}
+
+export const __testing = {
+ reset() {
+ hook.__testing.reset();
+ },
+};
diff --git a/server/services/pipeline/coverFilenameHooks.integration.test.js b/server/services/pipeline/coverFilenameHooks.integration.test.js
new file mode 100644
index 0000000000..35f050bcd1
--- /dev/null
+++ b/server/services/pipeline/coverFilenameHooks.integration.test.js
@@ -0,0 +1,323 @@
+/**
+ * Hook-level integration tests for the cover/back-cover auto-file feature.
+ *
+ * `coverUniverseFiler.test.js` covers the helper in isolation. These tests
+ * cover the wiring around it — owner parsing, the
+ * `reducerStamped && writeOk` gate (or `applyFilename → onStamped` for the
+ * comic-pages factory), and the `mediaJobEvents` listener path. The hooks'
+ * handlers run inside a `void (async () => {})` IIFE, so each test waits
+ * for the post-emit side effect rather than awaiting the handler.
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const tempData = mkdtempSync(join(tmpdir(), 'portos-coverhook-test-'));
+
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ return new Proxy(actual, {
+ get(target, prop) {
+ if (prop === 'PATHS') return { ...actual.PATHS, data: tempData };
+ return target[prop];
+ },
+ });
+});
+
+// Mock the series + issue + universe lookups so the hooks see deterministic
+// state without bringing the full series/issue stack into scope. The
+// universe lookup specifically is read TWICE inside coverUniverseFiler
+// (once at queue entry, once as a delete-race guard) — we want both calls
+// to see the same record in the happy path.
+const seriesStore = new Map();
+const issuesStore = new Map();
+const universeStore = new Map();
+const seasonStore = new Map(); // `${seriesId}::${seasonId}` → season payload
+
+const updateSeasonOnSeriesMock = vi.fn(async (seriesId, seasonId, patchFn) => {
+ const key = `${seriesId}::${seasonId}`;
+ const cur = seasonStore.get(key);
+ if (!cur) return null;
+ const patch = patchFn(cur);
+ if (!patch || Object.keys(patch).length === 0) return null;
+ const next = { ...cur, ...patch };
+ seasonStore.set(key, next);
+ return next;
+});
+
+const updateStageWithLatestMock = vi.fn(async (issueId, _stageId, computeFn) => {
+ const issue = issuesStore.get(issueId);
+ if (!issue) throw new Error('issue not found');
+ const currentStage = issue.stages?.comicPages || null;
+ const patch = computeFn(currentStage);
+ if (!patch || Object.keys(patch).length === 0) return issue;
+ issue.stages = issue.stages || {};
+ issue.stages.comicPages = { ...currentStage, ...patch };
+ return issue;
+});
+
+vi.mock('./series.js', () => ({
+ getSeries: vi.fn(async (id) => seriesStore.get(id) || null),
+ updateSeasonOnSeries: updateSeasonOnSeriesMock,
+}));
+
+vi.mock('./issues.js', () => ({
+ getIssue: vi.fn(async (id) => issuesStore.get(id) || null),
+ updateStageWithLatest: updateStageWithLatestMock,
+}));
+
+vi.mock('../universeBuilder.js', () => ({
+ getUniverse: vi.fn(async (id) => universeStore.get(id) || null),
+}));
+
+// Real imports below — these read through the mocks above.
+const { mediaJobEvents } = await import('../mediaJobQueue/index.js');
+const collections = await import('../mediaCollections.js');
+const seasonHook = await import('./seasonCoverFilenameHook.js');
+const comicHook = await import('./comicPagesFilenameHook.js');
+const { buildSeasonCoverOwner, buildComicPagesOwner } = await import('./owners.js');
+
+async function waitFor(predicate, { timeoutMs = 1000, intervalMs = 5 } = {}) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (await predicate()) return;
+ await new Promise((r) => setTimeout(r, intervalMs));
+ }
+ throw new Error('waitFor: predicate never became true');
+}
+
+beforeEach(() => {
+ rmSync(tempData, { recursive: true, force: true });
+ mkdirSync(tempData, { recursive: true });
+ seriesStore.clear();
+ issuesStore.clear();
+ universeStore.clear();
+ seasonStore.clear();
+ updateSeasonOnSeriesMock.mockClear();
+ updateStageWithLatestMock.mockClear();
+ seasonHook.__testing.reset();
+ comicHook.__testing.reset();
+ seasonHook.initSeasonCoverFilenameHook();
+ comicHook.initComicPagesFilenameHook();
+});
+
+afterEach(() => {
+ seasonHook.__testing.reset();
+ comicHook.__testing.reset();
+});
+
+describe('seasonCoverFilenameHook — universe collection auto-file', () => {
+ it('files the cover into the universe collection when the active jobId still matches', async () => {
+ const universeId = 'u-season-1';
+ const seriesId = 'ser-1';
+ const seasonId = 'season-1';
+ universeStore.set(universeId, { id: universeId, name: 'Foo' });
+ seriesStore.set(seriesId, { id: seriesId, universeId });
+ seasonStore.set(`${seriesId}::${seasonId}`, {
+ cover: { proofImage: { jobId: 'job-active' } },
+ });
+
+ mediaJobEvents.emit('completed', {
+ id: 'job-active',
+ kind: 'image',
+ result: { filename: 'cover-final.png' },
+ owner: buildSeasonCoverOwner({ seriesId, seasonId, target: 'cover', variant: 'proof' }),
+ });
+
+ await waitFor(async () => {
+ const linked = await collections.findCollectionByUniverseId(universeId);
+ return linked?.items?.some((it) => it.ref === 'cover-final.png');
+ });
+ const linked = await collections.findCollectionByUniverseId(universeId);
+ expect(linked.items.map((it) => it.ref)).toEqual(['cover-final.png']);
+ });
+
+ it('does NOT file when the slot jobId no longer matches (stale render lands after a re-render)', async () => {
+ const universeId = 'u-season-2';
+ const seriesId = 'ser-2';
+ const seasonId = 'season-2';
+ universeStore.set(universeId, { id: universeId, name: 'Foo' });
+ seriesStore.set(seriesId, { id: seriesId, universeId });
+ seasonStore.set(`${seriesId}::${seasonId}`, {
+ // The slot is on a NEWER jobId — our completion is stale.
+ cover: { proofImage: { jobId: 'job-newer' } },
+ });
+
+ mediaJobEvents.emit('completed', {
+ id: 'job-stale',
+ kind: 'image',
+ result: { filename: 'stale.png' },
+ owner: buildSeasonCoverOwner({ seriesId, seasonId, target: 'cover', variant: 'proof' }),
+ });
+
+ // Give the IIFE time to run; verify the universe collection never gets
+ // the stale filename. A small wait is enough — the handler's path is
+ // synchronous through await microtasks once the mocks resolve.
+ await new Promise((r) => setTimeout(r, 60));
+ const linked = await collections.findCollectionByUniverseId(universeId);
+ expect(linked).toBeNull();
+ });
+
+ it('does NOT file when the series update write fails (reducerStamped but !writeOk)', async () => {
+ const universeId = 'u-season-3';
+ const seriesId = 'ser-3';
+ const seasonId = 'season-3';
+ universeStore.set(universeId, { id: universeId, name: 'Foo' });
+ seriesStore.set(seriesId, { id: seriesId, universeId });
+ seasonStore.set(`${seriesId}::${seasonId}`, {
+ cover: { proofImage: { jobId: 'job-write-fail' } },
+ });
+ // Force the write to throw after the reducer has chosen to stamp.
+ updateSeasonOnSeriesMock.mockImplementationOnce(async (_s, _se, patchFn) => {
+ patchFn({ cover: { proofImage: { jobId: 'job-write-fail' } } }); // reducer runs and stamps flag
+ throw new Error('boom: simulated write failure');
+ });
+
+ mediaJobEvents.emit('completed', {
+ id: 'job-write-fail',
+ kind: 'image',
+ result: { filename: 'should-not-land.png' },
+ owner: buildSeasonCoverOwner({ seriesId, seasonId, target: 'cover', variant: 'proof' }),
+ });
+
+ await new Promise((r) => setTimeout(r, 60));
+ const linked = await collections.findCollectionByUniverseId(universeId);
+ expect(linked).toBeNull();
+ });
+
+ it('parses owner correctly — non-season-cover owners are ignored', async () => {
+ const universeId = 'u-season-4';
+ const seriesId = 'ser-4';
+ universeStore.set(universeId, { id: universeId, name: 'Foo' });
+ seriesStore.set(seriesId, { id: seriesId, universeId });
+
+ mediaJobEvents.emit('completed', {
+ id: 'job-x',
+ kind: 'image',
+ result: { filename: 'irrelevant.png' },
+ // Wrong namespace — should not be picked up by the season hook.
+ owner: 'pipeline:other:not-a-season-cover',
+ });
+
+ await new Promise((r) => setTimeout(r, 60));
+ const linked = await collections.findCollectionByUniverseId(universeId);
+ expect(linked).toBeNull();
+ });
+});
+
+describe('comicPagesFilenameHook — universe collection auto-file', () => {
+ it('files the issue cover into the universe collection on completion', async () => {
+ const universeId = 'u-comic-1';
+ const seriesId = 'ser-comic-1';
+ const issueId = 'iss-1';
+ universeStore.set(universeId, { id: universeId, name: 'Bar' });
+ seriesStore.set(seriesId, { id: seriesId, universeId });
+ issuesStore.set(issueId, {
+ id: issueId,
+ seriesId,
+ stages: {
+ comicPages: {
+ cover: { proofImage: { jobId: 'job-cover-active' } },
+ },
+ },
+ });
+
+ mediaJobEvents.emit('completed', {
+ id: 'job-cover-active',
+ kind: 'image',
+ result: { filename: 'issue-cover.png' },
+ owner: buildComicPagesOwner({ issueId, target: 'cover', variant: 'proof' }),
+ });
+
+ await waitFor(async () => {
+ const linked = await collections.findCollectionByUniverseId(universeId);
+ return linked?.items?.some((it) => it.ref === 'issue-cover.png');
+ });
+ });
+
+ it('files the issue back-cover on completion (separate target from cover)', async () => {
+ const universeId = 'u-comic-2';
+ const seriesId = 'ser-comic-2';
+ const issueId = 'iss-2';
+ universeStore.set(universeId, { id: universeId, name: 'Baz' });
+ seriesStore.set(seriesId, { id: seriesId, universeId });
+ issuesStore.set(issueId, {
+ id: issueId,
+ seriesId,
+ stages: {
+ comicPages: {
+ backCover: { proofImage: { jobId: 'job-back-active' } },
+ },
+ },
+ });
+
+ mediaJobEvents.emit('completed', {
+ id: 'job-back-active',
+ kind: 'image',
+ result: { filename: 'issue-back.png' },
+ owner: buildComicPagesOwner({ issueId, target: 'backCover', variant: 'proof' }),
+ });
+
+ await waitFor(async () => {
+ const linked = await collections.findCollectionByUniverseId(universeId);
+ return linked?.items?.some((it) => it.ref === 'issue-back.png');
+ });
+ });
+
+ it('does NOT file an interior PAGE render — only cover/backCover get universe-bucketed', async () => {
+ const universeId = 'u-comic-3';
+ const seriesId = 'ser-comic-3';
+ const issueId = 'iss-3';
+ universeStore.set(universeId, { id: universeId, name: 'Foo' });
+ seriesStore.set(seriesId, { id: seriesId, universeId });
+ issuesStore.set(issueId, {
+ id: issueId,
+ seriesId,
+ stages: {
+ comicPages: {
+ pages: [{ proofImage: { jobId: 'job-page-0' } }],
+ },
+ },
+ });
+
+ mediaJobEvents.emit('completed', {
+ id: 'job-page-0',
+ kind: 'image',
+ result: { filename: 'page-0.png' },
+ owner: buildComicPagesOwner({ issueId, target: 'page', pageIndex: 0, variant: 'proof' }),
+ });
+
+ await new Promise((r) => setTimeout(r, 60));
+ const linked = await collections.findCollectionByUniverseId(universeId);
+ expect(linked).toBeNull();
+ });
+
+ it('does NOT file when the slot jobId no longer matches (stale render after re-render)', async () => {
+ const universeId = 'u-comic-4';
+ const seriesId = 'ser-comic-4';
+ const issueId = 'iss-4';
+ universeStore.set(universeId, { id: universeId, name: 'Foo' });
+ seriesStore.set(seriesId, { id: seriesId, universeId });
+ issuesStore.set(issueId, {
+ id: issueId,
+ seriesId,
+ stages: {
+ comicPages: {
+ cover: { proofImage: { jobId: 'job-newer' } },
+ },
+ },
+ });
+
+ mediaJobEvents.emit('completed', {
+ id: 'job-stale-cover',
+ kind: 'image',
+ result: { filename: 'stale-cover.png' },
+ owner: buildComicPagesOwner({ issueId, target: 'cover', variant: 'proof' }),
+ });
+
+ await new Promise((r) => setTimeout(r, 60));
+ const linked = await collections.findCollectionByUniverseId(universeId);
+ expect(linked).toBeNull();
+ });
+});
diff --git a/server/services/pipeline/coverUniverseFiler.js b/server/services/pipeline/coverUniverseFiler.js
new file mode 100644
index 0000000000..2b5d55e1d9
--- /dev/null
+++ b/server/services/pipeline/coverUniverseFiler.js
@@ -0,0 +1,102 @@
+/**
+ * Pipeline — auto-file series/volume/issue cover renders into a Universe's
+ * media collection.
+ *
+ * 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.
+ *
+ * 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.
+ *
+ * **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.
+ */
+
+import {
+ findOrCreateUniverseCollection,
+ unlinkCollectionsForUniverse,
+ addItem,
+ ERR_DUPLICATE,
+} from '../mediaCollections.js';
+import * as seriesSvc from './series.js';
+import * as universeSvc from '../universeBuilder.js';
+
+// 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
+// quick experiments with no canon yet).
+export async function fileCoverIntoUniverseCollection({ seriesId, filename }) {
+ if (!seriesId || typeof filename !== 'string' || !filename) return;
+
+ // Pin the universeId we observed up front. After this await the series's
+ // link could change (a parallel updateSeries unlinks or re-points it);
+ // every downstream step compares against this snapshot so a mid-flight
+ // re-link doesn't mis-attribute the cover to the new universe.
+ const initialSeries = await seriesSvc.getSeries(seriesId).catch(() => null);
+ if (!initialSeries?.universeId) return;
+ const universeId = initialSeries.universeId;
+
+ // Re-read series before the universe lookup so a re-link landed during
+ // the previous await is caught before we resolve the universe payload.
+ const series = await seriesSvc.getSeries(seriesId).catch(() => null);
+ if (!series?.universeId || series.universeId !== universeId) return;
+
+ // Resolve the universe as close as possible to the create so we don't
+ // stamp a newly-created collection with stale universe details.
+ const liveUniverse = await universeSvc.getUniverse(universeId).catch(() => null);
+ if (!liveUniverse) return;
+
+ // Honor the file header's contract: failures are logged and swallowed.
+ // A findOrCreateUniverseCollection rejection (validation, I/O) would
+ // otherwise reject out of this helper and crash any direct caller that
+ // doesn't already wrap it.
+ const collection = await findOrCreateUniverseCollection({
+ universeId: liveUniverse.id,
+ universeName: liveUniverse.name,
+ description: `Renders for "${liveUniverse.name}"`,
+ }).catch((err) => {
+ console.error(`❌ cover → universe collection provision failed for ${filename}: ${err?.message || err}`);
+ return null;
+ });
+ if (!collection) return;
+
+ // File the render first, regardless of what happened to the universe
+ // mid-flight. The user's cover is real work — we never throw it away
+ // just because the universe got deleted between findOrCreate and now.
+ await addItem(collection.id, { kind: 'image', ref: filename }).catch((err) => {
+ // A duplicate just means the user re-rendered the same cover into the
+ // same slot — not an error worth surfacing.
+ if (err?.code === ERR_DUPLICATE) return;
+ console.error(`❌ cover → universe collection filing failed for ${filename}: ${err?.message || err}`);
+ });
+
+ // Delete-race recovery: deleteUniverse may have fired between the
+ // initial getUniverse and findOrCreateUniverseCollection's write,
+ // leaving the freshly-stamped collection bound to a now-deleted
+ // universeId — rename-locked with no universe to cascade from. Unlink
+ // the collection so the user can rename or delete it via normal flows;
+ // the cover added above is preserved in the (now-orphaned) bucket
+ // instead of being thrown away with the universe.
+ const stillExists = await universeSvc.getUniverse(universeId).catch(() => null);
+ if (!stillExists || stillExists.id !== liveUniverse.id) {
+ await unlinkCollectionsForUniverse(universeId).catch((err) => {
+ // Log per the file header: bookkeeping failures are swallowed but
+ // never silenced. If this unlink fails, the just-stamped collection
+ // stays bound to a deleted universeId (rename-locked) and the
+ // operator needs the log entry to find + fix it.
+ console.error(`❌ cover → universe collection orphan-unlink failed for universe=${universeId}: ${err?.message || err}`);
+ });
+ }
+}
diff --git a/server/services/pipeline/coverUniverseFiler.test.js b/server/services/pipeline/coverUniverseFiler.test.js
new file mode 100644
index 0000000000..ab5afe6868
--- /dev/null
+++ b/server/services/pipeline/coverUniverseFiler.test.js
@@ -0,0 +1,118 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const fileStore = new Map();
+
+vi.mock('../../lib/fileUtils.js', () => ({
+ PATHS: { data: '/mock/data' },
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
+ readJSONFile: vi.fn(async (path, fallback) =>
+ fileStore.has(path) ? fileStore.get(path) : fallback,
+ ),
+}));
+
+let uuidCounter = 0;
+vi.mock('crypto', async () => {
+ const actual = await vi.importActual('crypto');
+ return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
+});
+
+const collections = await import('../mediaCollections.js');
+const seriesSvc = await import('./series.js');
+const universeSvc = await import('../universeBuilder.js');
+const { fileCoverIntoUniverseCollection } = await import('./coverUniverseFiler.js');
+
+describe('fileCoverIntoUniverseCollection', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ });
+
+ it('files the cover image into the universe collection (creating it on first use)', async () => {
+ const universe = await universeSvc.createUniverse({ name: 'Foo' });
+ const series = await seriesSvc.createSeries({ name: 'My Series', universeId: universe.id });
+ await fileCoverIntoUniverseCollection({ seriesId: series.id, filename: 'cover-001.png' });
+ const linked = await collections.findCollectionByUniverseId(universe.id);
+ expect(linked?.name).toBe('Universe: Foo');
+ expect(linked?.items.map((it) => it.ref)).toEqual(['cover-001.png']);
+ });
+
+ it('reuses an existing universe-linked collection', async () => {
+ const universe = await universeSvc.createUniverse({ name: 'Foo' });
+ const existing = await collections.findOrCreateCollectionByName({
+ name: 'Universe: Foo', universeId: universe.id,
+ });
+ const series = await seriesSvc.createSeries({ name: 'S', universeId: universe.id });
+ await fileCoverIntoUniverseCollection({ seriesId: series.id, filename: 'a.png' });
+ await fileCoverIntoUniverseCollection({ seriesId: series.id, filename: 'b.png' });
+ const fresh = await collections.getCollection(existing.id);
+ expect(fresh.items.map((it) => it.ref).sort()).toEqual(['a.png', 'b.png']);
+ });
+
+ it('swallows duplicate filings silently (same cover re-rendered)', async () => {
+ const universe = await universeSvc.createUniverse({ name: 'Foo' });
+ const series = await seriesSvc.createSeries({ name: 'S', universeId: universe.id });
+ await fileCoverIntoUniverseCollection({ seriesId: series.id, filename: 'dup.png' });
+ await fileCoverIntoUniverseCollection({ seriesId: series.id, filename: 'dup.png' });
+ const linked = await collections.findCollectionByUniverseId(universe.id);
+ expect(linked.items).toHaveLength(1);
+ });
+
+ it('no-ops when the series has no universeId', async () => {
+ const series = await seriesSvc.createSeries({ name: 'S' });
+ await fileCoverIntoUniverseCollection({ seriesId: series.id, filename: 'x.png' });
+ expect(await collections.listCollections()).toEqual([]);
+ });
+
+ it('no-ops when seriesId or filename is missing', async () => {
+ await fileCoverIntoUniverseCollection({ seriesId: null, filename: 'x.png' });
+ await fileCoverIntoUniverseCollection({ seriesId: 'ser-x', filename: '' });
+ expect(await collections.listCollections()).toEqual([]);
+ });
+
+ it('no-ops when the series references a missing universe', async () => {
+ const series = await seriesSvc.createSeries({ name: 'S', universeId: 'ghost-universe' });
+ await fileCoverIntoUniverseCollection({ seriesId: series.id, filename: 'x.png' });
+ expect(await collections.listCollections()).toEqual([]);
+ });
+
+ it('never hijacks a same-named collection belonging to a different universe', async () => {
+ // Universe A already owns a "Universe: Twin" bucket.
+ const universeA = await universeSvc.createUniverse({ name: 'Twin' });
+ const ownedByA = await collections.findOrCreateCollectionByName({
+ name: 'Universe: Twin', universeId: universeA.id,
+ });
+ // Universe B (different id, same display name) renders its first cover.
+ const universeB = await universeSvc.createUniverse({ name: 'Twin' });
+ const seriesB = await seriesSvc.createSeries({ name: 'B-Series', universeId: universeB.id });
+ await fileCoverIntoUniverseCollection({ seriesId: seriesB.id, filename: 'b-cover.png' });
+ // Universe A's bucket must be untouched.
+ const a = await collections.getCollection(ownedByA.id);
+ expect(a.items).toHaveLength(0);
+ // Universe B got its own properly-stamped bucket.
+ const b = await collections.findCollectionByUniverseId(universeB.id);
+ expect(b).not.toBeNull();
+ expect(b.id).not.toBe(ownedByA.id);
+ expect(b.items.map((it) => it.ref)).toEqual(['b-cover.png']);
+ });
+
+ it('serializes concurrent filings for the same universe (no orphan collections from a race)', async () => {
+ const universe = await universeSvc.createUniverse({ name: 'Race' });
+ const series = await seriesSvc.createSeries({ name: 'S', universeId: universe.id });
+ // Two completions back-to-back before the collection exists — the
+ // shared file-level write tail in mediaCollections.js must serialize
+ // the create-or-find write so only one collection is persisted and
+ // both filenames land in it.
+ await Promise.all([
+ fileCoverIntoUniverseCollection({ seriesId: series.id, filename: 'cover.png' }),
+ fileCoverIntoUniverseCollection({ seriesId: series.id, filename: 'back.png' }),
+ ]);
+ const linked = await collections.findCollectionByUniverseId(universe.id);
+ expect(linked).not.toBeNull();
+ expect(linked.items.map((it) => it.ref).sort()).toEqual(['back.png', 'cover.png']);
+ // Only one "Universe: Race" collection — no race-induced duplicate.
+ const all = await collections.listCollections();
+ const named = all.filter((c) => c.name === 'Universe: Race');
+ expect(named).toHaveLength(1);
+ });
+});
diff --git a/server/services/pipeline/filenameHookFactory.js b/server/services/pipeline/filenameHookFactory.js
index 61f0bbbb32..83fa273e1a 100644
--- a/server/services/pipeline/filenameHookFactory.js
+++ b/server/services/pipeline/filenameHookFactory.js
@@ -13,12 +13,20 @@
* { patch, label } → stage gets the patch; label is logged
* or `null` to skip (e.g. stale jobId after a re-render — see CLAUDE.md
* "Pending socket-request tracking" for the same generation-aware idea).
+ *
+ * Optional `onStamped({ parsed, job, filename, label })` fires once *after*
+ * the stage write actually commits AND the reducer chose to stamp. Used by
+ * the comic-pages hook to file cover renders into a universe's collection
+ * — gating on commit avoids a stale-render or write-failure landing in the
+ * universe bucket. The callback is awaited inside the same outer
+ * try/catch frame as the hook, so a thrown error is logged and swallowed
+ * the same way as other hook failures (bookkeeping must not fail renders).
*/
import { mediaJobEvents } from '../mediaJobQueue/index.js';
import { updateStageWithLatest } from './issues.js';
-export function createFilenameHook({ name, stageId, kind = 'image', parseOwner, applyFilename }) {
+export function createFilenameHook({ name, stageId, kind = 'image', parseOwner, applyFilename, onStamped = null }) {
let registeredHandler = null;
const handler = (job) => {
@@ -30,7 +38,13 @@ export function createFilenameHook({ name, stageId, kind = 'image', parseOwner,
if (!parsed) return;
const shortId = String(job.id || '').slice(0, 8);
+ // Track BOTH "reducer chose to stamp" AND "write actually committed."
+ // The reducer flag alone isn't enough: if updateStageWithLatest throws
+ // *after* the reducer ran (validation, IO), the `.catch` below fires
+ // but `stampedLabel` keeps its truthy value — without `writeOk` we'd
+ // log "stamped" and fire `onStamped` for a write that never landed.
let stampedLabel = null;
+ let writeOk = false;
await updateStageWithLatest(
parsed.issueId,
stageId,
@@ -40,12 +54,17 @@ export function createFilenameHook({ name, stageId, kind = 'image', parseOwner,
stampedLabel = result.label || null;
return result.patch || {};
},
- ).catch((err) => {
+ ).then(() => { writeOk = true; }).catch((err) => {
console.error(`❌ ${name} filename hook failed for job ${shortId}: ${err?.message || err}`);
});
- if (stampedLabel) {
+ if (stampedLabel && writeOk) {
console.log(`📎 ${name} filename stamped — issue=${parsed.issueId.slice(0, 8)} ${stampedLabel} ← ${filename}`);
+ if (onStamped) {
+ await onStamped({ parsed, job, filename, label: stampedLabel }).catch((err) => {
+ console.error(`❌ ${name} onStamped hook failed for job ${shortId}: ${err?.message || err}`);
+ });
+ }
}
})().catch((err) => {
console.error(`❌ ${name} filename hook crashed: ${err?.message || err}`);
diff --git a/server/services/pipeline/seasonCoverFilenameHook.js b/server/services/pipeline/seasonCoverFilenameHook.js
index 3a2c0de482..32f5e5002d 100644
--- a/server/services/pipeline/seasonCoverFilenameHook.js
+++ b/server/services/pipeline/seasonCoverFilenameHook.js
@@ -21,6 +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';
let registeredHandler = null;
@@ -35,7 +36,12 @@ const handler = (job) => {
const shortId = String(job.id || '').slice(0, 8);
const slotKey = slotKeyForVariant(parsed.variant);
const { seriesId, seasonId, target } = parsed;
- let stamped = false;
+ // Track BOTH that the reducer chose to stamp AND that the write actually
+ // landed. Setting a flag inside the reducer alone isn't enough: a
+ // validation/IO failure in updateSeasonOnSeries would still trigger the
+ // universe filing with a filename that never persisted on the season.
+ let reducerStamped = false;
+ let writeOk = false;
await seriesSvc.updateSeasonOnSeries(seriesId, seasonId, (cur) => {
const record = cur?.[target];
@@ -45,19 +51,20 @@ const handler = (job) => {
// already — in that case dropping our completion is the correct
// behavior (the newer job's filename will overwrite ours anyway).
if (record[slotKey]?.jobId !== job.id) return {};
- stamped = true;
+ reducerStamped = true;
return {
[target]: {
...record,
[slotKey]: { ...record[slotKey], filename },
},
};
- }).catch((err) => {
+ }).then(() => { writeOk = true; }).catch((err) => {
console.error(`❌ seasonCover filename hook failed for job ${shortId}: ${err?.message || err}`);
});
- if (stamped) {
+ 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 });
}
})().catch((err) => {
console.error(`❌ seasonCover filename hook crashed: ${err?.message || err}`);
diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.js
index b68c2b0dc5..5830bfb371 100644
--- a/server/services/sharing/exporter.js
+++ b/server/services/sharing/exporter.js
@@ -218,22 +218,27 @@ function collectAssetReferences(record) {
}
/**
- * Find the media collection linked to a universe. Prefers the explicit
- * `universeId` field on the collection (added by the universe-builder
- * route); falls back to matching the conventional `Universe: <name>`
- * name. Returns null when nothing's linked.
+ * 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(() => []);
- const direct = all.find((c) => c.universeId === universe.id);
- if (direct) return direct;
- const conventional = `universe: ${(universe.name || '').toLowerCase()}`;
- const legacy = all.find((c) => (c.name || '').toLowerCase() === conventional);
- // Legacy universe-builder collections were named conventionally but did not
- // carry the explicit link. Preserve the link in the share payload so the
- // importer can restore membership instead of leaving copied assets unsorted.
- return legacy ? { ...legacy, universeId: universe.id } : null;
+ return all.find((c) => c.universeId === universe.id) || null;
}
/**
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index 4547298fd9..dfd9679c87 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -30,7 +30,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 { findOrCreateCollectionByName, addItem as addCollectionItem, ERR_DUPLICATE as COLLECTION_ERR_DUPLICATE } from '../mediaCollections.js';
+import { findOrCreateUniverseCollection, 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';
@@ -66,9 +66,13 @@ function remoteWins(localTs, remoteTs) {
/**
* Merge a manifest's `collection` payload into local state. Find-or-create
- * the collection by `universeId` (with name as a fallback), 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 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).
+ *
+ * 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.
*
* The asset blobs are NOT copied here — `copyAssetsLocally` (called in
* `processManifest`) already pulled every available asset entry. This function
@@ -77,12 +81,36 @@ function remoteWins(localTs, remoteTs) {
*/
async function mergeCollectionPayload(payload, availableAssetKeys = null) {
if (!payload?.universeId || !Array.isArray(payload.items)) return { itemsAdded: 0 };
- const collection = await findOrCreateCollectionByName({
- name: payload.name || `Universe: ${payload.universeId}`,
- description: payload.description || '',
+
+ // 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 };
+ }
+
+ // 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: findOrCreateCollectionByName failed: ${err.message}`);
+ console.log(`⚠️ sharing.importer: findOrCreateUniverseCollection failed: ${err.message}`);
return null;
});
if (!collection) return { itemsAdded: 0 };
@@ -318,12 +346,20 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =
// generated images appear alongside the universe in the recipient's UI.
let itemsAdded = 0;
let itemsDeferred = 0;
+ let collectionPendingUniverse = null;
if (manifest.collection) {
const r = await withReexportSuppressed('universe', manifest.collection.universeId, () =>
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
+ // later (independent) sync.
+ if (r.missingUniverse) collectionPendingUniverse = manifest.collection.universeId;
}
let adoptedSubscription = null;
@@ -342,6 +378,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =
overridden,
collectionItemsAdded: itemsAdded,
collectionItemsDeferred: itemsDeferred,
+ collectionPendingUniverse,
adoptedSubscription: adoptedSubscription
? { id: adoptedSubscription.id, bucketId: adoptedSubscription.bucketId, recordKind: adoptedSubscription.recordKind, recordId: adoptedSubscription.recordId }
: null,
@@ -483,11 +520,19 @@ export async function processManifest(bucketId, manifestFilename) {
} else {
outcome = { mode: 'inbox', ...(await applyInbox(bucket, manifest, manifestFilename, records)) };
}
- if (assetCopy.missing.length > 0 || missingRecords.length > 0) {
+ // 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`.
+ const collectionPendingUniverse = outcome?.collectionPendingUniverse || null;
+ if (assetCopy.missing.length > 0 || missingRecords.length > 0 || collectionPendingUniverse) {
if (assetCopy.missing.length > 0) outcome.pendingAssets = assetCopy.missing;
if (missingRecords.length > 0) outcome.pendingRecords = missingRecords;
+ if (collectionPendingUniverse) outcome.pendingCollectionUniverse = collectionPendingUniverse;
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}`);
+ 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}` : ''}`);
return { processed: true, pending: true, manifest, outcome };
}
await markProcessed(bucketId, manifestFilename, manifest.id);
@@ -599,6 +644,17 @@ export async function promoteInboxItem(bucketId, manifestId) {
await mergeMediaJobRecords(bucket.path, manifest.recordIds);
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.
+ 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,
+ });
+ }
// 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.js
index 982aee5d7d..6c97e38bbe 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -255,7 +255,13 @@ describe('sharing round-trip', () => {
expect(fs.existsSync(join(tempData, 'images', 'second.png'))).toBe(true);
});
- it('universe export bundles a legacy convention-named collection with no universeId', async () => {
+ 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 it
+ // out under a new same-named universe. The runtime fallback is gone;
+ // the upgrade path for genuinely-legacy installs is migration 021
+ // (which runs at boot, before any exporter call). This test pins the
+ // new contract.
const bucket = await buckets.createBucket({ name: 'LegacyBucket', path: tempBucket, mode: 'auto-merge' });
const universeBuilder = await import('../universeBuilder.js');
const mediaCollections = await import('../mediaCollections.js');
@@ -263,29 +269,19 @@ describe('sharing round-trip', () => {
const fs = await import('fs');
fs.writeFileSync(join(tempData, 'images', 'legacy.png'), 'PNG');
- const collection = await mediaCollections.createCollection({
+ // Unlinked collection with the conventional name — exporter must NOT
+ // adopt this for the universe.
+ const orphan = await mediaCollections.createCollection({
name: `Universe: ${u.name}`,
description: 'Legacy unlinked collection',
});
- await mediaCollections.addItem(collection.id, { kind: 'image', ref: 'legacy.png' });
+ await mediaCollections.addItem(orphan.id, { kind: 'image', ref: 'legacy.png' });
const exp = await exporter.exportUniverse(u.id, bucket.id);
const manifest = JSON.parse(fs.readFileSync(join(tempBucket, 'manifests', exp.filename), 'utf-8'));
- expect(manifest.collection).toMatchObject({ name: 'Universe: Post-Epoc', universeId: u.id });
- expect(manifest.collection.items).toHaveLength(1);
-
- await mediaCollections.deleteCollection(collection.id);
- await universeBuilder.deleteUniverse(u.id);
-
- simulateRemoteSender(tempBucket, exp.filename);
- const r = await importer.processManifest(bucket.id, exp.filename);
- expect(r.processed).toBe(true);
- expect(r.outcome.collectionItemsAdded).toBe(1);
-
- const restored = (await mediaCollections.listCollections()).find((c) => c.name === 'Universe: Post-Epoc');
- expect(restored).toBeTruthy();
- expect(restored.universeId).toBe(u.id);
- expect(restored.items.map((i) => i.ref)).toEqual(['legacy.png']);
+ // No collection payload in the manifest — the universe had no
+ // universeId-linked collection.
+ expect(manifest.collection).toBeFalsy();
});
it('keeps universe manifests retryable while Drive assets are still syncing', async () => {
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index eacf2d65ab..e452ac6c0f 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -35,6 +35,7 @@ import {
} from '../lib/storyBible.js';
import { sanitizeOrigin } from '../lib/sharingOrigin.js';
import { emitRecordUpdated, emitRecordDeleted } from './sharing/recordEvents.js';
+import { renameCollectionForUniverse, unlinkCollectionsForUniverse } from './mediaCollections.js';
// Bumped when a sanitizer-time backfill changes how on-disk universes are
// shaped, so future migrations can gate on the prior version.
@@ -814,6 +815,13 @@ export async function updateUniverse(id, patch = {}) {
if (!merged) throw makeErr('Invalid universe payload', ERR_VALIDATION);
state.universes[idx] = merged;
await writeState(state);
+ // Cascade rename onto the linked media collection — log but don't fail
+ // the save: a stale collection name is recoverable, a failed save isn't.
+ if (merged.name !== cur.name) {
+ await renameCollectionForUniverse(merged.id, merged.name).catch((err) => {
+ console.error(`❌ universe-collection rename cascade failed for ${merged.id}: ${err?.message || err}`);
+ });
+ }
emitRecordUpdated('universe', merged.id);
return merged;
}
@@ -826,6 +834,14 @@ export async function deleteUniverse(id) {
// Drop runs referencing the deleted universe — they're useless without it.
state.runs = state.runs.filter((r) => r.universeId !== id);
await writeState(state);
+ // Release the rename-lock on any linked media collections — without this,
+ // the orphan collection's `universeId` stays stamped and the lock in
+ // updateCollection blocks renames forever even though the universe is gone.
+ // Best-effort: a failure here mustn't fail the delete (the universe is
+ // already gone from state).
+ await unlinkCollectionsForUniverse(id).catch((err) => {
+ console.error(`❌ unlink media collections for deleted universe ${id} failed: ${err?.message || err}`);
+ });
emitRecordDeleted('universe', id);
return { id };
}
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index 54bc4ed6cd..d01db86043 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -236,6 +236,29 @@ describe("universeBuilder service", () => {
).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
});
+ it("updateUniverse cascades a name change onto the linked media collection", async () => {
+ const collections = await import("./mediaCollections.js");
+ const w = await seedWorld();
+ // Seed a linked collection. The render route uses
+ // findOrCreateUniverseCollection (universeId-first); we use the
+ // name-first helper here only because the resulting record is
+ // shape-identical and avoids dragging in the production route's
+ // dependencies for this rename-cascade-focused test.
+ await collections.findOrCreateCollectionByName({
+ name: collections.universeCollectionNameFor(w.name),
+ universeId: w.id,
+ });
+ await svc.updateUniverse(w.id, { name: "Renamed Universe" });
+ const linked = await collections.findCollectionByUniverseId(w.id);
+ expect(linked?.name).toBe("Universe: Renamed Universe");
+ });
+
+ it("updateUniverse rename succeeds even when no linked collection exists", async () => {
+ const w = await seedWorld();
+ const patched = await svc.updateUniverse(w.id, { name: "Solo Rename" });
+ expect(patched.name).toBe("Solo Rename");
+ });
+
it("deleteUniverse removes the universe and its runs", async () => {
const w = await seedWorld();
await svc.recordRun({
@@ -251,6 +274,27 @@ describe("universeBuilder service", () => {
expect(await svc.listRuns(w.id)).toEqual([]);
});
+ it("deleteUniverse unlinks linked media collections (releases the rename-lock)", async () => {
+ const collections = await import("./mediaCollections.js");
+ const w = await seedWorld();
+ // Seed a linked collection (see rename-cascade test above for why we
+ // use the name-first helper here even though production routes through
+ // findOrCreateUniverseCollection).
+ const linked = await collections.findOrCreateCollectionByName({
+ name: collections.universeCollectionNameFor(w.name),
+ universeId: w.id,
+ });
+ expect(linked.universeId).toBe(w.id);
+ await svc.deleteUniverse(w.id);
+ // Collection survives — the user may still want the renders.
+ const fresh = await collections.getCollection(linked.id);
+ // …but the `universeId` is cleared so the rename-lock no longer applies.
+ expect(fresh.universeId).toBeNull();
+ await expect(
+ collections.updateCollection(fresh.id, { name: "User-Renamed" }),
+ ).resolves.toMatchObject({ name: "User-Renamed" });
+ });
+
describe("compilePrompts", () => {
it("returns one prompt per variation across selected categories with style prefix", async () => {
const w = await seedWorld();