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([canoncard-from-series-name-full-provenance-label]): render source series name on CanonCard chip

[._.]/ Adam Eivy3e6f4480ce33
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 6b04435a44..8131add2a9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -10,6 +10,7 @@
### Universe Builder
+- **CanonCard provenance chip now names the source series.** The "from series" chip on `CanonCard` (rendered by both the Universe Canon section and the per-issue Nouns stage) now reads `from <Series Name>` when an entry's `sourceSeriesId` resolves through a new `seriesNameMap` prop; the tooltip carries both name and id (`Introduced by series "<name>" (<id>)`). Map is sourced from a new top-level `seriesNameMap` field on the `GET /api/universe-builder/:id/canon-usage` response, which now lists every linked series — not just ones with a prose-match row — so an entry whose `sourceSeriesId` points at a series with no matching prose still resolves to a name. Missing-map / unknown-id cases keep the legacy `from series` label + id-only tooltip. New `SourceSeriesChip` helper extracted in `client/src/components/pipeline/CanonCard.jsx`; 4 vitest cases in `CanonCard.test.jsx` + 2 vitest cases in `server/services/canonUsage.test.js`.
- **Other tab — Auto-sort with AI.** New `POST /api/universe-builder/:id/auto-sort` batches every `kind: 'other'` bucket into one LLM call that classifies each into characters / settings / objects (and optionally suggests a clearer key). Reassignments land atomically via one `updateUniverse` patch (defensive per-entry kind gate filters hallucinated kinds so the sanitizer can't coerce them back to `other`); `suggestedKey` renames surface in the response but stay opt-in. The Other-tab button replaces its old toast stub with a real spinner + result summary. New service `server/services/universeBuilderAutoSort.js` (16 unit tests, including separate prompt-injection pins for ASCII newlines on labels + styleNotes + logline, and for Unicode line/paragraph separators + NEL + form feed + vertical tab on the same three fields) + `server/routes/universeBuilder.test.js` (4 route tests) + `client/src/pages/UniverseBuilder.test.jsx` (2 client tests for the `OtherTab` Auto-sort button — clicks fire `onAutoSort` when enabled; disabled with "Sorting…" label while `autoSorting=true`); client helper `autoSortBuckets` in `apiUniverseBuilder.js`.
- **Other tab — manual trunk assignment.** Each bucket on the Other tab now has an **Assign to…** menu (Cast / Places / Objects) that retags `categories[bucket].kind` so the bucket moves out of Other into the matching trunk on next render. Variations stay in place; per-variation promote-to-canon remains a separate action.
- **Render tab — Other group + dedupe.** Removed the redundant "Prompt set" dropdown from the Batch render card — scope is now always chosen via the Render targets section below. Render targets gained an **Other** group with per-bucket sub-buttons and a `Bulk-render all (N)` button. Top-level action is now **Render everything (N)**.
diff --git a/DONE.md b/DONE.md
index 6ddc690ff8..94861e3058 100644
--- a/DONE.md
+++ b/DONE.md
@@ -11,6 +11,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./
### 2026-05-17
- **[universe-builder-redesign-trunks-sub-buckets] Universe Builder redesign — trunks + sub-buckets layout (Phases A–D + Phase C follow-ups).** Multi-phase rewrite landing across 2026-05-15 → 2026-05-17. Phase A added a `kind: 'characters'|'settings'|'objects'|'other'` field to every category bucket + a migration to backfill the built-in defaults; Phase B taught `buildExpansionPrompt()` + `isExpansionShape()` to emit and accept rich canon arrays alongside categories, with client-side `handleExpand` merging canon entries into `universe.{characters,settings,objects}` (dedupe by name, respect locks); Phase C rewrote the page as a tabbed-trunk layout (Bible / Cast / Places / Objects / Other / Composites / Render) with URL state, a unified `EntryCard` rendering both canon entries and category variations, and per-trunk / per-bucket / all-canon batch-render targeting; Phase D shipped `POST /:id/promote-variation` to LLM-expand a variation into a full canon entry (atomic canon append + variation removal in one `updateUniverse` patch, duplicate-name 409 before the LLM call, trunk picker for `kind: 'other'` buckets). Phase C follow-ups closed today: (1) `updateUniverse(id, mutator)` now accepts an async `mutator(latest) => patch` callback that runs INSIDE `queueUniverseWrite` — `autoSortOtherBuckets` and `promoteVariationToCanon` route their read-modify-write through this so a slow LLM call can't admit a concurrent edit between read and persist; promote's variation removal also re-locates by label inside the queue rather than relying on the stale pre-LLM index, and the duplicate-name 409 is re-checked against the latest canon (returns `UNIVERSE_PROMOTE_CATEGORY_GONE` / `UNIVERSE_PROMOTE_VARIATION_GONE` when the bucket/variation disappears mid-flight); (2) `handleAutoSort` / `handlePromoteVariation` / `handleGenerateInCategory` now flush a dirty draft via `handleSave()` before kicking off — `UniverseBuilder.jsx` tracks a `savedDraftSnapshotRef` baseline (compared via `draftSnapshotForDirty`) that updates on universe-load, manual save, expand auto-save, refine auto-save, generate auto-save, and after each LLM mutator's `onFreshResult` merge. `useUniverseAction` gained a `preflight` option that runs AFTER the ref/savedId guard so double-clicks short-circuit before flushing. 5 new server tests (`updateUniverse` mutator overload — happy path, null-skip, throw-propagation, non-object validation, queue-ordering against a parallel literal-patch write) + 4 new client tests (`useUniverseAction` preflight — returns-false abort, throw-as-false, returns-true continue, post-ref-guard ordering).
+- **[canoncard-from-series-name-full-provenance-label] CanonCard "from series: <name>" full provenance label.** The provenance chip now reads `seriesNameMap?.[entry.sourceSeriesId]` to render `from <Series Name>` with `Introduced by series "<name>" (<id>)` in the tooltip; missing-name fallback preserves the existing `from series` label + id-only tooltip. Chip rendering extracted into a `SourceSeriesChip` helper alongside `ChipPicker` / `ReadonlyChip` in `client/src/components/pipeline/CanonCard.jsx`. Map plumbed from both parents: `UniverseCanonSection.jsx` passes `usage?.seriesNameMap` (no new fetch — reuses the canon-usage call it already makes), and `NounsStage.jsx` fetches `getUniverseCanonUsage(series.universeId)` once on universe load. Server-side `getUniverseCanonUsage` (`server/services/canonUsage.js`) gains a top-level `seriesNameMap: { [seriesId]: name }` field built from every `linkedSeries` (not just ones with prose-match rows) so an entry whose `sourceSeriesId` points at a series with no matching prose still resolves to a name. Coverage: 4 new vitest cases in `CanonCard.test.jsx` (chip omitted with no `sourceSeriesId`; generic fallback when map missing; resolved name + dual-tooltip when present; fallback when id not in map) and 2 new `canonUsage.test.js` cases (linked-with-no-prose-match included; empty map when no series link). NounsStage's per-render fetch is acknowledged as quadratic-cost relative to need; deferred to `[nounsstage-cheaper-seriesnamemap-fetch]` for a thin-endpoint follow-up.
- **[extract-useuniverseaction-hook] Extract `useUniverseAction` hook from `UniverseBuilder.jsx`.** New `client/src/hooks/useUniverseAction.js` consolidates the scaffolding shared by `handlePromoteVariation` + `handleAutoSort`: `selectedId` guard, per-action ref re-entrancy, `capturedId` snapshot, loading-toast lifecycle (`silent: true` + `.catch` → dismiss + error), mountedRef-gated busy reset, always-update `setWorlds`, and the `mountedRef.current && capturedId === selectedId` stale-write guard. Each caller now passes only what varies — its `ref`/`setBusy`/`loadingMessage`/`errorPrefix`/`notSavedMessage`, the API call (receives `capturedId`), and an `onFreshResult(result)` callback that does the selective `setDraft` and returns the success-toast string. `handleGenerateInCategory` is intentionally NOT a consumer (the PLAN line's "to a lesser extent" — eager local merge first + best-effort save is a different shape; forcing it through would warp it); the hook header documents this. 9 new vitest cases in `useUniverseAction.test.jsx` (selectedId guard, re-entrancy, happy path, stale-write, action-rejects, no-loading-toast variant, falsy-universe result, suppressed-toast onFreshResult, unmount mid-flight). PLAN.md description gated this on "extract when a 4th handler lands"; promoted now with 3 — the hook itself is small and the scaffold is the most-bug-prone piece of these handlers.
- **[extract-builduniversestylecontext-helper] Extract `buildUniverseStyleContext(universe, options)` helper.** New helper in `server/services/universeBuilder.js` (next to `joinInfluenceList`) renders the shared "Universe context" prompt block (LOGLINE / optional PREMISE / STYLE NOTES / optional EMBRACE INFLUENCES). Three call sites collapsed: `buildAutoSortPrompt` (`universeBuilderAutoSort.js`, `escape: true`), `buildPromotePrompt` (`universeBuilderPromote.js`, default opts + headerSuffix), and `buildCategoryGeneratePrompt` (`universeBuilderExpand.js`, `includePremise: true` + `includeEmbrace: false` since it has its own influences section). Toggles cover the actual variance: `includePremise`, `includeEmbrace`, `escape` (newline/control-char stripping for defense-in-depth), `headerSuffix` (per-call header framing). 9 new unit tests in `universeBuilder.test.js` assert byte-exact outputs for each call shape. Pipeline call sites at `visualStages.js` and `seriesTitleLogo.js` were inspected but are out of scope — they only use `joinInfluenceList` for render-style composition and template variables, not the LOGLINE/STYLE NOTES/EMBRACE block. `buildExpansionPrompt`'s "Current universe state" block also stays separate — its `[LOCKED]` flags + `LOCKABLE_FIELD_LABELS` make it too distinct to fold without compromising the helper.
- **[extract-descriptorforcanonentry-kind-entry-into] Extract `descriptorForCanonEntry(kind, entry)` into `server/lib/canonPrompt.js` (mirror in client).** New `server/lib/canonPrompt.js` + `client/src/lib/canonPrompt.js` mirror is the single source of truth for per-kind canon descriptor fields. Exports `shortCanonDescriptorFragments` (UI summary scope: physicalDescription || description for chars; description + Palette + recurringDetails for settings; description || significance for objects), `richCanonDescriptorFragments` (adds role, era, weather, significance-as-additive — the render-prompt scope), `descriptorForCanonEntry` (flattened short string matching legacy `KINDS[].descFor`), and `hasCanonDescriptorContent` (rich-field union for "is there anything to render?" gates). Migrated four call sites: `synthesizeCanonPrompt` (`server/services/universeBuilder.js`), `KINDS[].descFor` (`client/src/components/universe/UniverseCanonSection.jsx`), `canonEntryHasContent` (`client/src/pages/UniverseBuilder.jsx`), and `settingFrags` in `server/lib/scenePrompt.js` + client mirror. Tests: 29 new in `server/lib/canonPrompt.test.js`. Minor cosmetic uniformity in canon render prompts: lowercase `palette:`/`era:`/`weather:`/`significance:` prefixes are now capitalized (`Palette:` etc.) to match the UI descriptor format — case-only diff, no functional impact on diffusion models.
diff --git a/PLAN.md b/PLAN.md
index d9593e2a99..0fd99059b5 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -26,7 +26,7 @@ _Nothing currently parked — pick the next item from the Backlog._
### Universe-as-Canon — Phase 2 + extensions
-- [ ] [canoncard-from-series-name-full-provenance-label] **CanonCard "from series: <name>" full provenance label.** Card currently shows a "from series" chip with the series id in the tooltip. Plumb a `seriesNameMap` (or `sourceSeriesName` per entry) so the chip can render the actual series name. Needs the parent (`UniverseCanonSection` / `NounsStage`) to pass a `{ [seriesId]: name }` lookup.
+- [ ] [nounsstage-cheaper-seriesnamemap-fetch] **NounsStage seriesNameMap — avoid the heavy canon-usage fetch.** `NounsStage.jsx` currently calls `getUniverseCanonUsage(series.universeId)` purely to extract `seriesNameMap`. That endpoint also iterates every linked series × every issue running 3 scenePrompt matchers — O(series × issues × matchers) work for what should be O(series). Practically fine at typical PortOS scale (1-5 series, modest issue counts) but wasteful in principle. Options: (a) add a thin `GET /api/universes/:id/series-names` returning `[{id,name}]`, (b) expose `linkedSeriesNames` on `getUniverse()` response, or (c) cache canon-usage in shared context so `UniverseCanonSection` + `NounsStage` share one in-flight fetch. Pick after profiling a real universe with ≥10 linked series.
- [x] ~~**Drop the default `characters` category.**~~ Shipped via the Universe Builder redesign Phase A migration; default `characters` bucket retired, variations backfilled into `universe.characters[]`.
- [x] ~~**Universe expand LLM contract enrichment.**~~ Shipped via the Universe Builder redesign Phase B — expand contract now returns rich canon arrays alongside categories.
- [x] ~~**arcPlanner prompt context — include canon characters/places/objects.**~~ Shipped via the Universe Builder redesign Phase B (`renderCanonForPrompt(world)` + `worldCanonText` + migration 019 for `pipeline-arc-overview`, `pipeline-arc-verify`, `pipeline-arc-resolve`, `pipeline-volume-verify`). Follow-up still open: sweep `grep -rn "world\.categories" server/services/pipeline server/services/universeBuilder*.js` for other prompt builders that read categories but not canon.
diff --git a/client/src/components/pipeline/CanonCard.jsx b/client/src/components/pipeline/CanonCard.jsx
index e9f3c7669f..e912b795c8 100644
--- a/client/src/components/pipeline/CanonCard.jsx
+++ b/client/src/components/pipeline/CanonCard.jsx
@@ -56,6 +56,19 @@ function ReadonlyChip({ children }) {
);
}
+function SourceSeriesChip({ sourceSeriesId, seriesName }) {
+ return (
+ <span
+ className="inline-flex items-center px-1.5 py-0.5 rounded bg-port-card border border-port-border text-[9px] uppercase tracking-wider text-gray-400"
+ title={seriesName
+ ? `Introduced by series "${seriesName}" (${sourceSeriesId})`
+ : `Introduced by series ${sourceSeriesId}`}
+ >
+ {seriesName ? `from ${seriesName}` : 'from series'}
+ </span>
+ );
+}
+
// Wardrobes (A2) — collapsed summary by default; click to expand into an
// inline editor when `editable`. Per-field edits are buffered in a draft
// state and only PATCHed on blur, so a textarea keystroke doesn't fire a
@@ -227,6 +240,10 @@ export default function CanonCard({
// Optional — settings-only "Render clean plate" affordance. Called with
// `(entry)` so the parent can build the no-people prompt variant.
onRenderCleanPlate = null,
+ // Optional `{ [seriesId]: name }` lookup so the "from series" chip can
+ // render the actual series name. Null/empty falls back to the id-tooltip
+ // form for callers that don't have the map handy.
+ seriesNameMap = null,
}) {
const description = kind.descFor(entry);
const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : [];
@@ -282,12 +299,10 @@ export default function CanonCard({
</span>
) : null}
{entry.sourceSeriesId ? (
- <span
- className="inline-flex items-center px-1.5 py-0.5 rounded bg-port-card border border-port-border text-[9px] uppercase tracking-wider text-gray-400"
- title={`Introduced by series ${entry.sourceSeriesId}`}
- >
- from series
- </span>
+ <SourceSeriesChip
+ sourceSeriesId={entry.sourceSeriesId}
+ seriesName={seriesNameMap?.[entry.sourceSeriesId]}
+ />
) : null}
</div>
);
diff --git a/client/src/components/pipeline/CanonCard.test.jsx b/client/src/components/pipeline/CanonCard.test.jsx
new file mode 100644
index 0000000000..ca168f9c54
--- /dev/null
+++ b/client/src/components/pipeline/CanonCard.test.jsx
@@ -0,0 +1,74 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen } from '@testing-library/react';
+
+// CanonCard subscribes to live job progress via the socket-backed hook; the
+// chip-label code path doesn't touch it, but the hook would otherwise wire
+// up listeners during render. Stub it to a neutral resting state.
+vi.mock('../../hooks/useMediaJobProgress', () => ({
+ __esModule: true,
+ default: () => ({ status: 'unknown', filename: null, error: null }),
+}));
+
+// MediaJobThumb is rendered only when `inFlightJobId` is truthy — none of
+// these tests exercise that, so a stub keeps the test runtime self-contained.
+vi.mock('./MediaJobThumb', () => ({
+ __esModule: true,
+ default: () => null,
+}));
+
+import CanonCard from './CanonCard';
+
+const kind = {
+ key: 'characters',
+ label: 'Characters',
+ descFor: (e) => e.description || '',
+};
+
+const baseEntry = {
+ id: 'ent-1',
+ name: 'Lyra',
+ description: 'Cartographer-spy.',
+};
+
+const render_ = (props) => render(
+ <CanonCard
+ kind={kind}
+ entry={baseEntry}
+ onRender={() => {}}
+ {...props}
+ />
+);
+
+describe('CanonCard — "from series" provenance chip', () => {
+ it('omits the chip entirely when sourceSeriesId is absent', () => {
+ render_();
+ expect(screen.queryByText(/^from /)).not.toBeInTheDocument();
+ expect(screen.queryByText('from series')).not.toBeInTheDocument();
+ });
+
+ it('falls back to generic "from series" label + id tooltip when seriesNameMap is missing', () => {
+ render_({ entry: { ...baseEntry, sourceSeriesId: 'ser-abc' } });
+ const chip = screen.getByText('from series');
+ expect(chip).toBeInTheDocument();
+ expect(chip).toHaveAttribute('title', 'Introduced by series ser-abc');
+ });
+
+ it('renders the series name from seriesNameMap and includes id in tooltip', () => {
+ render_({
+ entry: { ...baseEntry, sourceSeriesId: 'ser-abc' },
+ seriesNameMap: { 'ser-abc': 'Phantom Pact' },
+ });
+ const chip = screen.getByText('from Phantom Pact');
+ expect(chip).toBeInTheDocument();
+ expect(chip).toHaveAttribute('title', 'Introduced by series "Phantom Pact" (ser-abc)');
+ });
+
+ it('falls back to generic label when sourceSeriesId is not present in seriesNameMap', () => {
+ render_({
+ entry: { ...baseEntry, sourceSeriesId: 'ser-missing' },
+ seriesNameMap: { 'ser-other': 'Other Series' },
+ });
+ expect(screen.getByText('from series')).toBeInTheDocument();
+ expect(screen.queryByText(/from ser-missing/)).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/pipeline/stages/NounsStage.jsx b/client/src/components/pipeline/stages/NounsStage.jsx
index 123b14dcf8..1c17f2a093 100644
--- a/client/src/components/pipeline/stages/NounsStage.jsx
+++ b/client/src/components/pipeline/stages/NounsStage.jsx
@@ -22,6 +22,7 @@ import toast from '../../ui/Toast';
import {
getUniverse, updateUniverse,
extractUniverseCanon, refineUniverseCharacter,
+ getUniverseCanonUsage,
} from '../../../services/apiUniverseBuilder';
import { getSettings, updateSettings, generateImage } from '../../../services/apiSystem';
import { listImageModels } from '../../../services/apiImageVideo';
@@ -150,6 +151,22 @@ export default function NounsStage({ issue, series }) {
return () => { cancelled = true; };
}, [series?.universeId, mountedRef]);
+ // Sibling-series name lookup for the canon-card "from <series>" chip.
+ // The current series is in `series.name`; everything else (including the
+ // entries that surface in the "Other series canon" details panel) needs the
+ // server-side aggregation. Failure is non-fatal — chips just fall back to
+ // the id-tooltip form.
+ const [seriesNameMap, setSeriesNameMap] = useState(null);
+ useEffect(() => {
+ if (!series?.universeId) { setSeriesNameMap(null); return; }
+ let cancelled = false;
+ getUniverseCanonUsage(series.universeId).then((u) => {
+ if (cancelled || !mountedRef.current) return;
+ setSeriesNameMap(u?.seriesNameMap || null);
+ }).catch(() => { /* non-fatal */ });
+ return () => { cancelled = true; };
+ }, [series?.universeId, mountedRef]);
+
const persistImageCfg = useCallback(async (next) => {
setImageCfg(next);
const current = await getSettings().catch(() => ({}));
@@ -396,6 +413,7 @@ export default function NounsStage({ issue, series }) {
refiningCharacterId={refiningCharacterId}
onPatchEntry={(entryId, patch) => handlePatchEntry(kind, entryId, patch)}
onRenderCleanPlate={handleRenderCleanPlate}
+ seriesNameMap={seriesNameMap}
/>
))}
@@ -413,7 +431,7 @@ export default function NounsStage({ issue, series }) {
);
}
-function KindSection({ kind, all, prose, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningCharacterId, onPatchEntry, onRenderCleanPlate }) {
+function KindSection({ kind, all, prose, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningCharacterId, onPatchEntry, onRenderCleanPlate, seriesNameMap }) {
const Icon = kind.icon;
const inIssue = useMemo(() => kind.match(prose, all), [prose, all, kind]);
const inIssueIds = useMemo(() => new Set(inIssue.map((e) => e.id || e.name)), [inIssue]);
@@ -459,6 +477,7 @@ function KindSection({ kind, all, prose, renderingJobs, onRender, onJobCompleted
refineDisabled={!!refiningCharacterId && refiningCharacterId !== entry.id}
onPatchEntry={onPatchEntry}
onRenderCleanPlate={onRenderCleanPlate}
+ seriesNameMap={seriesNameMap}
/>
))}
</ul>
@@ -487,6 +506,7 @@ function KindSection({ kind, all, prose, renderingJobs, onRender, onJobCompleted
refineDisabled={!!refiningCharacterId && refiningCharacterId !== entry.id}
onPatchEntry={onPatchEntry}
onRenderCleanPlate={onRenderCleanPlate}
+ seriesNameMap={seriesNameMap}
/>
))}
</ul>
diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsx
index 7cb11e8cd2..722586740d 100644
--- a/client/src/components/universe/UniverseCanonSection.jsx
+++ b/client/src/components/universe/UniverseCanonSection.jsx
@@ -473,6 +473,7 @@ export default function UniverseCanonSection({ universe, universeId, onUniverseC
togglingLockId={togglingLockId}
onPatchEntry={(entryId, patch) => handlePatchEntry(kind, entryId, patch)}
onRenderCleanPlate={handleRenderCleanPlate}
+ seriesNameMap={usage?.seriesNameMap || null}
/>
))}
@@ -481,7 +482,7 @@ export default function UniverseCanonSection({ universe, universeId, onUniverseC
);
}
-function KindSection({ kind, all, totalCount, filtered, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate }) {
+function KindSection({ kind, all, totalCount, filtered, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate, seriesNameMap }) {
const Icon = kind.icon;
return (
<section className="rounded border border-port-border bg-port-bg/60">
@@ -517,6 +518,7 @@ function KindSection({ kind, all, totalCount, filtered, usage, renderingJobs, on
togglingLock={togglingLockId === entry.id}
onPatchEntry={onPatchEntry}
onRenderCleanPlate={onRenderCleanPlate}
+ seriesNameMap={seriesNameMap}
/>
))}
</ul>
diff --git a/server/services/canonUsage.js b/server/services/canonUsage.js
index a61b20ef28..84d2ab3742 100644
--- a/server/services/canonUsage.js
+++ b/server/services/canonUsage.js
@@ -43,6 +43,7 @@ function corpusForIssue(issue) {
* characters: { [entryId]: [{ seriesId, seriesName, issueIds, issueCount }, ...] },
* settings: { [entryId]: [...] },
* objects: { [entryId]: [...] },
+ * seriesNameMap: { [seriesId]: seriesName }, // every linked series, even ones with no prose match
* seriesCount, // how many series link to this universe
* issueCount, // total issues scanned
* }
@@ -54,6 +55,10 @@ export async function getUniverseCanonUsage(universeId) {
const allSeries = await listSeries();
const linkedSeries = allSeries.filter((s) => s.universeId === universeId);
+ // Cover entries whose `sourceSeriesId` points at a linked series that has no
+ // prose-match — the per-entry rows would otherwise miss that series, but the
+ // chip-label lookup on the client still needs its name.
+ const seriesNameMap = Object.fromEntries(linkedSeries.map((s) => [s.id, s.name]));
// Per (kind, entryId) → Map(seriesId → { seriesName, issueIds: Set })
const tally = { characters: new Map(), settings: new Map(), objects: new Map() };
@@ -107,6 +112,7 @@ export async function getUniverseCanonUsage(universeId) {
characters: shape(tally.characters),
settings: shape(tally.settings),
objects: shape(tally.objects),
+ seriesNameMap,
seriesCount: linkedSeries.length,
issueCount,
};
diff --git a/server/services/canonUsage.test.js b/server/services/canonUsage.test.js
new file mode 100644
index 0000000000..f59b7e1149
--- /dev/null
+++ b/server/services/canonUsage.test.js
@@ -0,0 +1,69 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock the three collaborators canonUsage pulls from — universe storage, the
+// series store, and the issue store. Each test seeds the fixtures directly
+// so the assertions are deterministic without hitting disk.
+const mockUniverses = new Map();
+const mockSeriesList = [];
+const mockIssuesBySeries = new Map();
+
+vi.mock('./universeBuilder.js', () => ({
+ getUniverse: vi.fn(async (id) => {
+ const u = mockUniverses.get(id);
+ if (!u) throw new Error(`Universe not found: ${id}`);
+ return u;
+ }),
+}));
+
+vi.mock('./pipeline/series.js', () => ({
+ listSeries: vi.fn(async () => [...mockSeriesList]),
+}));
+
+vi.mock('./pipeline/issues.js', () => ({
+ listIssues: vi.fn(async ({ seriesId }) => mockIssuesBySeries.get(seriesId) || []),
+}));
+
+const { getUniverseCanonUsage } = await import('./canonUsage.js');
+
+beforeEach(() => {
+ mockUniverses.clear();
+ mockSeriesList.length = 0;
+ mockIssuesBySeries.clear();
+});
+
+describe('canonUsage — seriesNameMap', () => {
+ it('includes every linked series, even ones with no prose match', async () => {
+ mockUniverses.set('uni-1', {
+ id: 'uni-1',
+ characters: [{ id: 'char-1', name: 'Lyra', sourceSeriesId: 'ser-quiet' }],
+ settings: [],
+ objects: [],
+ });
+ mockSeriesList.push(
+ { id: 'ser-active', name: 'Phantom Pact', universeId: 'uni-1' },
+ // Linked but has no issues / no prose match — must still appear in the
+ // map so the CanonCard chip can render its name for entries stamped
+ // with sourceSeriesId='ser-quiet'.
+ { id: 'ser-quiet', name: 'Silent Series', universeId: 'uni-1' },
+ // Different universe — must NOT leak into this universe's lookup.
+ { id: 'ser-other', name: 'Other Universe', universeId: 'uni-2' },
+ );
+ mockIssuesBySeries.set('ser-active', [
+ { id: 'iss-1', stages: { prose: { output: 'A long prose passage.' } } },
+ ]);
+
+ const usage = await getUniverseCanonUsage('uni-1');
+ expect(usage.seriesNameMap).toEqual({
+ 'ser-active': 'Phantom Pact',
+ 'ser-quiet': 'Silent Series',
+ });
+ expect(usage.seriesCount).toBe(2);
+ });
+
+ it('returns an empty map when no series link to the universe', async () => {
+ mockUniverses.set('uni-empty', { id: 'uni-empty', characters: [], settings: [], objects: [] });
+ const usage = await getUniverseCanonUsage('uni-empty');
+ expect(usage.seriesNameMap).toEqual({});
+ expect(usage.seriesCount).toBe(0);
+ });
+});