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: Universe-as-Canon — lock canon entries, auto-lock series extracts, backfill from categories

[._.]/ Adam Eivyb87d1f505dfb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b661ffc315..09957dbd5f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,56 @@
## Added
+- **Universe-as-Canon lock semantics — series-extracted canon arrives auto-locked.**
+ Every canon entry on a universe (characters/settings/objects) can now carry a
+ `locked: true` flag, plus `prompt`, `tags`, `source`, and `sourceSeriesId`
+ fields. When a series with a linked universe runs prose extraction (`prose`
+ stage auto-extract or the `/extract-bible` route), every NEW canon entry it
+ inserts is stamped `source: 'series-extract'`, `sourceSeriesId: series.id`,
+ and `locked: true`. This protects an active series's canon from being
+ silently rewritten by a later refine / re-extract / differentiate-cast pass
+ against the universe — the human operator unlocks the entry first when they
+ want regeneration to touch it.
+ - **Refine + Differentiate honor locks.** `POST /:id/characters/:entryId/refine`
+ returns 409 (`UNIVERSE_CANON_LOCKED`) on a locked character. The
+ `differentiate-cast` flow sends the full cast to the LLM (so unlocked
+ rewrites stay distinct from locked descriptions) but discards rewrites
+ targeting locked ids at apply time — locked `physicalDescription` round-
+ trips verbatim. New `skippedLocked` count surfaces alongside the existing
+ `touched` / `skipped` counts in the response.
+ - **`mergeExtractedBible` lock-aware semantics.** Locked entries pass
+ through narrative-field overwrites intact; only `evidence[]` is appended
+ (deduped) so the crossover trail still grows across multiple extractions.
+ `firstAppearance` and `missingFromProse` are not touched on locked
+ entries.
+ - **Categories→canon backfill on first read.** v1 universes (no
+ `schemaVersion` on disk) load through `sanitizeTemplate` and have every
+ `categories[key].variations[i]` copied into the matching canon array as a
+ new entry — characters → `characters[]`, landscapes/environments →
+ `settings[]` (tagged `landscape` / `environment`), vehicles/structures →
+ `objects[]` (tagged `vehicle` / `structure`), and any custom category
+ bucket flows into `objects[]` tagged with the bucket name. The migration
+ is idempotent (`schemaVersion: 2` stamped after first read and persisted
+ so user-renamed entries survive subsequent loads). Categories continue to
+ coexist with canon arrays during the UI transition; a follow-up retires
+ `categories` once the UI reads canon directly.
+ - **New lock-toggle route.** `PATCH /api/universe-builder/:id/canon/:kind/:entryId/lock`
+ with `{ locked: boolean }` toggles a single entry's lock. Unlock strips
+ the field entirely so the on-disk shape stays minimal (only `true` is
+ persisted, mirroring the variation pattern).
+ - **Source vocabulary.** Legacy `source: 'user' | 'ai' | 'imported'`
+ accepted on read for back-compat; new universe-canon writes use the
+ semantic `source: 'universe-expand' | 'series-extract' | 'manual'`
+ vocabulary. Writers-room flows continue to write the legacy values, so
+ the existing badge UI in `CharactersBible.jsx` / `SettingsBible.jsx` /
+ `ObjectsBible.jsx` is unaffected.
+ - **Tests.** 8 new storyBible cases (sanitizer extras + lock-aware merge +
+ autoLock provenance), 3 new universeBuilder cases (backfill + idempotence
+ + no-overwrite), and a new `universeCanon.test.js` file with 10 cases
+ covering `setCanonEntryLock` + refine refuses locked + differentiate
+ skips locked + extract autoLock pass-through. Full server suite (4,525
+ tests) passes.
+
- **Universe canon — characters, places, and objects on the universe.** Phase A
of the Universe-as-canon refactor. `universe.characters[]`/`settings[]`/
`objects[]` arrays now live on the universe record alongside the existing
diff --git a/PLAN.md b/PLAN.md
index 611f109b93..5b24bb2e29 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -27,6 +27,16 @@ The world model is now a Marvel-style **universe** carrying canonical entities (
- [ ] Filter the Universe Canon page by "in series X" — when one universe holds multiple shows, the user wants to see only canon that's relevant to the show they're working on. New URL param `?series=<id>` + a series picker dropdown in the header. Reuses the existing `canonUsage` to derive the per-series subset.
- [ ] Per-series `stylePrompt` override — let one series in a universe deviate slightly without forking the whole universe (e.g., noir spin-off). Wire `series.stylePromptOverride` into `composeStyledPrompt` ahead of the universe's stylePrompt; UI on the series page.
+**Universe-as-Canon Phase 2 — unified Builder UI + categories retirement.**
+
+The server-side lock + provenance + backfill foundation shipped 2026-05-14 (see NEXT.md). The UI still shows the legacy two-page split (Builder for categories/composites, separate Canon page for characters/settings/objects). Follow-up to land the user-visible piece:
+
+- [ ] **Extract shared CanonCard.** Pull `CanonCard` + `KindSection` out of `client/src/pages/UniverseCanon.jsx` into `client/src/components/universe/CanonCard.jsx`. Add a lock-toggle icon (wired to the new `PATCH /api/universe-builder/:id/canon/:kind/:entryId/lock` route), a "from series: <name>" provenance badge when `sourceSeriesId` is set, and tag chips. Disable Refine + Render buttons when locked; show "Unlock to edit" affordance.
+- [ ] **Fold canon into UniverseBuilder.jsx.** Replace the existing categories grid with three kind-sections (Characters / Settings / Objects) rendered from `universe.characters[]` / `settings[]` / `objects[]` using the shared `CanonCard`. Each section gets a "+ Add" inline modal (calls `PATCH /:id` with the new entry spliced into the kind array) + tag filter chip row that filters by `entry.tags.includes(activeTag)`. Move the "Extract from prose" button into the page header. Keep composite sheets as their own section unchanged.
+- [ ] **Retire the standalone Canon page + route.** Replace `client/src/pages/UniverseCanon.jsx` with a `<Navigate to={`/world-builder/${id}#canon-characters`}>` (or delete + drop the route in `App.jsx`). Update `server/lib/navManifest.js` to drop the `nav.world-builder.canon` entry (or repoint to the Builder anchor); confirm `Layout.jsx` sidebar matches. Update `server/lib/navManifest.test.js` + `server/routes/palette.test.js`.
+- [ ] **Retire `universe.categories` on the schema.** After the UI no longer reads it: drop `categories` from `sanitizeTemplate`, the route Zod schemas (`createSchema`, `patchSchema`, `expandSchema`, `refinePromptsSchema`, `selectionSchema`), the expand prompt template, `universeBuilderRefine.js`'s `mergeCategoriesWithLocks`, the `compilePrompts` `'variations'`/`'all'` branches (replaced by per-kind canon rendering), and `WORLD_CATEGORIES` + `VARIATIONS_PER_CATEGORY_MAX` + related exports in `universeBuilder.js`. The backfill helper stays as a one-time data-migration utility (move it to `server/scripts/` if/when the in-memory backfill is no longer needed).
+- [ ] **Universe expand LLM contract enrichment.** Today expand emits `categories[key].variations[]` which the backfill converts to canon. Future enhancement: ask the LLM directly for `characters[]` / `settings[]` / `objects[]` with rich narrative metadata (role/personality/background for characters, slugline/era/palette for settings) alongside the visual `prompt` so the initial universe ships with usable canon depth instead of name-only stubs. Update `universeBuilderExpand.js`'s LLM prompt + the expand response normalizer. Composite sheets stay unchanged.
+
**Universe-Canon image-anchor follow-up (bigger).**
- [ ] Use rendered reference images as image-to-image anchors in downstream comic-page renders for models that support it. Codex can't accept image references; for SDXL / Flux pipelines, the per-character rendered ref could anchor every panel render. Touch: `composeComicPagePrompt` + the image-gen dispatcher. Related: existing PLAN item "Solidify characters before visual render" below (under Pipeline continuity gaps) — the universe-canon work already provides the storage; the "solidify" pass is the LLM step that merges accumulated evidence into one canonical description, and the new "AI: differentiate cast" button is its sibling (push apart vs. distill).
diff --git a/server/lib/storyBible.js b/server/lib/storyBible.js
index 737189b75a..d6edec366c 100644
--- a/server/lib/storyBible.js
+++ b/server/lib/storyBible.js
@@ -42,9 +42,26 @@ export const BIBLE_LIMITS = Object.freeze({
SIGNIFICANCE_MAX: 1000,
// Per-bible cap (universal — protects against runaway extraction)
ENTRIES_PER_BIBLE_MAX: 200,
+ PROMPT_MAX: 2000,
+ TAG_MAX: 60,
+ TAGS_PER_ENTRY_MAX: 12,
+ SOURCE_SERIES_ID_MAX: 64,
});
-const SOURCES = new Set(['user', 'ai', 'imported']);
+// Canonical provenance vocabulary. `BIBLE_SOURCE.SERIES_EXTRACT` is the
+// default for new bible-extracted entries; `UNIVERSE_EXPAND` is stamped on
+// canon backfilled from a v1 universe's categories; `MANUAL` is user-authored.
+// Legacy values ('user' / 'ai' / 'imported') are accepted on read so existing
+// data round-trips; nothing in the codebase coerces them.
+export const BIBLE_SOURCE = Object.freeze({
+ UNIVERSE_EXPAND: 'universe-expand',
+ SERIES_EXTRACT: 'series-extract',
+ MANUAL: 'manual',
+});
+const SOURCES = new Set([
+ ...Object.values(BIBLE_SOURCE),
+ 'user', 'ai', 'imported',
+]);
export const BIBLE_KIND = Object.freeze({
CHARACTER: 'character',
@@ -65,13 +82,17 @@ export const BIBLE_FIELD = Object.freeze({
// added here flows through without touching every walker.
export const BIBLE_KEYS = Object.freeze(Object.values(BIBLE_FIELD));
+// Frozen list of kind values — for route/Zod kind validation, lock-toggle
+// dispatch, and any caller that needs to enumerate kinds.
+export const BIBLE_KINDS = Object.freeze(Object.values(BIBLE_KIND));
+
// Fields the bible-extraction prompt cares about. Routed both into the
// `existing<X>Json` prompt variable (bibleExtractor) and into the script
// stage's bibles context (evaluator). Excludes ids/timestamps/source/notes.
export const PROMPT_FIELDS = Object.freeze({
- [BIBLE_KIND.CHARACTER]: ['name', 'aliases', 'role', 'physicalDescription', 'personality', 'background'],
- [BIBLE_KIND.SETTING]: ['name', 'slugline', 'description', 'palette', 'era', 'weather', 'recurringDetails'],
- [BIBLE_KIND.OBJECT]: ['name', 'aliases', 'description', 'significance'],
+ [BIBLE_KIND.CHARACTER]: ['name', 'aliases', 'role', 'physicalDescription', 'personality', 'background', 'prompt', 'tags'],
+ [BIBLE_KIND.SETTING]: ['name', 'slugline', 'description', 'palette', 'era', 'weather', 'recurringDetails', 'prompt', 'tags'],
+ [BIBLE_KIND.OBJECT]: ['name', 'aliases', 'description', 'significance', 'prompt', 'tags'],
});
export function pickPromptFields(kind, entry) {
@@ -123,6 +144,8 @@ function ensureId(raw, idPrefix) {
}
function ensureSource(raw) {
+ // Default 'user' preserves the writers-room badge UI; universe-canon callers
+ // pass `BIBLE_SOURCE.*` explicitly.
return SOURCES.has(raw) ? raw : 'user';
}
@@ -130,6 +153,20 @@ function ensureFirstAppearance(raw) {
return isStr(raw) && raw.trim() ? raw.trim().slice(0, 200) : null;
}
+// Shared canon extras applied to every kind. `locked` follows the on-disk
+// minimization pattern from universe-builder variations: only `true` is
+// persisted, missing/false collapses to absent.
+function applyCanonExtras(raw) {
+ const out = {
+ prompt: trimTo(raw.prompt, BIBLE_LIMITS.PROMPT_MAX),
+ tags: cleanStringArray(raw.tags, BIBLE_LIMITS.TAG_MAX, BIBLE_LIMITS.TAGS_PER_ENTRY_MAX),
+ source: ensureSource(raw.source),
+ sourceSeriesId: trimTo(raw.sourceSeriesId, BIBLE_LIMITS.SOURCE_SERIES_ID_MAX) || null,
+ };
+ if (raw.locked === true) out.locked = true;
+ return out;
+}
+
// Accepts the writers-room shape natively; legacy pipeline `description`
// is treated as `physicalDescription` when the latter is empty so old
// series.json migrates forward on first save. TODO(item-4): drop the
@@ -156,7 +193,7 @@ export function sanitizeCharacter(raw, { idPrefix = DEFAULT_ID_PREFIX.character,
firstAppearance: ensureFirstAppearance(raw.firstAppearance),
evidence: cleanStringArray(raw.evidence, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),
missingFromProse: cleanStringArray(raw.missingFromProse, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),
- source: ensureSource(raw.source),
+ ...applyCanonExtras(raw),
createdAt: created,
updatedAt: preserveTimestamps && isStr(raw.updatedAt) ? raw.updatedAt : nowIso(),
};
@@ -184,7 +221,7 @@ export function sanitizeSetting(raw, { idPrefix = DEFAULT_ID_PREFIX.setting, pre
firstAppearance: ensureFirstAppearance(raw.firstAppearance),
evidence: cleanStringArray(raw.evidence, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),
missingFromProse: cleanStringArray(raw.missingFromProse, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),
- source: ensureSource(raw.source),
+ ...applyCanonExtras(raw),
createdAt: created,
updatedAt: preserveTimestamps && isStr(raw.updatedAt) ? raw.updatedAt : nowIso(),
};
@@ -206,7 +243,7 @@ export function sanitizeObject(raw, { idPrefix = DEFAULT_ID_PREFIX.object, prese
firstAppearance: ensureFirstAppearance(raw.firstAppearance),
evidence: cleanStringArray(raw.evidence, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),
missingFromProse: cleanStringArray(raw.missingFromProse, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),
- source: ensureSource(raw.source),
+ ...applyCanonExtras(raw),
createdAt: created,
updatedAt: preserveTimestamps && isStr(raw.updatedAt) ? raw.updatedAt : nowIso(),
};
@@ -322,8 +359,22 @@ const sortKey = (kind) => (entry) => {
* - prose-derived fields (firstAppearance/evidence/missingFromProse)
* refresh verbatim including explicit nulls
* - blank key fields backfill from incoming + re-index
+ *
+ * Lock semantics: when an existing matched entry has `locked === true`,
+ * field backfills + prose-field rewrites are skipped — only `evidence[]`
+ * appends (deduped) so the crossover trail still accumulates. `autoLock`
+ * stamps new inserts as locked + carries `sourceSeriesId` so a series-driven
+ * extraction cannot be silently rewritten by a later AI pass.
+ *
+ * Default source stays 'ai' (legacy) so writers-room badge UI is unaffected;
+ * universe-canon callers pass `BIBLE_SOURCE.*` explicitly.
*/
-export function mergeExtractedBible(existing, incoming, kind, { idPrefix = DEFAULT_ID_PREFIX[kind] } = {}) {
+export function mergeExtractedBible(existing, incoming, kind, {
+ idPrefix = DEFAULT_ID_PREFIX[kind],
+ source = 'ai',
+ autoLock = false,
+ sourceSeriesId = null,
+} = {}) {
if (!Array.isArray(existing)) existing = [];
const keyOf = sortKey(kind);
if (!Array.isArray(incoming)) {
@@ -335,6 +386,20 @@ export function mergeExtractedBible(existing, incoming, kind, { idPrefix = DEFAU
const map = new Map();
for (const e of existing) indexEntry(map, e, cfg.keyFields);
+ const appendEvidence = (current, additions) => {
+ const out = Array.isArray(current) ? [...current] : [];
+ const seen = new Set(out.map(normalizeBibleName));
+ const trimmed = cleanStringArray(additions, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX);
+ for (const item of trimmed) {
+ const key = normalizeBibleName(item);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push(item);
+ if (out.length >= BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX) break;
+ }
+ return out;
+ };
+
for (const rawIncoming of incoming) {
if (!rawIncoming || typeof rawIncoming !== 'object') continue;
// Sanitize the incoming entry through the same shape the existing
@@ -344,6 +409,13 @@ export function mergeExtractedBible(existing, incoming, kind, { idPrefix = DEFAU
if (!sane) continue;
const found = lookupExisting(map, sane, cfg.keyFields);
if (found) {
+ if (found.locked === true) {
+ if ('evidence' in rawIncoming) {
+ found.evidence = appendEvidence(found.evidence, sane.evidence);
+ }
+ found.updatedAt = nowIso();
+ continue;
+ }
for (const field of cfg.userEditable) {
if (isBlank(found[field]) && !isBlank(sane[field])) {
found[field] = sane[field];
@@ -375,7 +447,9 @@ export function mergeExtractedBible(existing, incoming, kind, { idPrefix = DEFAU
// Without this, the merged entries would silently truncate on next
// read.
if (existing.length >= BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX) continue;
- const inserted = { ...sane, source: 'ai' };
+ const inserted = { ...sane, source };
+ if (sourceSeriesId) inserted.sourceSeriesId = sourceSeriesId;
+ if (autoLock) inserted.locked = true;
existing.push(inserted);
indexEntry(map, inserted, cfg.keyFields);
}
diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.js
index 2270d11b9e..e3f0fc4c73 100644
--- a/server/lib/storyBible.test.js
+++ b/server/lib/storyBible.test.js
@@ -96,6 +96,56 @@ describe('storyBible — sanitizeCharacter', () => {
const out = sanitizeCharacter({ name: 'A', aliases: ['', ' ', null, 42, 'real'] });
expect(out.aliases).toEqual(['real']);
});
+
+ // ---- Universe-as-Canon extras: prompt / tags / locked / source / sourceSeriesId ----
+
+ it('accepts Universe-as-Canon extras: prompt + tags + sourceSeriesId', () => {
+ const out = sanitizeCharacter({
+ name: 'Alex',
+ prompt: 'field lead detective, expressive face, short jacket',
+ tags: ['protagonist', 'detective'],
+ sourceSeriesId: 'ser-1234',
+ });
+ expect(out.prompt).toBe('field lead detective, expressive face, short jacket');
+ expect(out.tags).toEqual(['protagonist', 'detective']);
+ expect(out.sourceSeriesId).toBe('ser-1234');
+ });
+
+ it('persists locked: true and accepts the new source vocabulary', () => {
+ const out = sanitizeCharacter({ name: 'Alex', locked: true, source: 'series-extract' });
+ expect(out.locked).toBe(true);
+ expect(out.source).toBe('series-extract');
+ });
+
+ it('omits locked when not strictly true (mirrors variation pattern)', () => {
+ expect(sanitizeCharacter({ name: 'A', locked: false }).locked).toBeUndefined();
+ expect(sanitizeCharacter({ name: 'A', locked: 'yes' }).locked).toBeUndefined();
+ expect(sanitizeCharacter({ name: 'A', locked: 1 }).locked).toBeUndefined();
+ expect(sanitizeCharacter({ name: 'A' }).locked).toBeUndefined();
+ });
+
+ it('caps tags + prompt + sourceSeriesId at their limits', () => {
+ const longPrompt = 'p'.repeat(BIBLE_LIMITS.PROMPT_MAX + 50);
+ const tooManyTags = Array.from({ length: BIBLE_LIMITS.TAGS_PER_ENTRY_MAX + 5 }, (_, i) => `tag-${i}`);
+ const longSrc = 's'.repeat(BIBLE_LIMITS.SOURCE_SERIES_ID_MAX + 10);
+ const out = sanitizeCharacter({
+ name: 'A', prompt: longPrompt, tags: tooManyTags, sourceSeriesId: longSrc,
+ });
+ expect(out.prompt.length).toBe(BIBLE_LIMITS.PROMPT_MAX);
+ expect(out.tags.length).toBe(BIBLE_LIMITS.TAGS_PER_ENTRY_MAX);
+ expect(out.sourceSeriesId.length).toBe(BIBLE_LIMITS.SOURCE_SERIES_ID_MAX);
+ });
+
+ it('extras apply identically to settings + objects', () => {
+ const s = sanitizeSetting({ name: 'Bubble Room', tags: ['indoor'], prompt: 'pastel lab', locked: true });
+ expect(s.tags).toEqual(['indoor']);
+ expect(s.prompt).toBe('pastel lab');
+ expect(s.locked).toBe(true);
+ const o = sanitizeObject({ name: 'Ward Tape', tags: ['prop', 'recurring'], prompt: 'striped tape coil', source: 'manual' });
+ expect(o.tags).toEqual(['prop', 'recurring']);
+ expect(o.prompt).toBe('striped tape coil');
+ expect(o.source).toBe('manual');
+ });
});
describe('storyBible — sanitizeSetting', () => {
@@ -223,6 +273,51 @@ describe('storyBible — mergeExtractedBible (characters)', () => {
const merged = mergeExtractedBible(existing, incoming, 'character');
expect(merged.length).toBe(BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX);
});
+
+ // ---- Universe-as-Canon lock-aware merge ----
+
+ it('locked existing entry: skips field overwrites, appends new evidence (deduped)', () => {
+ const existing = [sanitizeCharacter({
+ id: 'c1', name: 'Alex', physicalDescription: 'jacket with bright piping',
+ role: 'Field Lead', personality: 'calm menace', evidence: ['Issue 1 prose'],
+ locked: true, source: 'series-extract',
+ })];
+ const merged = mergeExtractedBible(existing, [{
+ name: 'Alex',
+ physicalDescription: 'rewritten attempt',
+ role: 'rewritten role',
+ personality: 'rewritten',
+ evidence: ['Issue 1 prose', 'Issue 3 prose'], // first is dupe, second is new
+ firstAppearance: 'should-be-ignored',
+ }], 'character');
+ expect(merged.length).toBe(1);
+ const alex = merged[0];
+ // Narrative fields round-trip verbatim — locked entries are protected.
+ expect(alex.physicalDescription).toBe('jacket with bright piping');
+ expect(alex.role).toBe('Field Lead');
+ expect(alex.personality).toBe('calm menace');
+ expect(alex.firstAppearance).toBeNull();
+ // Evidence accumulates: dedupe by case-insensitive trimmed string.
+ expect(alex.evidence).toEqual(['Issue 1 prose', 'Issue 3 prose']);
+ // Lock survives.
+ expect(alex.locked).toBe(true);
+ });
+
+ it('autoLock option stamps locked: true + sourceSeriesId on new inserts', () => {
+ const merged = mergeExtractedBible([], [{ name: 'Beta' }], 'character', {
+ source: 'series-extract', autoLock: true, sourceSeriesId: 'ser-active',
+ });
+ expect(merged.length).toBe(1);
+ expect(merged[0].locked).toBe(true);
+ expect(merged[0].source).toBe('series-extract');
+ expect(merged[0].sourceSeriesId).toBe('ser-active');
+ });
+
+ it('autoLock false (default) inserts unlocked entries — legacy behavior preserved', () => {
+ const merged = mergeExtractedBible([], [{ name: 'Beta' }], 'character');
+ expect(merged[0].locked).toBeUndefined();
+ expect(merged[0].source).toBe('ai'); // legacy default
+ });
});
describe('storyBible — mergeExtractedBible (settings)', () => {
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index bf2e5e1383..b4a8705edc 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -18,6 +18,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import * as svc from '../services/universeBuilder.js';
import * as canonSvc from '../services/universeCanon.js';
+import { BIBLE_KINDS } from '../lib/storyBible.js';
import { getUniverseCanonUsage } from '../services/canonUsage.js';
import { expandWorldTemplate } from '../services/universeBuilderExpand.js';
import { refineWorldPrompts } from '../services/universeBuilderRefine.js';
@@ -438,4 +439,24 @@ router.get('/:id/canon-usage', asyncHandler(async (req, res) => {
res.json(result);
}));
+// Lock toggle for canon entries. Locked entries are protected from AI rewrite
+// paths (refine, differentiate, re-extract field overwrites).
+const setLockSchema = z.object({
+ locked: z.boolean(),
+});
+const lockParamsSchema = z.object({
+ kind: z.enum(BIBLE_KINDS),
+});
+router.patch('/:id/canon/:kind/:entryId/lock', asyncHandler(async (req, res) => {
+ const { kind } = validateRequest(lockParamsSchema, req.params);
+ const body = validateRequest(setLockSchema, req.body ?? {});
+ const result = await canonSvc.setCanonEntryLock(
+ req.params.id,
+ kind,
+ req.params.entryId,
+ body.locked,
+ ).catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
export default router;
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index a05506f76b..a8e9404f59 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -15,7 +15,7 @@ import { randomUUID } from 'crypto';
import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';
import {
sanitizeBibleList, mergeExtractedBible,
- BIBLE_LIMITS, BIBLE_KIND, BIBLE_FIELD, BIBLE_KEYS,
+ BIBLE_LIMITS, BIBLE_KIND, BIBLE_FIELD, BIBLE_KEYS, BIBLE_SOURCE,
isStr, trimTo,
} from '../../lib/storyBible.js';
import { sanitizeArc, sanitizeSeasonList } from '../../lib/storyArc.js';
@@ -227,16 +227,19 @@ export async function purgeImageRefFromAllSeries(filename) {
export async function extractAndMergeIntoSeries(seriesId, opts = {}) {
const series = await getSeries(seriesId);
- // Phase B.3 routing: if the series links to a universe, extract into the
- // universe (single source of truth) and return a compatible shape so
- // every legacy caller (auto-extract in textStages, season:episodes
- // autorun, the /extract-bible route) keeps working without a fork.
+ // Phase B.3 routing: when the series links to a universe, extract into the
+ // universe and return a compatible shape so every legacy caller keeps
+ // working without a fork. New entries arrive auto-locked + tagged with this
+ // series so a later refine/differentiate cannot silently rewrite them.
if (series.universeId) {
- // Dynamic import to avoid a circular dep — universeCanon → series.js
- // (for updateSeries, indirectly) and back here would deadlock on
- // module-init otherwise.
+ // Dynamic import avoids a circular dep through universeCanon → series.js.
const { extractCanonFromProse } = await import('../universeCanon.js');
- const { universe, results } = await extractCanonFromProse(series.universeId, opts);
+ const { universe, results } = await extractCanonFromProse(series.universeId, {
+ ...opts,
+ source: BIBLE_SOURCE.SERIES_EXTRACT,
+ autoLock: true,
+ sourceSeriesId: series.id,
+ });
return { series, universe, results };
}
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index 87df81082f..4507a9d865 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -26,7 +26,14 @@ import { join } from 'path';
import { randomUUID } from 'crypto';
import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';
import { composeStyledPrompt } from '../lib/composeStyledPrompt.js';
-import { sanitizeBibleList, BIBLE_KIND } from '../lib/storyBible.js';
+import {
+ sanitizeBibleList, BIBLE_KIND, BIBLE_FIELD, BIBLE_LIMITS, BIBLE_SOURCE,
+ normalizeBibleName,
+} from '../lib/storyBible.js';
+
+// Bumped when a sanitizer-time backfill changes how on-disk universes are
+// shaped, so future migrations can gate on the prior version.
+export const CURRENT_SCHEMA_VERSION = 2;
const STATE_PATH = join(PATHS.data, 'universe-builder.json');
@@ -100,9 +107,9 @@ export const LOCKABLE_FIELD_LABELS = Object.freeze({
export const INFLUENCE_LOCK_FIELDS = Object.freeze(['influencesEmbrace', 'influencesAvoid']);
export const isInfluenceLockField = (key) => INFLUENCE_LOCK_FIELDS.includes(key);
-// Starter buckets the UI surfaces for a fresh universe. They remain for
-// compatibility, but saved templates may carry any additional sanitized
-// category keys the LLM or user creates.
+// Legacy buckets the v1 universe schema used. Retires after Phase 2 UI reads
+// canon directly — until then it's still consumed by existing expand / refine
+// / route code.
export const WORLD_CATEGORIES = Object.freeze([
'landscapes',
'environments',
@@ -111,6 +118,18 @@ export const WORLD_CATEGORIES = Object.freeze([
'vehicles',
]);
+// Maps v1 category buckets to canon kinds + tags. Unknown keys fall to
+// object (catch-all kind) tagged with the bucket name.
+const CATEGORY_TO_CANON = Object.freeze({
+ characters: { kind: BIBLE_KIND.CHARACTER, tags: [] },
+ landscapes: { kind: BIBLE_KIND.SETTING, tags: ['landscape'] },
+ environments: { kind: BIBLE_KIND.SETTING, tags: ['environment'] },
+ structures: { kind: BIBLE_KIND.OBJECT, tags: ['structure'] },
+ vehicles: { kind: BIBLE_KIND.OBJECT, tags: ['vehicle'] },
+});
+const resolveCanonForCategory = (categoryKey) =>
+ CATEGORY_TO_CANON[categoryKey] || { kind: BIBLE_KIND.OBJECT, tags: [categoryKey] };
+
const DEFAULT_STATE = { universes: [], runs: [] };
const isStr = (v) => typeof v === 'string';
@@ -324,6 +343,68 @@ export const sanitizeCompositeSheets = (raw = []) => {
return sheets;
};
+// Backfill canon arrays from v1 `categories[].variations[]`. Idempotent:
+// entries matching an existing canon name (case-insensitive) are skipped, so
+// hand-authored / series-extracted records are never overwritten. Categories
+// stay intact during the transition; Phase 2 UI retires them.
+function backfillCanonFromCategories(raw, existingCanon) {
+ // v2 hot path — already backfilled. Sanitize through the kind sanitizers
+ // once and return; no category scan needed.
+ if (raw.schemaVersion >= CURRENT_SCHEMA_VERSION) {
+ return {
+ characters: sanitizeBibleList(existingCanon.characters, BIBLE_KIND.CHARACTER),
+ settings: sanitizeBibleList(existingCanon.settings, BIBLE_KIND.SETTING),
+ objects: sanitizeBibleList(existingCanon.objects, BIBLE_KIND.OBJECT),
+ schemaVersion: raw.schemaVersion,
+ };
+ }
+
+ const next = {
+ characters: Array.isArray(existingCanon.characters) ? [...existingCanon.characters] : [],
+ settings: Array.isArray(existingCanon.settings) ? [...existingCanon.settings] : [],
+ objects: Array.isArray(existingCanon.objects) ? [...existingCanon.objects] : [],
+ };
+ const nameSeen = {
+ characters: new Set(next.characters.map((e) => normalizeBibleName(e?.name))),
+ settings: new Set(next.settings.map((e) => normalizeBibleName(e?.name))),
+ objects: new Set(next.objects.map((e) => normalizeBibleName(e?.name))),
+ };
+
+ const categories = raw && typeof raw.categories === 'object' ? raw.categories : {};
+ for (const [rawKey, value] of Object.entries(categories)) {
+ const categoryKey = normalizeCategoryKey(rawKey) || rawKey;
+ const { kind, tags } = resolveCanonForCategory(categoryKey);
+ const targetField = BIBLE_FIELD[kind];
+ const variations = Array.isArray(value?.variations) ? value.variations : [];
+ for (const variation of variations) {
+ const label = trimTo(variation?.label, BIBLE_LIMITS.NAME_MAX);
+ if (!label) continue;
+ const nameKey = normalizeBibleName(label);
+ if (nameSeen[targetField].has(nameKey)) continue;
+ if (next[targetField].length >= BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX) break;
+ const entry = {
+ name: label,
+ prompt: trimTo(variation?.prompt, BIBLE_LIMITS.PROMPT_MAX),
+ tags,
+ source: BIBLE_SOURCE.UNIVERSE_EXPAND,
+ };
+ if (variation?.locked === true) entry.locked = true;
+ // Setting sanitizer requires a name OR slugline; planting the label as
+ // both preserves the variation identity for scene-matchers.
+ if (kind === BIBLE_KIND.SETTING) entry.slugline = label;
+ next[targetField].push(entry);
+ nameSeen[targetField].add(nameKey);
+ }
+ }
+
+ return {
+ characters: sanitizeBibleList(next.characters, BIBLE_KIND.CHARACTER),
+ settings: sanitizeBibleList(next.settings, BIBLE_KIND.SETTING),
+ objects: sanitizeBibleList(next.objects, BIBLE_KIND.OBJECT),
+ schemaVersion: CURRENT_SCHEMA_VERSION,
+ };
+}
+
const sanitizeTemplate = (raw) => {
if (!raw || typeof raw !== 'object') return null;
if (!isStr(raw.id) || !raw.id) return null;
@@ -339,13 +420,15 @@ const sanitizeTemplate = (raw) => {
const compositeSheets = sanitizeCompositeSheets(raw.compositeSheets || []);
const influences = sanitizeInfluences(raw.influences);
const locked = sanitizeLocked(raw.locked);
- // Canon entity registries — structured records (vs categories[].variations[]
- // which is the freeform prompt-template library). A series's cast/places/
- // objects will eventually reference these by id (Phase B). Existing
- // universes load with empty arrays until extraction populates them.
- const characters = sanitizeBibleList(raw.characters, BIBLE_KIND.CHARACTER);
- const settings = sanitizeBibleList(raw.settings, BIBLE_KIND.SETTING);
- const objects = sanitizeBibleList(raw.objects, BIBLE_KIND.OBJECT);
+ // Canon registries. Backfill copies legacy `categories[].variations[]` into
+ // the matching kind on first read so series-side prompts can pull canon by
+ // entity name; categories stays alive until Phase 2 retires it.
+ const canonBackfill = backfillCanonFromCategories(raw, {
+ characters: raw.characters,
+ settings: raw.settings,
+ objects: raw.objects,
+ });
+ const { characters, settings, objects, schemaVersion } = canonBackfill;
const llm = raw.llm && typeof raw.llm === 'object'
? {
provider: trimTo(raw.llm.provider, 80) || null,
@@ -370,6 +453,7 @@ const sanitizeTemplate = (raw) => {
characters,
settings,
objects,
+ schemaVersion,
llm,
createdAt,
updatedAt,
@@ -393,8 +477,17 @@ const sanitizeRun = (raw) => {
async function readState() {
await ensureDir(PATHS.data);
const raw = await readJSONFile(STATE_PATH, DEFAULT_STATE, { logError: false });
+ const rawById = new Map(Array.isArray(raw.universes) ? raw.universes.filter((u) => u?.id).map((u) => [u.id, u]) : []);
const universes = Array.isArray(raw.universes) ? raw.universes.map(sanitizeTemplate).filter(Boolean) : [];
const runs = Array.isArray(raw.runs) ? raw.runs.map(sanitizeRun).filter(Boolean) : [];
+ // Persist on first backfill so subsequent reads skip the work and the user
+ // is free to rename or delete canon entries without the backfill re-adding
+ // them from their source variation.
+ const migrated = universes.filter((u) => (rawById.get(u.id)?.schemaVersion || 0) < CURRENT_SCHEMA_VERSION);
+ if (migrated.length > 0) {
+ console.log(`🌍 Universe Builder canon backfill — migrated ${migrated.length} universe(s) to schemaVersion=${CURRENT_SCHEMA_VERSION}`);
+ await writeState({ universes, runs });
+ }
return { universes, runs };
}
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index f7ed9139d7..53565f6577 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -577,6 +577,113 @@ describe("universeBuilder service", () => {
});
});
+ describe("categories→canon backfill", () => {
+ it("backfills canon arrays from categories on first read + stamps schemaVersion=2", async () => {
+ fileStore.set("/mock/data/universe-builder.json", {
+ universes: [
+ {
+ id: "w-v1", name: "Legacy",
+ starterPrompt: "old", stylePrompt: "", negativePrompt: "",
+ categories: {
+ characters: { variations: [{ label: "Alex", prompt: "field lead detective" }] },
+ landscapes: { variations: [{ label: "Crystal Canyon", prompt: "canyon, alien sun", locked: true }] },
+ environments: { variations: [{ label: "Bubble Room", prompt: "pastel lab" }] },
+ vehicles: { variations: [{ label: "Rover", prompt: "dust-streaked rover" }] },
+ structures: { variations: [{ label: "Monolith", prompt: "black monolith" }] },
+ factions: { variations: [{ label: "Rebels", prompt: "scarred faction icon" }] }, // custom key → object tagged 'factions'
+ },
+ createdAt: "2024-01-01T00:00:00Z",
+ },
+ ],
+ runs: [],
+ });
+ const list = await svc.listUniverses();
+ const w = list[0];
+ expect(w.schemaVersion).toBe(2);
+ // Characters
+ const alex = w.characters.find((c) => c.name === "Alex");
+ expect(alex).toBeTruthy();
+ expect(alex.prompt).toBe("field lead detective");
+ expect(alex.tags).toEqual([]);
+ expect(alex.source).toBe("universe-expand");
+ // Settings — landscape + environment
+ const canyon = w.settings.find((s) => s.name === "Crystal Canyon");
+ expect(canyon.tags).toEqual(["landscape"]);
+ expect(canyon.locked).toBe(true); // variation lock carries through
+ expect(canyon.slugline).toBe("Crystal Canyon"); // settings need slugline
+ const bubble = w.settings.find((s) => s.name === "Bubble Room");
+ expect(bubble.tags).toEqual(["environment"]);
+ // Objects — vehicle + structure + custom 'factions'
+ const rover = w.objects.find((o) => o.name === "Rover");
+ expect(rover.tags).toEqual(["vehicle"]);
+ const monolith = w.objects.find((o) => o.name === "Monolith");
+ expect(monolith.tags).toEqual(["structure"]);
+ const rebels = w.objects.find((o) => o.name === "Rebels");
+ expect(rebels.tags).toEqual(["factions"]); // unknown category key → object catch-all
+ });
+
+ it("backfill is idempotent — re-reading a v2 universe does not duplicate canon", async () => {
+ fileStore.set("/mock/data/universe-builder.json", {
+ universes: [
+ {
+ id: "w-v1", name: "Legacy",
+ starterPrompt: "old", stylePrompt: "", negativePrompt: "",
+ categories: {
+ characters: { variations: [{ label: "Alex", prompt: "detective" }] },
+ },
+ createdAt: "2024-01-01T00:00:00Z",
+ },
+ ],
+ runs: [],
+ });
+ // First read triggers backfill + persist.
+ const first = (await svc.listUniverses())[0];
+ expect(first.characters.length).toBe(1);
+ // Second read — schemaVersion=2 already on disk, backfill skipped.
+ const second = (await svc.listUniverses())[0];
+ expect(second.characters.length).toBe(1);
+ // Third read post-rename: a user-renamed entry must not be clobbered by
+ // re-running backfill (the schemaVersion guard prevents the re-insert).
+ const renamed = { ...second, characters: second.characters.map((c) => ({ ...c, name: "Alex Smith" })) };
+ fileStore.set("/mock/data/universe-builder.json", { universes: [renamed], runs: [] });
+ const third = (await svc.listUniverses())[0];
+ expect(third.characters.length).toBe(1);
+ expect(third.characters[0].name).toBe("Alex Smith");
+ });
+
+ it("backfill does not overwrite a pre-existing canon entry sharing a variation label", async () => {
+ fileStore.set("/mock/data/universe-builder.json", {
+ universes: [
+ {
+ id: "w-mixed", name: "Mixed",
+ starterPrompt: "", stylePrompt: "", negativePrompt: "",
+ categories: {
+ characters: { variations: [{ label: "Alex", prompt: "from variation" }] },
+ },
+ // Hand-authored canon entry whose name collides with the variation
+ // label. Backfill must NOT overwrite — the canon entry's richer
+ // metadata wins.
+ characters: [{
+ id: "chr-existing", name: "Alex",
+ role: "Hand-authored role",
+ physicalDescription: "hand-authored description",
+ source: "manual",
+ }],
+ createdAt: "2024-01-01T00:00:00Z",
+ },
+ ],
+ runs: [],
+ });
+ const w = (await svc.listUniverses())[0];
+ // Still exactly one Alex (no duplicate).
+ const alexes = w.characters.filter((c) => c.name === "Alex");
+ expect(alexes.length).toBe(1);
+ // Hand-authored fields preserved; the variation's prompt didn't bleed in.
+ expect(alexes[0].role).toBe("Hand-authored role");
+ expect(alexes[0].source).toBe("manual");
+ });
+ });
+
describe("sanitizers", () => {
it("drops malformed variations on read", async () => {
// Manually plant invalid state — sanitizeTemplate strips it on read.
diff --git a/server/services/universeCanon.js b/server/services/universeCanon.js
index 8779def6b0..28aa811641 100644
--- a/server/services/universeCanon.js
+++ b/server/services/universeCanon.js
@@ -7,7 +7,7 @@
import { getUniverse, updateUniverse, listUniverses } from './universeBuilder.js';
import { extractBible } from '../lib/bibleExtractor.js';
import {
- BIBLE_KIND, BIBLE_FIELD, BIBLE_KEYS, mergeExtractedBible,
+ BIBLE_KIND, BIBLE_KINDS, BIBLE_FIELD, BIBLE_KEYS, BIBLE_SOURCE, mergeExtractedBible,
} from '../lib/storyBible.js';
import { runStagedLLM } from '../lib/stageRunner.js';
import { runPromptRefine } from './pipeline/refineHelpers.js';
@@ -39,6 +39,10 @@ const buildStyleClause = (universe) => {
* Extract characters/places/objects from a prose corpus and merge into the
* universe's canon arrays. Mirrors `extractAndMergeIntoSeries` so callers
* can swap targets without changing prompt shapes.
+ *
+ * `opts.source` / `opts.autoLock` / `opts.sourceSeriesId` stamp NEW inserts
+ * only — existing entries are not touched by these options (locked existing
+ * entries are protected by mergeExtractedBible itself).
*/
export async function extractCanonFromProse(universeId, opts = {}) {
const universe = await getUniverse(universeId);
@@ -65,11 +69,16 @@ export async function extractCanonFromProse(universeId, opts = {}) {
? await Promise.all(kinds.map(runOne))
: await kinds.reduce(async (acc, kind) => [...(await acc), await runOne(kind)], Promise.resolve([]));
+ const mergeOpts = {
+ source: opts.source || BIBLE_SOURCE.SERIES_EXTRACT,
+ autoLock: opts.autoLock === true,
+ sourceSeriesId: opts.sourceSeriesId || null,
+ };
const results = {};
const patch = {};
for (const { kind, result } of completed) {
const field = BIBLE_FIELD[kind];
- patch[field] = mergeExtractedBible(universe[field] || [], result.extracted, kind);
+ patch[field] = mergeExtractedBible(universe[field] || [], result.extracted, kind, mergeOpts);
results[field] = {
extracted: result.extracted, runId: result.runId,
providerId: result.providerId, model: result.model,
@@ -94,6 +103,14 @@ export async function refineUniverseCharacter(universeId, entryId, options = {})
});
}
const target = list[idx];
+ // 409 (vs. silent overwrite) so the UI can render a clear "Unlock to edit"
+ // affordance for entries an active series depends on.
+ if (target.locked === true) {
+ throw new ServerError(
+ `Character "${target.name}" is locked — unlock it before refining`,
+ { status: 409, code: 'UNIVERSE_CANON_LOCKED' },
+ );
+ }
const peers = list.filter((_, i) => i !== idx);
const { refined, changes, rationale, runId, providerId, model } = await runPromptRefine({
@@ -132,6 +149,14 @@ export async function differentiateUniverseCast(universeId, options = {}) {
});
}
+ // The LLM sees the FULL cast so unlocked rewrites are differentiated from
+ // locked descriptions too. Lock enforcement happens at apply time.
+ if (list.every((c) => c.locked === true)) {
+ throw new ServerError(
+ 'All characters are locked — unlock at least one before differentiating the cast',
+ { status: 400, code: 'UNIVERSE_CANON_ALL_LOCKED' },
+ );
+ }
const castForPrompt = list.map(targetForPrompt);
const result = await runStagedLLM('pipeline-character-differentiate-cast', {
castJson: JSON.stringify(castForPrompt, null, 2),
@@ -164,9 +189,14 @@ export async function differentiateUniverseCast(universeId, options = {}) {
}
let touched = 0;
+ let skippedLocked = 0;
const nextList = list.map((entry) => {
const rewrite = byId.get(entry.id);
if (!rewrite) return entry;
+ if (entry.locked === true) {
+ skippedLocked += 1;
+ return entry;
+ }
touched += 1;
return { ...entry, physicalDescription: rewrite.physicalDescription };
});
@@ -178,11 +208,12 @@ export async function differentiateUniverseCast(universeId, options = {}) {
const updated = await updateUniverse(universeId, { characters: nextList });
const rationale = typeof result.content?.rationale === 'string' ? result.content.rationale.trim() : '';
- console.log(`✨ Universe cast differentiate — universe=${universeId.slice(0, 8)} touched=${touched}/${list.length} runId=${(result.runId || '').slice(0, 8)}`);
+ console.log(`✨ Universe cast differentiate — universe=${universeId.slice(0, 8)} touched=${touched}/${list.length} skippedLocked=${skippedLocked} runId=${(result.runId || '').slice(0, 8)}`);
return {
universe: updated,
touched,
skipped: list.length - touched,
+ skippedLocked,
rationale,
runId: result.runId,
providerId: result.providerId,
@@ -190,6 +221,39 @@ export async function differentiateUniverseCast(universeId, options = {}) {
};
}
+// Toggle the `locked` flag on a single canon entry. Locked entries are
+// protected from AI rewrite paths — see `mergeExtractedBible` (evidence-only
+// append) and the refine/differentiate runtime guards.
+export async function setCanonEntryLock(universeId, kind, entryId, locked) {
+ if (!BIBLE_KINDS.includes(kind)) {
+ throw new ServerError(
+ `Invalid canon kind "${kind}" — expected one of: ${BIBLE_KINDS.join(', ')}`,
+ { status: 400, code: 'UNIVERSE_CANON_INVALID_KIND' },
+ );
+ }
+ const universe = await getUniverse(universeId);
+ const field = BIBLE_FIELD[kind];
+ const list = Array.isArray(universe[field]) ? universe[field] : [];
+ const idx = list.findIndex((e) => e.id === entryId);
+ if (idx < 0) {
+ throw new ServerError(
+ `Canon ${kind} ${entryId} not found in universe`,
+ { status: 404, code: 'UNIVERSE_CANON_NOT_FOUND' },
+ );
+ }
+ const target = list[idx];
+ // No-op short-circuit avoids a write + updatedAt churn on redundant toggles.
+ if ((target.locked === true) === (locked === true)) {
+ return { universe, entry: target };
+ }
+ // applyCanonExtras strips locked: false on save, so we can pass it through
+ // directly instead of destructure-stripping here.
+ const nextList = list.map((e, i) => (i === idx ? { ...e, locked } : e));
+ const updated = await updateUniverse(universeId, { [field]: nextList });
+ const entry = (updated[field] || []).find((e) => e.id === entryId) || null;
+ return { universe: updated, entry };
+}
+
/**
* Strip a filename from every `imageRefs[]` across every universe's
* characters/settings/objects. Mirror of the series-side purge so the image-
diff --git a/server/services/universeCanon.test.js b/server/services/universeCanon.test.js
new file mode 100644
index 0000000000..f35d509486
--- /dev/null
+++ b/server/services/universeCanon.test.js
@@ -0,0 +1,198 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// In-memory file store mirroring universeBuilder.test.js so canon mutations
+// roundtrip through the same readState/writeState path the real service uses.
+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}` };
+});
+
+// The bible extractor + staged-LLM runner + prompt-refine helpers all reach
+// out to live AI providers. Stub them to return deterministic shapes so we
+// can test lock semantics without spinning up a model.
+const extractBibleMock = vi.fn();
+vi.mock('../lib/bibleExtractor.js', () => ({
+ extractBible: (...args) => extractBibleMock(...args),
+}));
+
+const runStagedLLMMock = vi.fn();
+vi.mock('../lib/stageRunner.js', () => ({
+ runStagedLLM: (...args) => runStagedLLMMock(...args),
+}));
+
+const runPromptRefineMock = vi.fn();
+vi.mock('./pipeline/refineHelpers.js', () => ({
+ runPromptRefine: (...args) => runPromptRefineMock(...args),
+}));
+
+const svc = await import('./universeBuilder.js');
+const canonSvc = await import('./universeCanon.js');
+
+const seedUniverseWithCharacters = async (characters) => {
+ const w = await svc.createUniverse({
+ name: 'Test Universe',
+ starterPrompt: 'test seed',
+ stylePrompt: 'test style',
+ });
+ // Bypass the route schema to plant canon entries directly via updateUniverse.
+ return svc.updateUniverse(w.id, { characters });
+};
+
+beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ extractBibleMock.mockReset();
+ runStagedLLMMock.mockReset();
+ runPromptRefineMock.mockReset();
+});
+
+describe('universeCanon — setCanonEntryLock', () => {
+ it('toggles locked: true on the target entry and persists', async () => {
+ const w = await seedUniverseWithCharacters([
+ { name: 'Alex', physicalDescription: 'jacket' },
+ ]);
+ const entryId = w.characters[0].id;
+ const { entry } = await canonSvc.setCanonEntryLock(w.id, 'character', entryId, true);
+ expect(entry.locked).toBe(true);
+ // Persisted: a fresh read finds it locked.
+ const reread = (await svc.listUniverses())[0];
+ expect(reread.characters.find((c) => c.id === entryId).locked).toBe(true);
+ });
+
+ it('removes the locked field entirely on unlock (minimal on-disk shape)', async () => {
+ const w = await seedUniverseWithCharacters([
+ { name: 'Alex', physicalDescription: 'jacket', locked: true },
+ ]);
+ const entryId = w.characters[0].id;
+ const { entry } = await canonSvc.setCanonEntryLock(w.id, 'character', entryId, false);
+ expect(entry.locked).toBeUndefined();
+ });
+
+ it('rejects unknown kind with a 400-coded ServerError', async () => {
+ const w = await seedUniverseWithCharacters([
+ { name: 'Alex', physicalDescription: 'jacket' },
+ ]);
+ await expect(
+ canonSvc.setCanonEntryLock(w.id, 'monster', w.characters[0].id, true),
+ ).rejects.toMatchObject({ status: 400, code: 'UNIVERSE_CANON_INVALID_KIND' });
+ });
+
+ it('rejects unknown entry with a 404-coded ServerError', async () => {
+ const w = await seedUniverseWithCharacters([
+ { name: 'Alex', physicalDescription: 'jacket' },
+ ]);
+ await expect(
+ canonSvc.setCanonEntryLock(w.id, 'character', 'chr-not-real', true),
+ ).rejects.toMatchObject({ status: 404, code: 'UNIVERSE_CANON_NOT_FOUND' });
+ });
+});
+
+describe('universeCanon — refineUniverseCharacter respects locks', () => {
+ it('refuses with 409 when the target character is locked', async () => {
+ const w = await seedUniverseWithCharacters([
+ { name: 'Alex', physicalDescription: 'jacket', locked: true },
+ ]);
+ await expect(
+ canonSvc.refineUniverseCharacter(w.id, w.characters[0].id),
+ ).rejects.toMatchObject({ status: 409, code: 'UNIVERSE_CANON_LOCKED' });
+ // No LLM call was made — the guard fires before runPromptRefine.
+ expect(runPromptRefineMock).not.toHaveBeenCalled();
+ });
+
+ it('proceeds when the character is unlocked', async () => {
+ const w = await seedUniverseWithCharacters([
+ { name: 'Alex', physicalDescription: 'jacket' },
+ { name: 'Beth', physicalDescription: 'coat' },
+ ]);
+ runPromptRefineMock.mockResolvedValue({
+ refined: 'fresh description', changes: [], rationale: 'distinct from Beth',
+ runId: 'run-1', providerId: 'test', model: 'test',
+ });
+ const result = await canonSvc.refineUniverseCharacter(w.id, w.characters[0].id);
+ expect(runPromptRefineMock).toHaveBeenCalledTimes(1);
+ expect(result.entry.physicalDescription).toBe('fresh description');
+ });
+});
+
+describe('universeCanon — differentiateUniverseCast respects locks', () => {
+ it('skips locked entries at apply time even though the LLM saw them', async () => {
+ const w = await seedUniverseWithCharacters([
+ { name: 'Alex', physicalDescription: 'jacket', locked: true },
+ { name: 'Beth', physicalDescription: 'coat' },
+ ]);
+ const [alex, beth] = w.characters;
+ runStagedLLMMock.mockResolvedValue({
+ content: {
+ characters: [
+ { id: alex.id, physicalDescription: 'rewritten alex (should be ignored)' },
+ { id: beth.id, physicalDescription: 'rewritten beth' },
+ ],
+ rationale: 'differentiated',
+ },
+ runId: 'run-2', providerId: 'test', model: 'test',
+ });
+ const result = await canonSvc.differentiateUniverseCast(w.id);
+ expect(result.touched).toBe(1);
+ expect(result.skippedLocked).toBe(1);
+ const refreshed = (await svc.listUniverses())[0];
+ expect(refreshed.characters.find((c) => c.id === alex.id).physicalDescription).toBe('jacket');
+ expect(refreshed.characters.find((c) => c.id === beth.id).physicalDescription).toBe('rewritten beth');
+ });
+
+ it('rejects when every character is locked', async () => {
+ const w = await seedUniverseWithCharacters([
+ { name: 'Alex', physicalDescription: 'a', locked: true },
+ { name: 'Beth', physicalDescription: 'b', locked: true },
+ ]);
+ await expect(
+ canonSvc.differentiateUniverseCast(w.id),
+ ).rejects.toMatchObject({ status: 400, code: 'UNIVERSE_CANON_ALL_LOCKED' });
+ expect(runStagedLLMMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('universeCanon — extractCanonFromProse passes autoLock + sourceSeriesId through', () => {
+ it('autoLock=true makes newly-inserted entries locked + stamps sourceSeriesId', async () => {
+ const w = await seedUniverseWithCharacters([]);
+ extractBibleMock.mockImplementation(async ({ kind }) => ({
+ extracted: kind === 'character' ? [{ name: 'NewbyChar' }] : [],
+ runId: 'r', providerId: 'p', model: 'm',
+ }));
+ const result = await canonSvc.extractCanonFromProse(w.id, {
+ corpus: 'some prose',
+ kinds: ['character'],
+ source: 'series-extract',
+ autoLock: true,
+ sourceSeriesId: 'ser-active',
+ });
+ const inserted = result.universe.characters.find((c) => c.name === 'NewbyChar');
+ expect(inserted.locked).toBe(true);
+ expect(inserted.source).toBe('series-extract');
+ expect(inserted.sourceSeriesId).toBe('ser-active');
+ });
+
+ it('without autoLock, new entries are unlocked (universe-side direct extraction)', async () => {
+ const w = await seedUniverseWithCharacters([]);
+ extractBibleMock.mockImplementation(async ({ kind }) => ({
+ extracted: kind === 'character' ? [{ name: 'Newby' }] : [],
+ runId: 'r', providerId: 'p', model: 'm',
+ }));
+ const result = await canonSvc.extractCanonFromProse(w.id, {
+ corpus: 'some prose',
+ kinds: ['character'],
+ });
+ const inserted = result.universe.characters.find((c) => c.name === 'Newby');
+ expect(inserted.locked).toBeUndefined();
+ expect(inserted.source).toBe('series-extract'); // default new vocab
+ });
+});