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

refactor([extract-descriptorforcanonentry-kind-entry-into]): canonPrompt helper — single source of truth for per-kind descriptor fields

[._.]/ Adam Eivye0cb4bf9a00b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3f83f29ef8..238a2fba91 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -26,6 +26,7 @@
## Refactors
+- **`canonPrompt` shared helper (`server/lib/canonPrompt.js` + `client/src/lib/canonPrompt.js` mirror).** Single source of truth for per-kind canon descriptor field precedence. Exports `shortCanonDescriptorFragments` (UI-summary scope), `richCanonDescriptorFragments` (render-prompt scope), `descriptorForCanonEntry` (flattened short string), and `hasCanonDescriptorContent` (rich-field union for "has anything to render?" gates). Migrated four call sites: `synthesizeCanonPrompt` in `server/services/universeBuilder.js`, `KINDS[].descFor` in `client/src/components/universe/UniverseCanonSection.jsx`, `canonEntryHasContent` in `client/src/pages/UniverseBuilder.jsx`, and `settingFrags` in `server/lib/scenePrompt.js` + client mirror. Minor cosmetic uniformity: lowercase `palette:`/`era:`/`weather:`/`significance:` prefixes in canon render prompts are now capitalized to match the UI descriptor format — case-only change, no functional impact on diffusion models. 29 new tests in `server/lib/canonPrompt.test.js`.
- **`TabPills` UI primitive (`client/src/components/ui/TabPills.jsx`).** Consolidates ten duplicated tab-nav patterns — two local `TabNav` components (UniverseBuilder, StoryboardPanel) plus eight inline tab-button blocks (Brain, Calendar, ChiefOfStaff, DigitalTwin, MediaGen, Messages, Settings, Wiki). Two variants (`underline` default, `pills`) with knobs for the call-site quirks (`runningKind` per-tab spinner, `stretch` flex-1 equal-width, `mobileDropdown` `<select>` fallback, `hideLabelOnMobile` icon-only at < sm, `controlsIdPrefix` for `aria-controls` wiring, `listRef`+`onScroll` for ChiefOfStaff's scroll-arrow overlay). Covered by 7 vitest cases. Minor intentional visual unification across the surface area: StoryboardPanel active tab text-port-accent (was text-white), ChiefOfStaff and Settings gained the standard `bg-port-accent/5` active wash + `hover:bg-port-card` inactive.
- **CoS — explicit `init()` instead of module-level auto-init.** `server/services/cos.js` previously called `init()` at the bottom of the module, gated by `NODE_ENV !== 'test' && VITEST !== 'true'` so unit tests didn't spin up listeners/timers. The guard was a "test hack in the prod boot path" — `init` is now exported and called explicitly from `server/index.js` alongside `automationScheduler.init()` / `agentActionExecutor.init()` / etc. Test imports of `cos.js` no longer have side effects, and the prod boot path no longer branches on test-env vars.
- **`LoraPicker` extracted** (`client/src/components/imageGen/LoraPicker.jsx`). The LoRA multi-select previously inlined in `ImageGen.jsx` is now a shared component used by both the standalone Image Gen page and the Universe Builder batch-render form.
diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsx
index b5c66ad0bb..7cb11e8cd2 100644
--- a/client/src/components/universe/UniverseCanonSection.jsx
+++ b/client/src/components/universe/UniverseCanonSection.jsx
@@ -34,23 +34,20 @@ import CanonCard from '../pipeline/CanonCard';
import MediaPreview from '../media/MediaPreview';
import { pipelineImageCfgToRenderOpts } from '../../lib/pipelineImageDefaults';
import { universeStylePreset } from '../../lib/universeStylePreset';
+import { descriptorForCanonEntry } from '../../lib/canonPrompt';
const KINDS = [
{
key: 'characters', apiKind: 'character', label: 'Characters', singular: 'character', icon: Users,
- descFor: (c) => c.physicalDescription || c.description || '',
+ descFor: (c) => descriptorForCanonEntry('characters', c),
},
{
key: 'settings', apiKind: 'setting', label: 'Places', singular: 'place', icon: MapPin,
- descFor: (s) => [
- s.description,
- s.palette ? `Palette: ${s.palette}` : '',
- s.recurringDetails,
- ].filter(Boolean).join('. '),
+ descFor: (s) => descriptorForCanonEntry('settings', s),
},
{
key: 'objects', apiKind: 'object', label: 'Objects', singular: 'object', icon: Package,
- descFor: (o) => o.description || o.significance || '',
+ descFor: (o) => descriptorForCanonEntry('objects', o),
},
];
diff --git a/client/src/lib/canonPrompt.js b/client/src/lib/canonPrompt.js
new file mode 100644
index 0000000000..5a8b48378d
--- /dev/null
+++ b/client/src/lib/canonPrompt.js
@@ -0,0 +1,125 @@
+// Mirror of server/lib/canonPrompt.js — keep byte-for-byte in sync.
+// The server copy is authoritative; tests in server/lib/canonPrompt.test.js
+// are the contract.
+
+const trim = (s) => (typeof s === 'string' ? s.trim() : '');
+
+// SHORT spec: chars/objects use single-with-fallback; settings uses a
+// sequence so palette can carry its prefix.
+const SHORT_SPEC = Object.freeze({
+ characters: Object.freeze({ primary: 'physicalDescription', fallback: 'description' }),
+ settings: Object.freeze({
+ sequence: Object.freeze([
+ { field: 'description' },
+ { field: 'palette', prefix: 'Palette' },
+ { field: 'recurringDetails' },
+ ]),
+ }),
+ objects: Object.freeze({ primary: 'description', fallback: 'significance' }),
+});
+
+// RICH spec: ordered list of all descriptor fields. Prefixes capitalized
+// uniformly so flattened output reads as natural sentence fragments.
+const RICH_SPEC = Object.freeze({
+ characters: Object.freeze([
+ { field: 'physicalDescription' },
+ { field: 'role' },
+ ]),
+ settings: Object.freeze([
+ { field: 'description' },
+ { field: 'palette', prefix: 'Palette' },
+ { field: 'era', prefix: 'Era' },
+ { field: 'weather', prefix: 'Weather' },
+ { field: 'recurringDetails' },
+ ]),
+ objects: Object.freeze([
+ { field: 'description' },
+ { field: 'significance', prefix: 'Significance' },
+ ]),
+});
+
+function normalizeKind(kind) {
+ const k = String(kind || '').toLowerCase();
+ if (k === 'character' || k === 'characters') return 'characters';
+ if (k === 'setting' || k === 'settings') return 'settings';
+ if (k === 'object' || k === 'objects') return 'objects';
+ return null;
+}
+
+function fragmentsFromSequence(sequence, entry) {
+ const out = [];
+ for (const spec of sequence) {
+ const value = trim(entry[spec.field]);
+ if (!value) continue;
+ out.push(spec.prefix ? { field: spec.field, value, prefix: spec.prefix } : { field: spec.field, value });
+ }
+ return out;
+}
+
+// Short-circuit "any non-blank field in this sequence" — used by
+// `hasCanonDescriptorContent` so per-entry render-count filters don't
+// allocate a full fragments array just to read `.length > 0`.
+function sequenceHasAnyField(sequence, entry) {
+ for (const spec of sequence) {
+ if (trim(entry[spec.field])) return true;
+ }
+ return false;
+}
+
+/**
+ * SHORT descriptor fragments — the visual subset used in canon UI cards
+ * and the render-ref button-enable predicate.
+ *
+ * Returns `[{ field, value, prefix? }]` in display order. Empty/missing
+ * fields produce no fragment. For chars/objects this is at most a single
+ * fragment (primary with single-field fallback).
+ */
+export function shortCanonDescriptorFragments(kind, entry) {
+ if (!entry || typeof entry !== 'object') return [];
+ const spec = SHORT_SPEC[normalizeKind(kind)];
+ if (!spec) return [];
+ if (spec.sequence) return fragmentsFromSequence(spec.sequence, entry);
+ const primary = trim(entry[spec.primary]);
+ if (primary) return [{ field: spec.primary, value: primary }];
+ const fallback = trim(entry[spec.fallback]);
+ if (fallback) return [{ field: spec.fallback, value: fallback }];
+ return [];
+}
+
+/**
+ * RICH descriptor fragments — every descriptive field that contributes to
+ * a render prompt body. Used by render-synthesis and the
+ * "has any content?" gate.
+ */
+export function richCanonDescriptorFragments(kind, entry) {
+ if (!entry || typeof entry !== 'object') return [];
+ const sequence = RICH_SPEC[normalizeKind(kind)];
+ if (!sequence) return [];
+ return fragmentsFromSequence(sequence, entry);
+}
+
+/**
+ * Flatten SHORT fragments into a sentence-style descriptor string.
+ * Matches the legacy `KINDS[].descFor` output:
+ * characters: "physicalDescription" else "description"
+ * settings: "description. Palette: <palette>. recurringDetails"
+ * objects: "description" else "significance"
+ */
+export function descriptorForCanonEntry(kind, entry) {
+ return shortCanonDescriptorFragments(kind, entry)
+ .map((f) => (f.prefix ? `${f.prefix}: ${f.value}` : f.value))
+ .join('. ');
+}
+
+/**
+ * True when the entry has any non-blank value across the RICH field set.
+ * Mirrors `canonEntryHasContent`'s per-kind union check (UniverseBuilder.jsx)
+ * and is the read-side mirror of `synthesizeCanonPrompt`'s skip-empty-seed
+ * rule.
+ */
+export function hasCanonDescriptorContent(kind, entry) {
+ if (!entry || typeof entry !== 'object') return false;
+ const sequence = RICH_SPEC[normalizeKind(kind)];
+ if (!sequence) return false;
+ return sequenceHasAnyField(sequence, entry);
+}
diff --git a/client/src/lib/scenePrompt.js b/client/src/lib/scenePrompt.js
index 6c294df4ad..bc7802ce8f 100644
--- a/client/src/lib/scenePrompt.js
+++ b/client/src/lib/scenePrompt.js
@@ -1,6 +1,8 @@
// Mirror of server/lib/scenePrompt.js — keep byte-for-byte in sync.
// The shape-invariant tests in server/lib/scenePrompt.test.js are the contract.
+import { shortCanonDescriptorFragments } from './canonPrompt.js';
+
const PROMPT_MAX = 1900;
export const normalizeSlugline = (s) => String(s || '')
@@ -98,11 +100,13 @@ export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyle
? matchedSetting.timeOfDay
: '';
const settingMetaFrag = [intExtPart, todPart].filter(Boolean).join(', ');
+ const baselineFrags = matchedSetting
+ ? shortCanonDescriptorFragments('setting', matchedSetting)
+ .map((f) => (f.prefix ? `${f.prefix}: ${f.value}.` : f.value))
+ : [];
const settingFrags = matchedSetting ? [
settingMetaFrag ? `${settingMetaFrag}.` : '',
- matchedSetting.description?.trim() || '',
- matchedSetting.palette ? `Palette: ${matchedSetting.palette.trim()}.` : '',
- matchedSetting.recurringDetails?.trim() || '',
+ ...baselineFrags,
].filter(Boolean) : [];
// Accept either `physicalDescription` (writers-room shape) or
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index 4eec35d0da..5ece1d5810 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -38,6 +38,7 @@ import TabPills from '../components/ui/TabPills';
import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends';
import { PIPELINE_IMAGE_DEFAULTS, readPipelineImageSettings } from '../lib/pipelineImageDefaults';
import { normalizeSlugline } from '../lib/scenePrompt';
+import { hasCanonDescriptorContent } from '../lib/canonPrompt';
const CATEGORY_LABELS = {
landscapes: 'Landscapes',
@@ -1881,19 +1882,11 @@ function totalVariationCount(world) {
return getCategoryKeys(world.categories).reduce((n, c) => n + (world.categories?.[c]?.variations?.length || 0), 0);
}
-// Match server-side `synthesizeCanonPrompt` (server/services/universeBuilder.js)
-// per-kind: entries with no identity-anchor (name / slugline / hand-authored
-// prompt) AND no descriptive content for that kind compile to an empty seed and
-// get skipped. Mirror the predicate here so the "Render N images" button count
-// doesn't overshoot what the server will actually enqueue.
-//
-// IMPORTANT: keep the per-kind field lists in sync with server's
-// `synthesizeCanonPrompt`. Drift between client/server here makes scoped render
-// counts and disabled states lie about what will actually be enqueued.
-// Server's `synthesizeCanonPrompt` trims each string field before pushing into
-// `parts` and then filters out empty results via `String(p).trim().filter(Boolean)`.
-// A whitespace-only field doesn't anchor renderability there — mirror that here
-// so client-side counts/disable states agree under optimistic edits.
+// Mirror the server's synthesizeCanonPrompt skip rule: entries with no
+// identity-anchor (name / slugline / prompt) AND no descriptive content for
+// the kind compile to an empty seed and get skipped at render time. The
+// "Render N images" button count must not overshoot what the server will
+// actually enqueue.
const hasNonBlankString = (v) => typeof v === 'string' && v.trim().length > 0;
const canonEntryHasContent = (e, kind) => {
@@ -1904,38 +1897,21 @@ const canonEntryHasContent = (e, kind) => {
// synthesizeCanonPrompt's identifier-seed rule.
if (hasNonBlankString(e.name)) return true;
if (kind === 'settings' && hasNonBlankString(e.slugline)) return true;
- if (kind === 'characters') {
- return hasNonBlankString(e.physicalDescription) || hasNonBlankString(e.role);
- }
- if (kind === 'settings') {
- return hasNonBlankString(e.description) || hasNonBlankString(e.palette)
- || hasNonBlankString(e.era) || hasNonBlankString(e.weather)
- || hasNonBlankString(e.recurringDetails);
- }
- if (kind === 'objects') {
- return hasNonBlankString(e.description) || hasNonBlankString(e.significance);
- }
- // Unknown kind — fall back to the inclusive union so an unrecognized trunk
- // doesn't silently collapse to 0.
- return hasNonBlankString(e.physicalDescription) || hasNonBlankString(e.description)
- || hasNonBlankString(e.palette) || hasNonBlankString(e.era) || hasNonBlankString(e.weather)
- || hasNonBlankString(e.recurringDetails) || hasNonBlankString(e.role)
- || hasNonBlankString(e.significance);
+ return hasCanonDescriptorContent(kind, e);
};
const countCanonWithContent = (world, kind) =>
(Array.isArray(world?.[kind]) ? world[kind] : []).filter((e) => canonEntryHasContent(e, kind)).length;
function renderPromptCount(world, promptMode = 'variations') {
- const variations = totalVariationCount(world);
+ if (promptMode === 'variations') return totalVariationCount(world);
const sheets = world.compositeSheets?.length || 0;
+ if (promptMode === 'sheets') return sheets;
const canon = countCanonWithContent(world, 'characters')
+ countCanonWithContent(world, 'settings')
+ countCanonWithContent(world, 'objects');
- if (promptMode === 'sheets') return sheets;
if (promptMode === 'canon') return canon;
- if (promptMode === 'all') return variations + sheets + canon;
- return variations;
+ return totalVariationCount(world) + sheets + canon;
}
// Mirrors the server's compilePrompts for selection/sheetSelection/canonSelection
diff --git a/server/lib/canonPrompt.js b/server/lib/canonPrompt.js
new file mode 100644
index 0000000000..8d2ec3feac
--- /dev/null
+++ b/server/lib/canonPrompt.js
@@ -0,0 +1,147 @@
+/**
+ * Shared per-kind field-precedence rules for canon entries. Pure ESM, no
+ * Node-only deps — mirrored to `client/src/lib/canonPrompt.js` for the
+ * client bundle.
+ *
+ * Source of truth for "which fields describe a canon entry of this kind,
+ * in what order". Consumers:
+ * - `synthesizeCanonPrompt` (server/services/universeBuilder.js) →
+ * render-prompt body (RICH fields)
+ * - `canonEntryHasContent` (client/src/pages/UniverseBuilder.jsx) →
+ * "is there any descriptive content?" gate (RICH fields)
+ * - `KINDS[].descFor` (client/src/components/universe/UniverseCanonSection.jsx) →
+ * UI summary + handleRenderRef button-enable predicate (SHORT fields)
+ * - `settingFrags` (server/lib/scenePrompt.js) → scene-prompt framing
+ * for settings (SHORT fields)
+ *
+ * SHORT vs RICH:
+ * - SHORT = the visual descriptor subset shown in UI cards. For
+ * chars/objects: single primary field with a single fallback (mirrors
+ * the legacy `descFor` `||` chain). For settings: description +
+ * palette + recurringDetails (the "setting baseline" from scenePrompt).
+ * - RICH = every descriptive field that contributes to a render prompt.
+ * Adds `role` (chars), `era`+`weather` (settings), additive
+ * `significance` (objects).
+ */
+
+const trim = (s) => (typeof s === 'string' ? s.trim() : '');
+
+// SHORT spec: chars/objects use single-with-fallback; settings uses a
+// sequence so palette can carry its prefix.
+const SHORT_SPEC = Object.freeze({
+ characters: Object.freeze({ primary: 'physicalDescription', fallback: 'description' }),
+ settings: Object.freeze({
+ sequence: Object.freeze([
+ { field: 'description' },
+ { field: 'palette', prefix: 'Palette' },
+ { field: 'recurringDetails' },
+ ]),
+ }),
+ objects: Object.freeze({ primary: 'description', fallback: 'significance' }),
+});
+
+// RICH spec: ordered list of all descriptor fields. Prefixes capitalized
+// uniformly so flattened output reads as natural sentence fragments.
+const RICH_SPEC = Object.freeze({
+ characters: Object.freeze([
+ { field: 'physicalDescription' },
+ { field: 'role' },
+ ]),
+ settings: Object.freeze([
+ { field: 'description' },
+ { field: 'palette', prefix: 'Palette' },
+ { field: 'era', prefix: 'Era' },
+ { field: 'weather', prefix: 'Weather' },
+ { field: 'recurringDetails' },
+ ]),
+ objects: Object.freeze([
+ { field: 'description' },
+ { field: 'significance', prefix: 'Significance' },
+ ]),
+});
+
+function normalizeKind(kind) {
+ const k = String(kind || '').toLowerCase();
+ if (k === 'character' || k === 'characters') return 'characters';
+ if (k === 'setting' || k === 'settings') return 'settings';
+ if (k === 'object' || k === 'objects') return 'objects';
+ return null;
+}
+
+function fragmentsFromSequence(sequence, entry) {
+ const out = [];
+ for (const spec of sequence) {
+ const value = trim(entry[spec.field]);
+ if (!value) continue;
+ out.push(spec.prefix ? { field: spec.field, value, prefix: spec.prefix } : { field: spec.field, value });
+ }
+ return out;
+}
+
+// Short-circuit "any non-blank field in this sequence" — used by
+// `hasCanonDescriptorContent` so per-entry render-count filters don't
+// allocate a full fragments array just to read `.length > 0`.
+function sequenceHasAnyField(sequence, entry) {
+ for (const spec of sequence) {
+ if (trim(entry[spec.field])) return true;
+ }
+ return false;
+}
+
+/**
+ * SHORT descriptor fragments — the visual subset used in canon UI cards
+ * and the render-ref button-enable predicate.
+ *
+ * Returns `[{ field, value, prefix? }]` in display order. Empty/missing
+ * fields produce no fragment. For chars/objects this is at most a single
+ * fragment (primary with single-field fallback).
+ */
+export function shortCanonDescriptorFragments(kind, entry) {
+ if (!entry || typeof entry !== 'object') return [];
+ const spec = SHORT_SPEC[normalizeKind(kind)];
+ if (!spec) return [];
+ if (spec.sequence) return fragmentsFromSequence(spec.sequence, entry);
+ const primary = trim(entry[spec.primary]);
+ if (primary) return [{ field: spec.primary, value: primary }];
+ const fallback = trim(entry[spec.fallback]);
+ if (fallback) return [{ field: spec.fallback, value: fallback }];
+ return [];
+}
+
+/**
+ * RICH descriptor fragments — every descriptive field that contributes to
+ * a render prompt body. Used by render-synthesis and the
+ * "has any content?" gate.
+ */
+export function richCanonDescriptorFragments(kind, entry) {
+ if (!entry || typeof entry !== 'object') return [];
+ const sequence = RICH_SPEC[normalizeKind(kind)];
+ if (!sequence) return [];
+ return fragmentsFromSequence(sequence, entry);
+}
+
+/**
+ * Flatten SHORT fragments into a sentence-style descriptor string.
+ * Matches the legacy `KINDS[].descFor` output:
+ * characters: "physicalDescription" else "description"
+ * settings: "description. Palette: <palette>. recurringDetails"
+ * objects: "description" else "significance"
+ */
+export function descriptorForCanonEntry(kind, entry) {
+ return shortCanonDescriptorFragments(kind, entry)
+ .map((f) => (f.prefix ? `${f.prefix}: ${f.value}` : f.value))
+ .join('. ');
+}
+
+/**
+ * True when the entry has any non-blank value across the RICH field set.
+ * Mirrors `canonEntryHasContent`'s per-kind union check (UniverseBuilder.jsx)
+ * and is the read-side mirror of `synthesizeCanonPrompt`'s skip-empty-seed
+ * rule.
+ */
+export function hasCanonDescriptorContent(kind, entry) {
+ if (!entry || typeof entry !== 'object') return false;
+ const sequence = RICH_SPEC[normalizeKind(kind)];
+ if (!sequence) return false;
+ return sequenceHasAnyField(sequence, entry);
+}
diff --git a/server/lib/canonPrompt.test.js b/server/lib/canonPrompt.test.js
new file mode 100644
index 0000000000..fbaedce9bb
--- /dev/null
+++ b/server/lib/canonPrompt.test.js
@@ -0,0 +1,242 @@
+import { describe, it, expect } from 'vitest';
+import {
+ shortCanonDescriptorFragments,
+ richCanonDescriptorFragments,
+ descriptorForCanonEntry,
+ hasCanonDescriptorContent,
+} from './canonPrompt.js';
+
+describe('canonPrompt.js', () => {
+ describe('descriptorForCanonEntry', () => {
+ it('returns empty string for null/non-object entry', () => {
+ expect(descriptorForCanonEntry('characters', null)).toBe('');
+ expect(descriptorForCanonEntry('characters', undefined)).toBe('');
+ expect(descriptorForCanonEntry('characters', 'not an object')).toBe('');
+ });
+
+ it('returns empty string for unknown kind', () => {
+ expect(descriptorForCanonEntry('unknown', { physicalDescription: 'tall' })).toBe('');
+ });
+
+ it('accepts singular and plural kinds', () => {
+ const entry = { physicalDescription: 'tall' };
+ expect(descriptorForCanonEntry('characters', entry)).toBe('tall');
+ expect(descriptorForCanonEntry('character', entry)).toBe('tall');
+ expect(descriptorForCanonEntry('CHARACTERS', entry)).toBe('tall');
+ });
+
+ describe('characters', () => {
+ it('uses physicalDescription as primary', () => {
+ expect(descriptorForCanonEntry('characters', {
+ physicalDescription: 'tall, dark hair',
+ description: 'old desc',
+ })).toBe('tall, dark hair');
+ });
+
+ it('falls back to description when physicalDescription is missing', () => {
+ expect(descriptorForCanonEntry('characters', { description: 'old desc' })).toBe('old desc');
+ });
+
+ it('falls back to description when physicalDescription is whitespace-only', () => {
+ expect(descriptorForCanonEntry('characters', {
+ physicalDescription: ' ',
+ description: 'old desc',
+ })).toBe('old desc');
+ });
+
+ it('returns empty when neither field is set', () => {
+ expect(descriptorForCanonEntry('characters', { name: 'Alice' })).toBe('');
+ });
+
+ it('does NOT include role (role is rich-only)', () => {
+ expect(descriptorForCanonEntry('characters', {
+ physicalDescription: 'tall',
+ role: 'protagonist',
+ })).toBe('tall');
+ });
+ });
+
+ describe('settings', () => {
+ it('joins description + palette + recurringDetails in order', () => {
+ expect(descriptorForCanonEntry('settings', {
+ description: 'a dusty plaza',
+ palette: 'ochre and copper',
+ recurringDetails: 'cracked statue at center',
+ })).toBe('a dusty plaza. Palette: ochre and copper. cracked statue at center');
+ });
+
+ it('prefixes palette with "Palette:"', () => {
+ expect(descriptorForCanonEntry('settings', { palette: 'noir' })).toBe('Palette: noir');
+ });
+
+ it('omits missing fields', () => {
+ expect(descriptorForCanonEntry('settings', {
+ description: 'plaza',
+ recurringDetails: 'statue',
+ })).toBe('plaza. statue');
+ });
+
+ it('does NOT include era or weather (rich-only)', () => {
+ expect(descriptorForCanonEntry('settings', {
+ description: 'plaza',
+ era: '2099',
+ weather: 'foggy',
+ })).toBe('plaza');
+ });
+
+ it('trims whitespace-only fields', () => {
+ expect(descriptorForCanonEntry('settings', {
+ description: ' plaza ',
+ palette: ' ',
+ recurringDetails: 'statue',
+ })).toBe('plaza. statue');
+ });
+ });
+
+ describe('objects', () => {
+ it('uses description as primary', () => {
+ expect(descriptorForCanonEntry('objects', {
+ description: 'a brass key',
+ significance: 'opens the vault',
+ })).toBe('a brass key');
+ });
+
+ it('falls back to significance when description is missing', () => {
+ expect(descriptorForCanonEntry('objects', { significance: 'opens the vault' }))
+ .toBe('opens the vault');
+ });
+
+ it('returns empty when neither field is set', () => {
+ expect(descriptorForCanonEntry('objects', { name: 'Brass Key' })).toBe('');
+ });
+ });
+ });
+
+ describe('shortCanonDescriptorFragments', () => {
+ it('returns empty array for unknown kind', () => {
+ expect(shortCanonDescriptorFragments('unknown', { description: 'x' })).toEqual([]);
+ });
+
+ it('returns ordered fragments for settings', () => {
+ const frags = shortCanonDescriptorFragments('settings', {
+ description: 'plaza',
+ palette: 'noir',
+ recurringDetails: 'statue',
+ });
+ expect(frags).toEqual([
+ { field: 'description', value: 'plaza' },
+ { field: 'palette', value: 'noir', prefix: 'Palette' },
+ { field: 'recurringDetails', value: 'statue' },
+ ]);
+ });
+
+ it('returns a single primary fragment for characters with physicalDescription', () => {
+ expect(shortCanonDescriptorFragments('characters', { physicalDescription: 'tall' }))
+ .toEqual([{ field: 'physicalDescription', value: 'tall' }]);
+ });
+
+ it('returns a single fallback fragment for characters with only description', () => {
+ expect(shortCanonDescriptorFragments('characters', { description: 'old desc' }))
+ .toEqual([{ field: 'description', value: 'old desc' }]);
+ });
+ });
+
+ describe('richCanonDescriptorFragments', () => {
+ it('includes role for characters', () => {
+ const frags = richCanonDescriptorFragments('characters', {
+ physicalDescription: 'tall',
+ role: 'protagonist',
+ });
+ expect(frags).toEqual([
+ { field: 'physicalDescription', value: 'tall' },
+ { field: 'role', value: 'protagonist' },
+ ]);
+ });
+
+ it('includes era and weather for settings', () => {
+ const frags = richCanonDescriptorFragments('settings', {
+ description: 'plaza',
+ palette: 'noir',
+ era: '2099',
+ weather: 'foggy',
+ recurringDetails: 'statue',
+ });
+ expect(frags).toEqual([
+ { field: 'description', value: 'plaza' },
+ { field: 'palette', value: 'noir', prefix: 'Palette' },
+ { field: 'era', value: '2099', prefix: 'Era' },
+ { field: 'weather', value: 'foggy', prefix: 'Weather' },
+ { field: 'recurringDetails', value: 'statue' },
+ ]);
+ });
+
+ it('includes significance additively for objects (not as fallback)', () => {
+ const frags = richCanonDescriptorFragments('objects', {
+ description: 'a brass key',
+ significance: 'opens the vault',
+ });
+ expect(frags).toEqual([
+ { field: 'description', value: 'a brass key' },
+ { field: 'significance', value: 'opens the vault', prefix: 'Significance' },
+ ]);
+ });
+
+ it('does NOT fall back to description for characters', () => {
+ expect(richCanonDescriptorFragments('characters', { description: 'old desc' })).toEqual([]);
+ });
+ });
+
+ describe('hasCanonDescriptorContent', () => {
+ it('is true when any rich field is set', () => {
+ expect(hasCanonDescriptorContent('characters', { physicalDescription: 'tall' })).toBe(true);
+ expect(hasCanonDescriptorContent('characters', { role: 'protagonist' })).toBe(true);
+ expect(hasCanonDescriptorContent('settings', { palette: 'noir' })).toBe(true);
+ expect(hasCanonDescriptorContent('settings', { weather: 'foggy' })).toBe(true);
+ expect(hasCanonDescriptorContent('objects', { significance: 'x' })).toBe(true);
+ });
+
+ it('is false when no rich field is set', () => {
+ expect(hasCanonDescriptorContent('characters', { name: 'Alice' })).toBe(false);
+ expect(hasCanonDescriptorContent('settings', { name: 'Plaza' })).toBe(false);
+ expect(hasCanonDescriptorContent('objects', {})).toBe(false);
+ });
+
+ it('treats whitespace-only fields as empty', () => {
+ expect(hasCanonDescriptorContent('characters', { physicalDescription: ' ' })).toBe(false);
+ });
+
+ it('is false for unknown kind (defensive — known kinds always pass through)', () => {
+ expect(hasCanonDescriptorContent('unknown', { physicalDescription: 'tall' })).toBe(false);
+ });
+
+ it('is false for null entry', () => {
+ expect(hasCanonDescriptorContent('characters', null)).toBe(false);
+ });
+
+ it('short-circuits on first non-blank field (does not allocate array)', () => {
+ // Sanity-check that adding extra blank fields after the first hit
+ // doesn't change the result — guards against accidental regression
+ // back to length-of-array-based implementation.
+ expect(hasCanonDescriptorContent('settings', {
+ description: 'plaza',
+ palette: '',
+ era: '',
+ weather: '',
+ recurringDetails: '',
+ })).toBe(true);
+ });
+ });
+
+ describe('richCanonDescriptorFragments edge cases', () => {
+ it('returns [] for empty settings entry', () => {
+ expect(richCanonDescriptorFragments('settings', {})).toEqual([]);
+ });
+
+ it('coerces non-string field values to empty (no fragment)', () => {
+ expect(richCanonDescriptorFragments('characters', {
+ physicalDescription: 42,
+ role: null,
+ })).toEqual([]);
+ });
+ });
+});
diff --git a/server/lib/scenePrompt.js b/server/lib/scenePrompt.js
index 9ff8496fb2..c7e13c5ae4 100644
--- a/server/lib/scenePrompt.js
+++ b/server/lib/scenePrompt.js
@@ -3,6 +3,8 @@
* deps — mirrored to `client/src/lib/scenePrompt.js` for the client bundle.
*/
+import { shortCanonDescriptorFragments } from './canonPrompt.js';
+
const PROMPT_MAX = 1900;
// Normalize a screenplay slugline so case/punctuation/dash variants collapse:
@@ -139,11 +141,19 @@ export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyle
? matchedSetting.timeOfDay
: '';
const settingMetaFrag = [intExtPart, todPart].filter(Boolean).join(', ');
+ // Pull descriptor fragments via the shared canon-prompt helper so the
+ // setting baseline stays in sync with `KINDS[].descFor` (UI) and
+ // `synthesizeCanonPrompt` (canon-render synthesis). Trailing-period on
+ // prefixed fragments preserves the pre-extraction "Palette: X." sentence
+ // boundary so palette + recurringDetails don't run together when the
+ // budget-truncation join collapses fragments with a single space.
+ const baselineFrags = matchedSetting
+ ? shortCanonDescriptorFragments('setting', matchedSetting)
+ .map((f) => (f.prefix ? `${f.prefix}: ${f.value}.` : f.value))
+ : [];
const settingFrags = matchedSetting ? [
settingMetaFrag ? `${settingMetaFrag}.` : '',
- matchedSetting.description?.trim() || '',
- matchedSetting.palette ? `Palette: ${matchedSetting.palette.trim()}.` : '',
- matchedSetting.recurringDetails?.trim() || '',
+ ...baselineFrags,
].filter(Boolean) : [];
// Accept either `physicalDescription` (writers-room shape) or
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index 7b0a184358..ac3945b311 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -30,6 +30,7 @@ import { randomUUID } from 'crypto';
import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { composeStyledPrompt } from '../lib/composeStyledPrompt.js';
+import { richCanonDescriptorFragments } from '../lib/canonPrompt.js';
import {
sanitizeBibleList, BIBLE_KIND, BIBLE_FIELD, BIBLE_LIMITS, BIBLE_SOURCE,
normalizeBibleName, isStr, trimTo,
@@ -923,14 +924,10 @@ const CANON_TRUNKS = Object.freeze([
{ key: 'objects', category: 'canon:objects' },
]);
-// Synthesize a render prompt from a canon entry. `entry.prompt` wins when the
-// user has hand-authored one; otherwise stitch together the descriptive fields
-// that exist for this kind (per-kind contract in `BIBLE_FIELD_WHITELIST`):
-// - characters: physicalDescription, role
-// - settings: description, palette, era, weather, recurringDetails
-// - objects: description, significance
-// The output is fed through `composeStyledPrompt(...)` so the universe's
-// embrace tokens still prefix every canon render.
+// Synthesize a render prompt from a canon entry. `entry.prompt` wins when
+// hand-authored; otherwise stitch the kind's descriptive fields. Output is
+// fed through `composeStyledPrompt(...)` so the universe's embrace tokens
+// still prefix every canon render.
export function synthesizeCanonPrompt(kind, entry) {
if (!entry) return '';
if (typeof entry.prompt === 'string' && entry.prompt.trim()) return entry.prompt.trim();
@@ -944,21 +941,9 @@ export function synthesizeCanonPrompt(kind, entry) {
? entry.slugline.trim()
: '';
const identifier = name || sluglineId;
- const parts = [];
- if (kind === 'characters') {
- if (entry.physicalDescription) parts.push(entry.physicalDescription);
- if (entry.role) parts.push(entry.role);
- } else if (kind === 'settings') {
- if (entry.description) parts.push(entry.description);
- if (entry.palette) parts.push(`palette: ${entry.palette}`);
- if (entry.era) parts.push(`era: ${entry.era}`);
- if (entry.weather) parts.push(`weather: ${entry.weather}`);
- if (entry.recurringDetails) parts.push(entry.recurringDetails);
- } else if (kind === 'objects') {
- if (entry.description) parts.push(entry.description);
- if (entry.significance) parts.push(`significance: ${entry.significance}`);
- }
- const body = parts.map((p) => String(p).trim()).filter(Boolean).join('. ');
+ const body = richCanonDescriptorFragments(kind, entry)
+ .map((f) => (f.prefix ? `${f.prefix}: ${f.value}` : f.value))
+ .join('. ');
if (identifier && body) return `${identifier} — ${body}`;
return identifier || body;
}
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index 76a59753d3..fb32a98989 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -318,6 +318,50 @@ describe("universeBuilder service", () => {
).resolves.toMatchObject({ name: "User-Renamed" });
});
+ describe("synthesizeCanonPrompt", () => {
+ it("hand-authored prompt wins over field synthesis", () => {
+ expect(svc.synthesizeCanonPrompt("characters", {
+ name: "Mira",
+ prompt: "custom prompt",
+ physicalDescription: "weathered scavenger",
+ })).toBe("custom prompt");
+ });
+
+ it("synthesizes from identifier + RICH descriptor for characters", () => {
+ expect(svc.synthesizeCanonPrompt("characters", {
+ name: "Mira",
+ physicalDescription: "weathered scavenger",
+ role: "protagonist",
+ })).toBe("Mira — weathered scavenger. protagonist");
+ });
+
+ it("synthesizes from identifier + RICH descriptor for settings (capitalized prefixes)", () => {
+ expect(svc.synthesizeCanonPrompt("settings", {
+ name: "Foundry City",
+ description: "vast smelting works",
+ palette: "rust + bone",
+ era: "post-collapse",
+ weather: "ash haze",
+ recurringDetails: "broken statue at center",
+ })).toBe("Foundry City — vast smelting works. Palette: rust + bone. Era: post-collapse. Weather: ash haze. broken statue at center");
+ });
+
+ it("falls back to slugline as identifier for settings without name", () => {
+ expect(svc.synthesizeCanonPrompt("settings", {
+ slugline: "INT. FOUNDRY — DAY",
+ description: "ore furnace",
+ })).toBe("INT. FOUNDRY — DAY — ore furnace");
+ });
+
+ it("returns identifier alone when no descriptive fields are set", () => {
+ expect(svc.synthesizeCanonPrompt("characters", { name: "Mira" })).toBe("Mira");
+ });
+
+ it("returns empty string for null entry", () => {
+ expect(svc.synthesizeCanonPrompt("characters", null)).toBe("");
+ });
+ });
+
describe("compilePrompts", () => {
it("returns one prompt per variation across selected categories with style prefix", async () => {
const w = await seedWorld();
@@ -563,7 +607,7 @@ describe("universeBuilder service", () => {
const place = compiled.find((c) => c.label === "Foundry City");
expect(place.category).toBe("canon:settings");
expect(place.prompt).toContain("Foundry City");
- expect(place.prompt).toContain("palette: rust + bone");
+ expect(place.prompt).toContain("Palette: rust + bone");
});
it("canonSelection: missing trunk skips it", () => {