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: make Universe Builder renders searchable by character/place name in MediaHistory

[._.]/ Adam Eivyabe506dca802
diff --git a/PLAN.md b/PLAN.md
index aef834b470..59e01103f7 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -79,6 +79,7 @@ _Nothing currently parked — pick the next item from the Backlog._
- [ ] [datasync-checksum-only-fast-path] **Add a checksum-only fast path to `dataSync.js`.** `getChecksum(category)` currently calls the category's `getSnapshot` and discards `data` (`server/services/dataSync.js:451-456`) — every probe materializes the full payload. With pipeline/universe added the wasted work scales with the largest user-creative payload. Define per-category `getChecksum` shortcuts (e.g. hash file size+mtime, or hash raw bytes without parse) and dispatch via `CATEGORIES[cat].getChecksum`. The orchestrator hits the checksum endpoint every cycle — this is the hottest sync-side I/O. Surfaced by /simplify during `extend-syncorchestrator-to-cover-pipeline-universe`.
- [x] [extract-flatten-canon-descriptor-fragments-helper] ~~**Extract `flattenCanonDescriptorFragments(fragments, { separator, trailingPeriod })` into `server/lib/canonPrompt.js` (+ client mirror).**~~ Shipped — `flattenCanonDescriptorFragments` + `mapCanonDescriptorFragments` added to `server/lib/canonPrompt.js` and mirrored to `client/src/lib/canonPrompt.js`. All 6 inline sites migrated: server `canonPrompt.js`/`scenePrompt.js`/`services/pipeline/visualStages.js`/`services/universeBuilder.js` + the two client mirrors. The `mapCanonDescriptorFragments` companion supports the scene-prompt budget-truncator that needs the array form.
- [ ] [consolidate-cert-path-constants] **Consolidate `CERT_DIR`/`CERT_PATH`/`KEY_PATH`/`META_PATH` constants.** Re-declared in `scripts/setup-cert.js`, `scripts/open-ui-in-browser.js`, `server/services/certProvisioner.js`, and `server/services/certRenewer.js` (4 sites). Surfaced by `/simplify` during the first-run HTTPS-auto-flip fix (2026-05-19); deferred to keep that PR scoped. Candidate home: `lib/certPaths.js` (alongside `lib/tailscale-https.js` so both runtime + bootstrap can import).
+- [ ] [imagegen-local-defer-module-load-side-effects] **Defer module-load side effects in `server/services/imageGen/local.js`.** Line 32 runs `IMAGE_MODELS = Object.fromEntries(getImageModels().map(...))` at module evaluation — `getImageModels()` calls `lib/mediaModels.js#loadMediaModels` which `mkdirSync`s `dirname(REGISTRY_FILE)` and `writeFileSync`s a default registry if missing. Any importer that loads via a mocked `PATHS.data` (e.g. `routes/pipeline.test.js` → `routes/pipeline.js` → `routes/universeBuilder.js` → `services/universeBuilderCollectionHook.js` → `services/imageGen/local.js`) fails on `mkdirSync('/mock/data')`. Worked around in 2026-05-19 by lazy-importing `readImageSidecar` in `universeBuilderCollectionHook.js`; real fix is to convert `IMAGE_MODELS` + sibling top-level constants to lazy getters and audit callers. Affects every consumer of `local.js` exports today.
- [ ] [cleanplateprompt-migrate-to-rich-canon-fragments] **Migrate `client/src/lib/cleanPlatePrompt.js#composeCleanPlatePrompt` to `richCanonDescriptorFragments('place', setting)`.** Clean-plate prompt builder (Cluster A — A4 setting reference renders) hand-rolls `description + Palette + recurringDetails` extraction at `cleanPlatePrompt.js:26-30` and is missing `era` / `weather` for the same reason `[pipeline-visual-stages-setting-field-injection]` was missing them — both are visual prompts that benefit from period/atmosphere cues. Tightly scoped sibling change (one client file + one test file). Deferred from that PR because the PLAN item targeted storyboard+comic-panel specifically; clean plates are setting-reference renders, adjacent but distinct.
### v2.1.0 pre-release review residue (deferred from main→release multi-agent review, 2026-05-16)
diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsx
index a183c4c265..6522ae830a 100644
--- a/client/src/components/media/MediaLightbox.jsx
+++ b/client/src/components/media/MediaLightbox.jsx
@@ -109,7 +109,18 @@ export default function MediaLightbox({
};
const isCodex = item.mode === 'codex';
+ // Map raw `entryKind` tokens to user-facing labels — the sidecar stores
+ // 'canon' / 'variation' / 'sheet' (ENTRY_REF_KIND values) for parity with
+ // the server contract; users shouldn't see the wire tokens.
+ const entryKindLabel = ({ canon: 'Canon entry', variation: 'Category variation', sheet: 'Composite sheet' })[item.entryKind] || item.entryKind;
const meta = [
+ // Universe Builder context — placed first so "this is Ash from MyVerse"
+ // reads before the technical render params. Sidecars without a universe
+ // tag fall through the existing null-filter at the end.
+ ['Universe', item.universeName],
+ ['Entity', item.entryName],
+ ['Kind', entryKindLabel],
+ ['Category', item.entryCategory],
['Model', item.modelId],
['Resolution', item.width && item.height ? `${item.width}×${item.height}` : null],
['Steps', item.steps],
diff --git a/client/src/components/media/normalize.js b/client/src/components/media/normalize.js
index 8df478192d..3221c1740a 100644
--- a/client/src/components/media/normalize.js
+++ b/client/src/components/media/normalize.js
@@ -44,6 +44,18 @@ export function normalizeImage(i) {
codexSessionId: i.codexSessionId,
mode: i.mode,
loraNames,
+ // Universe Builder tags — stamped onto sidecars by the completion hook
+ // (server/services/universeBuilderCollectionHook.js) for renders driven
+ // by a canon entry, category variation, or composite sheet. Powers
+ // entity-name search in MediaHistory and the lightbox detail panel.
+ universeId: i.universeId || null,
+ universeName: i.universeName || null,
+ universeRunId: i.universeRunId || null,
+ entryKind: i.entryKind || null, // 'canon' | 'variation' | 'sheet'
+ entryCategory: i.entryCategory || null,
+ entryId: i.entryId || null,
+ entryName: i.entryName || null,
+ entryLabel: i.entryLabel || null,
createdAt: i.createdAt,
hidden: !!i.hidden,
extractedFromVideoId: i.extractedFromVideoId || null,
diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsx
index 94ce8f56fb..8e3c1d707d 100644
--- a/client/src/pages/MediaHistory.jsx
+++ b/client/src/pages/MediaHistory.jsx
@@ -76,6 +76,13 @@ export default function MediaHistory() {
item.seed != null ? `seed ${item.seed}` : '',
item.width && item.height ? `${item.width}x${item.height}` : '',
...(Array.isArray(item.loraNames) ? item.loraNames : []),
+ // Universe Builder tags — searchable by entity name (e.g. "Ash"), universe
+ // name, kind, or category even when those tokens aren't in the prompt.
+ item.universeName,
+ item.entryName,
+ item.entryLabel,
+ item.entryCategory,
+ item.entryKind,
item.extractedFromVideoId ? 'extracted frame' : '',
item.stitchedFrom ? 'stitched' : '',
item.upscaledFrom ? 'upscaled 2x' : '',
@@ -180,7 +187,7 @@ export default function MediaHistory() {
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
- placeholder="Search prompt, model, seed, lora…"
+ placeholder="Search prompt, model, character, place…"
className="w-full pl-7 pr-7 py-1 bg-port-bg border border-port-border rounded text-xs text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"
/>
{query && (
diff --git a/scripts/migrations/028-backfill-universe-builder-image-sidecars.js b/scripts/migrations/028-backfill-universe-builder-image-sidecars.js
new file mode 100644
index 0000000000..00077b9e33
--- /dev/null
+++ b/scripts/migrations/028-backfill-universe-builder-image-sidecars.js
@@ -0,0 +1,193 @@
+/**
+ * Backfill universe + entity metadata onto pre-existing image sidecars.
+ *
+ * Background:
+ * The Universe Builder render path now writes universe/entity context
+ * (universeId, universeName, entryName, entryKind, entryCategory) into
+ * each image's `data/images/<jobId>.metadata.json` sidecar so the media
+ * history search can find renders by character name, place name, etc.
+ * (See `server/services/universeBuilderCollectionHook.js`.)
+ *
+ * Images rendered before that change have no such tag — `MediaHistory`
+ * can't find them by entity name. This migration walks every universe's
+ * canon entries, category variations, and composite sheets, reading the
+ * `imageRefs[]` that already link entities → filenames, and stamps the
+ * universe context onto each sidecar.
+ *
+ * Algorithm:
+ * 1. Read `data/universe-builder.json`. For each universe:
+ * a. canon characters[], places[], objects[] → entryKind: 'canon'
+ * b. categories[*].variations[*] → entryKind: 'variation'
+ * c. compositeSheets[*] → entryKind: 'sheet'
+ * 2. For each entry, walk its `imageRefs[]` (basenames in `data/images/`).
+ * 3. Read the sidecar (either naming convention), merge in universe context
+ * *only when the keys are absent*, write back. Never clobber an existing
+ * tag — a filename could have been moved between universes by hand-edit.
+ *
+ * Idempotent: re-runs skip sidecars where all target keys are already set.
+ * Best-effort: missing sidecars (orphaned imageRefs from earlier deletions)
+ * are silently skipped, not treated as errors.
+ */
+
+import { readFile, writeFile, stat } from 'fs/promises';
+import { join } from 'path';
+
+const readJson = async (path) => {
+ const raw = await readFile(path, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) return null;
+ return JSON.parse(raw);
+};
+
+// Mirrors the two sidecar naming conventions handled by
+// `server/services/imageGen/local.js#readImageSidecar`. Either filename<->sidecar
+// shape is valid on disk depending on which generator wrote the image.
+async function findSidecar(imagesDir, filename) {
+ const candidates = [
+ join(imagesDir, filename.replace(/\.png$/i, '.metadata.json')),
+ join(imagesDir, `${filename}.metadata.json`),
+ ];
+ for (const path of candidates) {
+ const exists = await stat(path).then(() => true).catch(() => false);
+ if (exists) return path;
+ }
+ return null;
+}
+
+// Build the patch to merge into the sidecar — mirrors `buildSidecarPatch`
+// in `server/services/universeBuilderCollectionHook.js`. Inlined here so this
+// one-shot migration's contract is frozen against future runtime changes.
+function buildPatch({ universe, entry, entryKind, entryCategory, entryLabel }) {
+ const patch = {
+ universeId: universe.id,
+ ...(typeof universe.name === 'string' ? { universeName: universe.name } : {}),
+ entryKind,
+ entryId: entry.id,
+ ...(entryCategory ? { entryCategory } : {}),
+ };
+ // Canon → use the entity's canonical name; variation/sheet → fall back to
+ // the entry's label (the closest analogue to "what the user called it").
+ const name = (entryKind === 'canon' && typeof entry.name === 'string' && entry.name)
+ || (typeof entry.label === 'string' && entry.label)
+ || null;
+ if (name) patch.entryName = name;
+ if (entryLabel) patch.entryLabel = entryLabel;
+ return patch;
+}
+
+// Returns true when at least one absent key got filled in.
+function applyPatch(metadata, patch) {
+ let changed = false;
+ for (const [k, v] of Object.entries(patch)) {
+ if (v == null) continue;
+ if (metadata[k] === undefined || metadata[k] === null) {
+ metadata[k] = v;
+ changed = true;
+ }
+ }
+ return changed;
+}
+
+async function backfillEntry({ imagesDir, universe, entry, entryKind, entryCategory, stats }) {
+ if (!entry || typeof entry !== 'object' || !entry.id) return;
+ const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : [];
+ if (refs.length === 0) return;
+ const patch = buildPatch({
+ universe, entry, entryKind, entryCategory,
+ entryLabel: typeof entry.label === 'string' ? entry.label : null,
+ });
+ for (const ref of refs) {
+ if (typeof ref !== 'string' || !ref) continue;
+ const sidecarPath = await findSidecar(imagesDir, ref);
+ if (!sidecarPath) {
+ stats.missingSidecar += 1;
+ continue;
+ }
+ const raw = await readFile(sidecarPath, 'utf-8').catch(() => null);
+ if (raw == null) {
+ stats.missingSidecar += 1;
+ continue;
+ }
+ let metadata;
+ try { metadata = JSON.parse(raw); } catch { stats.invalidSidecar += 1; continue; }
+ if (!metadata || typeof metadata !== 'object') { stats.invalidSidecar += 1; continue; }
+ const changed = applyPatch(metadata, patch);
+ if (!changed) {
+ stats.alreadyTagged += 1;
+ continue;
+ }
+ await writeFile(sidecarPath, JSON.stringify(metadata, null, 2));
+ stats.updated += 1;
+ }
+}
+
+const CANON_KINDS = ['characters', 'places', 'objects'];
+
+export default {
+ async up({ rootDir }) {
+ const universesPath = join(rootDir, 'data', 'universe-builder.json');
+ const imagesDir = join(rootDir, 'data', 'images');
+ const doc = await readJson(universesPath);
+ if (!doc || !Array.isArray(doc.universes) || doc.universes.length === 0) {
+ return { updated: 0, reason: 'no-universes' };
+ }
+
+ const stats = { updated: 0, alreadyTagged: 0, missingSidecar: 0, invalidSidecar: 0 };
+ let universesTouched = 0;
+
+ for (const universe of doc.universes) {
+ if (!universe || typeof universe !== 'object' || !universe.id) continue;
+ const before = stats.updated;
+
+ // 1. Canon entries — kindKey carries through as the entryCategory so
+ // search hits like "characters" / "places" / "objects" work too.
+ for (const kindKey of CANON_KINDS) {
+ const list = Array.isArray(universe[kindKey]) ? universe[kindKey] : [];
+ for (const entry of list) {
+ await backfillEntry({
+ imagesDir, universe, entry,
+ entryKind: 'canon', entryCategory: kindKey,
+ stats,
+ });
+ }
+ }
+
+ // 2. Category variations.
+ const categories = universe.categories && typeof universe.categories === 'object'
+ ? universe.categories : {};
+ for (const [categoryKey, cat] of Object.entries(categories)) {
+ const variations = Array.isArray(cat?.variations) ? cat.variations : [];
+ for (const variation of variations) {
+ await backfillEntry({
+ imagesDir, universe, entry: variation,
+ entryKind: 'variation', entryCategory: categoryKey,
+ stats,
+ });
+ }
+ }
+
+ // 3. Composite sheets — no category, but the sheet's label carries the
+ // user-visible name.
+ const sheets = Array.isArray(universe.compositeSheets) ? universe.compositeSheets : [];
+ for (const sheet of sheets) {
+ await backfillEntry({
+ imagesDir, universe, entry: sheet,
+ entryKind: 'sheet', entryCategory: null,
+ stats,
+ });
+ }
+
+ if (stats.updated > before) universesTouched += 1;
+ }
+
+ if (stats.updated > 0) {
+ console.log(`📦 migration 028: tagged ${stats.updated} image sidecar(s) across ${universesTouched} universe(s).`);
+ } else {
+ console.log(`📦 migration 028: nothing to backfill (${stats.alreadyTagged} already tagged, ${stats.missingSidecar} orphaned refs, ${stats.invalidSidecar} invalid).`);
+ }
+
+ return stats;
+ },
+};
diff --git a/scripts/migrations/028-backfill-universe-builder-image-sidecars.test.js b/scripts/migrations/028-backfill-universe-builder-image-sidecars.test.js
new file mode 100644
index 0000000000..ce5f2fc89a
--- /dev/null
+++ b/scripts/migrations/028-backfill-universe-builder-image-sidecars.test.js
@@ -0,0 +1,207 @@
+/**
+ * Test for migration 028 — backfill universe + entity metadata onto
+ * pre-existing image sidecars.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration from './028-backfill-universe-builder-image-sidecars.js';
+
+const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2));
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));
+
+describe('migration 028 — backfill universe builder image sidecars', () => {
+ let rootDir;
+ let dataDir;
+ let imagesDir;
+ let universesPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-028-'));
+ dataDir = join(rootDir, 'data');
+ imagesDir = join(dataDir, 'images');
+ mkdirSync(imagesDir, { recursive: true });
+ universesPath = join(dataDir, 'universe-builder.json');
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ function seedSidecar(filename, metadata) {
+ writeJson(join(imagesDir, filename.replace(/\.png$/i, '.metadata.json')), metadata);
+ }
+
+ it('stamps universe + canon entity context onto referenced sidecars', async () => {
+ writeJson(universesPath, {
+ universes: [
+ {
+ id: 'u-1', name: 'TestVerse',
+ characters: [
+ { id: 'char-ash', name: 'Ash', imageRefs: ['ash-1.png', 'ash-2.png'] },
+ ],
+ places: [{ id: 'place-glen', name: 'Hollow Glen', imageRefs: ['glen-1.png'] }],
+ objects: [],
+ },
+ ],
+ });
+ seedSidecar('ash-1.png', { id: 'ash-1', prompt: 'p1' });
+ seedSidecar('ash-2.png', { id: 'ash-2', prompt: 'p2' });
+ seedSidecar('glen-1.png', { id: 'glen-1', prompt: 'p3' });
+
+ const result = await migration.up({ rootDir });
+ expect(result.updated).toBe(3);
+
+ const ash1 = readJson(join(imagesDir, 'ash-1.metadata.json'));
+ expect(ash1.universeId).toBe('u-1');
+ expect(ash1.universeName).toBe('TestVerse');
+ expect(ash1.entryKind).toBe('canon');
+ expect(ash1.entryCategory).toBe('characters');
+ expect(ash1.entryId).toBe('char-ash');
+ expect(ash1.entryName).toBe('Ash');
+ expect(ash1.prompt).toBe('p1'); // original field preserved
+
+ const glen = readJson(join(imagesDir, 'glen-1.metadata.json'));
+ expect(glen.entryName).toBe('Hollow Glen');
+ expect(glen.entryCategory).toBe('places');
+ });
+
+ it('stamps category variations with their label as entryName', async () => {
+ writeJson(universesPath, {
+ universes: [
+ {
+ id: 'u-2', name: 'CatVerse',
+ categories: {
+ landscapes: {
+ variations: [
+ { id: 'var-foggy', label: 'Foggy moor at dusk', imageRefs: ['foggy.png'] },
+ ],
+ },
+ },
+ },
+ ],
+ });
+ seedSidecar('foggy.png', { id: 'foggy', prompt: 'misty hills' });
+
+ await migration.up({ rootDir });
+ const sc = readJson(join(imagesDir, 'foggy.metadata.json'));
+ expect(sc.entryKind).toBe('variation');
+ expect(sc.entryCategory).toBe('landscapes');
+ expect(sc.entryId).toBe('var-foggy');
+ expect(sc.entryName).toBe('Foggy moor at dusk');
+ expect(sc.entryLabel).toBe('Foggy moor at dusk');
+ });
+
+ it('stamps composite sheets (no category, entryName from label)', async () => {
+ writeJson(universesPath, {
+ universes: [
+ {
+ id: 'u-3', name: 'SheetVerse',
+ compositeSheets: [
+ { id: 'sheet-cast', label: 'Main cast lineup', imageRefs: ['cast.png'] },
+ ],
+ },
+ ],
+ });
+ seedSidecar('cast.png', { id: 'cast', prompt: 'eight characters' });
+
+ await migration.up({ rootDir });
+ const sc = readJson(join(imagesDir, 'cast.metadata.json'));
+ expect(sc.entryKind).toBe('sheet');
+ expect(sc.entryId).toBe('sheet-cast');
+ expect(sc.entryName).toBe('Main cast lineup');
+ expect(sc.entryCategory).toBeUndefined();
+ });
+
+ it('is idempotent — re-running reports zero updates', async () => {
+ writeJson(universesPath, {
+ universes: [
+ {
+ id: 'u-4', name: 'IdemVerse',
+ characters: [{ id: 'c1', name: 'Once', imageRefs: ['once.png'] }],
+ },
+ ],
+ });
+ seedSidecar('once.png', { id: 'once', prompt: 'p' });
+
+ const first = await migration.up({ rootDir });
+ expect(first.updated).toBe(1);
+
+ const second = await migration.up({ rootDir });
+ expect(second.updated).toBe(0);
+ expect(second.alreadyTagged).toBe(1);
+ });
+
+ it('does not clobber an existing universe tag on the sidecar', async () => {
+ writeJson(universesPath, {
+ universes: [
+ {
+ id: 'u-new', name: 'NewVerse',
+ characters: [{ id: 'c1', name: 'NewName', imageRefs: ['shared.png'] }],
+ },
+ ],
+ });
+ // Sidecar already carries a stamp from a different universe (e.g.
+ // image was moved manually). Migration must NOT overwrite it.
+ seedSidecar('shared.png', {
+ id: 'shared',
+ universeId: 'u-old',
+ universeName: 'OldVerse',
+ entryName: 'OldName',
+ });
+
+ await migration.up({ rootDir });
+ const sc = readJson(join(imagesDir, 'shared.metadata.json'));
+ expect(sc.universeId).toBe('u-old');
+ expect(sc.universeName).toBe('OldVerse');
+ expect(sc.entryName).toBe('OldName');
+ // But absent fields still get filled in.
+ expect(sc.entryKind).toBe('canon');
+ expect(sc.entryId).toBe('c1');
+ });
+
+ it('skips orphaned imageRefs (no sidecar on disk)', async () => {
+ writeJson(universesPath, {
+ universes: [
+ {
+ id: 'u-5', name: 'OrphanVerse',
+ characters: [
+ { id: 'c1', name: 'Living', imageRefs: ['alive.png', 'deleted.png'] },
+ ],
+ },
+ ],
+ });
+ seedSidecar('alive.png', { id: 'alive', prompt: 'p' });
+ // deleted.png has no sidecar on disk.
+
+ const result = await migration.up({ rootDir });
+ expect(result.updated).toBe(1);
+ expect(result.missingSidecar).toBe(1);
+ expect(existsSync(join(imagesDir, 'alive.metadata.json'))).toBe(true);
+ });
+
+ it('handles the alt sidecar naming convention (<filename>.metadata.json)', async () => {
+ writeJson(universesPath, {
+ universes: [
+ {
+ id: 'u-6', name: 'AltVerse',
+ characters: [{ id: 'c1', name: 'Alt', imageRefs: ['alt.png'] }],
+ },
+ ],
+ });
+ // Alternate convention: <filename>.metadata.json (not <basename>.metadata.json).
+ writeJson(join(imagesDir, 'alt.png.metadata.json'), { id: 'alt', prompt: 'p' });
+
+ await migration.up({ rootDir });
+ const sc = readJson(join(imagesDir, 'alt.png.metadata.json'));
+ expect(sc.entryName).toBe('Alt');
+ });
+
+ it('no-ops when universe-builder.json does not exist', async () => {
+ const result = await migration.up({ rootDir });
+ expect(result.updated).toBe(0);
+ expect(result.reason).toBe('no-universes');
+ });
+});
diff --git a/server/services/universeBuilderCollectionHook.js b/server/services/universeBuilderCollectionHook.js
index 07a02aa661..07b835cfc1 100644
--- a/server/services/universeBuilderCollectionHook.js
+++ b/server/services/universeBuilderCollectionHook.js
@@ -21,12 +21,31 @@
* the run finishes naturally.
*/
+import { writeFile } from 'fs/promises';
import { mediaJobEvents } from './mediaJobQueue/index.js';
import { addItem, ERR_DUPLICATE } from './mediaCollections.js';
import { withReexportSuppressed, emitRecordUpdated } from './sharing/recordEvents.js';
-import { appendEntryImageRef } from './universeBuilder.js';
+import { appendEntryImageRef, getUniverse, ENTRY_REF_KIND } from './universeBuilder.js';
-// runId → { universeId, pending }. Pure in-memory; lost on restart.
+// `imageGen/local.js` runs `getImageModels()` at module-load time, which
+// requires the on-disk media-models registry directory to be writable. That
+// fires through `routes/universeBuilder.js` → this hook on every importer
+// (e.g. `routes/pipeline.js`), tripping any test that mocks PATHS to a
+// non-writable path. Lazy-loading here keeps the production path identical
+// (one resolve per hook init, then a cached module ref) while letting
+// pipeline/routes tests load without invoking the registry side-effect.
+let _readImageSidecar = null;
+async function getReadImageSidecar() {
+ if (!_readImageSidecar) {
+ const mod = await import('./imageGen/local.js');
+ _readImageSidecar = mod.readImageSidecar;
+ }
+ return _readImageSidecar;
+}
+
+// runId → { universeId, pending, universePromise? }. Pure in-memory; lost on restart.
+// `universePromise` memoizes the universe doc for the lifetime of the batch so
+// 160-image runs don't re-read universe-builder.json per completion.
const activeRuns = new Map();
export function registerUniverseBuilderRun({ runId, universeId, jobCount }) {
@@ -45,6 +64,74 @@ function noteTerminal(runId) {
return entry.universeId;
}
+// Resolves the entry's canonical name (canon entries carry `.name`; variations
+// and sheets carry only the compiled label). Returns null when nothing can be
+// resolved — the caller falls back to `tag.label`.
+function resolveEntryName(universe, entryRef) {
+ if (!universe || !entryRef) return null;
+ if (entryRef.kind === ENTRY_REF_KIND.CANON && entryRef.kindKey && entryRef.id) {
+ const list = universe[entryRef.kindKey];
+ const hit = Array.isArray(list) ? list.find((e) => e?.id === entryRef.id) : null;
+ return typeof hit?.name === 'string' ? hit.name : null;
+ }
+ return null;
+}
+
+// Build the universe-context object to merge into the image sidecar. Mirrors
+// the migration's contract so new + backfilled renders carry identical shapes.
+function buildSidecarPatch({ tag, universe }) {
+ const entryRef = tag.entryRef;
+ const universeName = typeof universe?.name === 'string' ? universe.name : null;
+ const patch = {
+ universeId: tag.universeId,
+ ...(universeName ? { universeName } : {}),
+ ...(tag.runId ? { universeRunId: tag.runId } : {}),
+ ...(tag.label ? { entryLabel: tag.label } : {}),
+ };
+ if (!entryRef) {
+ // Legacy variations without stable ids: still tag the universe + label
+ // so search can find renders by universe even without entity granularity.
+ if (tag.category) patch.entryCategory = tag.category;
+ return patch;
+ }
+ patch.entryKind = entryRef.kind;
+ patch.entryId = entryRef.id;
+ if (entryRef.kind === ENTRY_REF_KIND.VARIATION && entryRef.categoryKey) {
+ patch.entryCategory = entryRef.categoryKey;
+ } else if (entryRef.kind === ENTRY_REF_KIND.CANON && entryRef.kindKey) {
+ patch.entryCategory = entryRef.kindKey;
+ }
+ const resolvedName = resolveEntryName(universe, entryRef) || tag.label || null;
+ if (resolvedName) patch.entryName = resolvedName;
+ return patch;
+}
+
+// Read-merge-write the image sidecar with universe context. Only fills keys
+// that are currently absent — re-renders of the same filename must not
+// silently overwrite an existing tag with a different universe's data.
+//
+// Skips writeback when the sidecar doesn't exist (empty metadata from
+// readImageSidecar's miss path). The PNG-generating code always writes a
+// sidecar before the `completed` event fires, so an empty result means the
+// PNG itself is missing too — creating a universe-only sidecar in that case
+// would leave a stub record with no prompt/seed/model on disk.
+async function enrichSidecar(filename, patch) {
+ const readImageSidecar = await getReadImageSidecar();
+ const { path, metadata } = await readImageSidecar(filename);
+ if (!metadata || Object.keys(metadata).length === 0) return;
+ let changed = false;
+ const next = { ...metadata };
+ for (const [k, v] of Object.entries(patch)) {
+ if (v == null) continue;
+ if (next[k] === undefined || next[k] === null) {
+ next[k] = v;
+ changed = true;
+ }
+ }
+ if (!changed) return;
+ await writeFile(path, JSON.stringify(next, null, 2));
+}
+
let completedHandler = null;
let terminalHandler = null;
@@ -90,16 +177,38 @@ export function initUniverseBuilderCollectionHook() {
});
};
+ // Enrich the image's sidecar with universe + entity context so
+ // MediaHistory can search for renders by character/place name and the
+ // lightbox can show which entity produced the image. The universe doc
+ // read is memoized per-run on activeRuns so 160-image batches read the
+ // ~700KB universe JSON once, not 160 times. Untracked runs (server
+ // restart mid-batch) fall back to a per-completion read — rare and
+ // bounded by the remaining job count.
+ const enrichSidecarCall = () => {
+ if (!tag.universeId) return Promise.resolve(null);
+ const entry = tag.runId ? activeRuns.get(tag.runId) : null;
+ if (entry && !entry.universePromise) {
+ entry.universePromise = getUniverse(tag.universeId).catch(() => null);
+ }
+ const universePromise = entry?.universePromise || getUniverse(tag.universeId).catch(() => null);
+ return universePromise
+ .then((universe) => enrichSidecar(filename, buildSidecarPatch({ tag, universe })))
+ .catch((err) => {
+ console.log(`⚠️ universe-builder sidecar enrich failed for ${filename}: ${err?.message || String(err)}`);
+ return null;
+ });
+ };
+
try {
// When the run is tracked, swallow the per-item emitRecordUpdated so a
// 160-image batch doesn't fan into 160 debounced re-exports. The final
// emit below fires once when pending hits zero.
- // The two writes touch independent files (media-collections.json vs
- // universe-builder.json) and have no ordering dependency — fire them
- // in parallel so a 160-image batch run doesn't pay double the
- // per-completion serialization cost.
+ // The three writes touch independent files (media-collections.json,
+ // universe-builder.json, the per-image sidecar) and have no ordering
+ // dependency — fire them in parallel so a large batch doesn't pay
+ // the per-completion serialization cost on every job.
const work = async () => {
- const [s] = await Promise.all([addItemCall(), appendEntryRefCall()]);
+ const [s] = await Promise.all([addItemCall(), appendEntryRefCall(), enrichSidecarCall()]);
return s;
};
const status = runActive && tag.universeId
diff --git a/server/services/universeBuilderCollectionHook.test.js b/server/services/universeBuilderCollectionHook.test.js
index ca92439093..d9f55f7044 100644
--- a/server/services/universeBuilderCollectionHook.test.js
+++ b/server/services/universeBuilderCollectionHook.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
-import { mkdtempSync, rmSync, mkdirSync } from 'fs';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -24,6 +24,14 @@ const { mediaJobEvents } = await import('./mediaJobQueue/index.js');
const collections = await import('./mediaCollections.js');
const recordEvents = await import('./sharing/recordEvents.js');
const hook = await import('./universeBuilderCollectionHook.js');
+const universeBuilder = await import('./universeBuilder.js');
+
+const sidecarPath = (filename) => join(tempData, 'images', filename.replace('.png', '.metadata.json'));
+const writeSidecar = (filename, data) => {
+ mkdirSync(join(tempData, 'images'), { recursive: true });
+ writeFileSync(sidecarPath(filename), JSON.stringify(data, null, 2));
+};
+const readSidecar = (filename) => JSON.parse(readFileSync(sidecarPath(filename), 'utf-8'));
async function waitFor(predicate, { timeoutMs = 2000, intervalMs = 5 } = {}) {
const deadline = Date.now() + timeoutMs;
@@ -133,4 +141,185 @@ describe('universeBuilderCollectionHook', () => {
await waitFor(() => unsuppressed().length >= 2);
expect(unsuppressed()).toHaveLength(2);
});
+
+ // Seed a fully-formed universe doc on disk so getUniverse() inside the hook
+ // can resolve canon names. Returns the seeded universe — callers use its
+ // `id` field as the universeId in `universeRun` tags.
+ async function seedUniverse({ name, characters = [], categoryKey = 'characters', variations = [] }) {
+ const created = await universeBuilder.createUniverse({
+ name,
+ characters,
+ categories: { [categoryKey]: { variations } },
+ });
+ return created;
+ }
+
+ it('enriches the image sidecar with canon entry name + universe context', async () => {
+ const universeName = 'TestVerse';
+ const characterId = 'char-ash';
+ const character = { id: characterId, name: 'Ash', physicalDescription: 'red hair' };
+ const seeded = await seedUniverse({ name: universeName, characters: [character] });
+ const c = await makeCollection(seeded.id);
+ const filename = 'canon-render.png';
+ writeSidecar(filename, { id: 'canon-render', prompt: 'a confident pyromancer', seed: 42 });
+ hook.registerUniverseBuilderRun({ runId: 'r-canon', universeId: seeded.id, jobCount: 1 });
+
+ mediaJobEvents.emit('completed', {
+ kind: 'image',
+ result: { filename },
+ params: {
+ universeRun: {
+ runId: 'r-canon',
+ universeId: seeded.id,
+ collectionId: c.id,
+ category: 'characters',
+ label: 'Ash — pyromancer cut',
+ entryRef: { kind: 'canon', kindKey: 'characters', id: characterId },
+ },
+ },
+ });
+
+ await waitFor(() => {
+ const sc = readSidecar(filename);
+ return sc.entryName === 'Ash';
+ });
+ const sc = readSidecar(filename);
+ expect(sc.universeId).toBe(seeded.id);
+ expect(sc.universeName).toBe(universeName);
+ expect(sc.universeRunId).toBe('r-canon');
+ expect(sc.entryKind).toBe('canon');
+ expect(sc.entryCategory).toBe('characters');
+ expect(sc.entryId).toBe(characterId);
+ expect(sc.entryName).toBe('Ash'); // canonical name wins
+ expect(sc.entryLabel).toBe('Ash — pyromancer cut'); // compiled label preserved
+ // Original sidecar fields untouched.
+ expect(sc.prompt).toBe('a confident pyromancer');
+ expect(sc.seed).toBe(42);
+ });
+
+ it('uses the compiled label as entryName for variation entries (no canon name)', async () => {
+ const variationId = 'var-charm-slinger';
+ const seeded = await seedUniverse({
+ name: 'CategoryVerse',
+ categoryKey: 'characters',
+ variations: [{ id: variationId, label: 'Field Lead: Charm-Slinger Detective', prompt: 'detective in a charm bandolier' }],
+ });
+ const c = await makeCollection(seeded.id);
+ const filename = 'variation-render.png';
+ writeSidecar(filename, { id: 'variation-render', prompt: 'detective in a charm bandolier' });
+ hook.registerUniverseBuilderRun({ runId: 'r-var', universeId: seeded.id, jobCount: 1 });
+
+ mediaJobEvents.emit('completed', {
+ kind: 'image',
+ result: { filename },
+ params: {
+ universeRun: {
+ runId: 'r-var',
+ universeId: seeded.id,
+ collectionId: c.id,
+ category: 'characters',
+ label: 'Field Lead: Charm-Slinger Detective',
+ entryRef: { kind: 'variation', categoryKey: 'characters', id: variationId },
+ },
+ },
+ });
+
+ await waitFor(() => readSidecar(filename).entryKind === 'variation');
+ const sc = readSidecar(filename);
+ expect(sc.entryKind).toBe('variation');
+ expect(sc.entryCategory).toBe('characters');
+ expect(sc.entryId).toBe(variationId);
+ expect(sc.entryName).toBe('Field Lead: Charm-Slinger Detective');
+ expect(sc.entryLabel).toBe('Field Lead: Charm-Slinger Detective');
+ });
+
+ it('does not touch the sidecar of a non-Universe render (no universeRun tag)', async () => {
+ const filename = 'plain-render.png';
+ writeSidecar(filename, { id: 'plain-render', prompt: 'just a sunset' });
+ mediaJobEvents.emit('completed', {
+ kind: 'image',
+ result: { filename },
+ params: {}, // no universeRun
+ });
+ // Give the hook a beat to (not) write anything.
+ await new Promise((r) => setTimeout(r, 50));
+ const sc = readSidecar(filename);
+ expect(sc).toEqual({ id: 'plain-render', prompt: 'just a sunset' });
+ expect(sc.universeId).toBeUndefined();
+ });
+
+ it('preserves an existing universe tag — re-render of the same filename does not clobber', async () => {
+ const seeded = await seedUniverse({
+ name: 'PreservedVerse',
+ characters: [{ id: 'char-original', name: 'Original' }],
+ });
+ const c = await makeCollection(seeded.id);
+ const filename = 'preserved.png';
+ // Sidecar already carries a different universe's tag (e.g. a moved/renamed
+ // file from a prior render).
+ writeSidecar(filename, {
+ id: 'preserved',
+ universeId: 'uni-existing',
+ universeName: 'OldVerse',
+ entryName: 'Original',
+ });
+
+ mediaJobEvents.emit('completed', {
+ kind: 'image',
+ result: { filename },
+ params: {
+ universeRun: {
+ runId: 'r-preserve',
+ universeId: seeded.id,
+ collectionId: c.id,
+ category: 'characters',
+ label: 'New label',
+ entryRef: { kind: 'canon', kindKey: 'characters', id: 'char-original' },
+ },
+ },
+ });
+ await new Promise((r) => setTimeout(r, 50));
+ const sc = readSidecar(filename);
+ // Existing values preserved.
+ expect(sc.universeId).toBe('uni-existing');
+ expect(sc.universeName).toBe('OldVerse');
+ expect(sc.entryName).toBe('Original');
+ // But absent fields get filled in.
+ expect(sc.universeRunId).toBe('r-preserve');
+ expect(sc.entryKind).toBe('canon');
+ });
+
+ it('enriches every sidecar in a batch — all N images get tagged', async () => {
+ const seeded = await seedUniverse({
+ name: 'BatchVerse',
+ characters: [{ id: 'char-batch', name: 'Batchy' }],
+ });
+ const c = await makeCollection(seeded.id);
+ for (let i = 0; i < 5; i += 1) {
+ writeSidecar(`batch-${i}.png`, { id: `batch-${i}`, prompt: 'p' });
+ }
+ hook.registerUniverseBuilderRun({ runId: 'r-batch', universeId: seeded.id, jobCount: 5 });
+ for (let i = 0; i < 5; i += 1) {
+ mediaJobEvents.emit('completed', {
+ kind: 'image',
+ result: { filename: `batch-${i}.png` },
+ params: {
+ universeRun: {
+ runId: 'r-batch',
+ universeId: seeded.id,
+ collectionId: c.id,
+ category: 'characters',
+ label: 'l',
+ entryRef: { kind: 'canon', kindKey: 'characters', id: 'char-batch' },
+ },
+ },
+ });
+ }
+ await waitFor(() => existsSync(sidecarPath('batch-4.png')) && readSidecar('batch-4.png').entryName === 'Batchy');
+ for (let i = 0; i < 5; i += 1) {
+ const sc = readSidecar(`batch-${i}.png`);
+ expect(sc.entryName).toBe('Batchy');
+ expect(sc.universeName).toBe('BatchVerse');
+ }
+ });
});