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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([pipeline-continuity-approval]): season-lock-aware resolve + worldEntitiesSummary + speechPattern
[._.]/ Adam Eivy1903e5fedce1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5cd350456a..dfcd547460 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,9 @@## Added+- **Season-lock-aware arc resolve.** `commitSeasonsWithRemap` now restores locked seasons field-for-field over LLM-proposed rewrites (via a new `mergeSeasonsWithLocks` helper) and re-inserts any locked season the LLM drops from the new shape. Auto-resolve + `/arc/generate` honor per-season `locked: true` flags without needing to unlock the whole arc — mirrors the per-field arc-lock pattern.+- **`worldEntitiesSummary` template variable in text-stage prompts.** New `renderEntitiesSummary` helper in `server/lib/universePromptRenderers.js` produces a compact one-line-per-kind synopsis of a linked universe's named canon (top-N entries per kind, 80-char descriptor cap). Plumbed into `loadWorldContext` (arc/verify/resolve contexts) and `textStages.buildStageContext` (per-issue prose/teleplay/comic-script). Migration 027 updates the three text-stage prompts to reference `{{worldEntitiesSummary}}` in a new "Universe at a glance" block.+- **Character bible `speechPattern` field.** Splits the historic `speechAccent` (regional/cultural accent) from the new dedicated `speechPattern` (cadence, sentence structure, lexical tics, recurring phrases — distinct from `voiceId`, which is the TTS engine pointer). Field is piped through the sanitizer + `MERGE_CONFIG`, the universe character-expand contract + prompt, the rendered reference-sheet header, the `CharacterDetailEditor.jsx` UI, and the prose/teleplay/comic-script character render mustache so dialogue carries the character's prose voice. Migration 027 handles existing installs.- **Per-stage editorial locks on Pipeline issues.** Each `issue.stages.{id}` now carries a `locked` flag; locked stages refuse regeneration (text generate, image / video enqueue, refine, extract-scenes / extract-pages, audio extract / render, episode-video fresh start, cover-concepts commit). UI exposes a lock toggle on every Pipeline Issue tab and renders a per-stage Lock indicator on the TabPills strip, so users can freeze a finalized comic script while still iterating storyboards.- **Per-field arc locks on series.** `series.locked.arcFields` is an opt-in sub-map (`{ logline, summary, themes, protagonistArc, shape }`); locked fields are preserved verbatim through `commitSeasonsWithRemap` so arc regenerate + auto-resolve only rewrite the unlocked fields. Inline lock icons on the Arc Canvas read view toggle each field.- **Pagination on `GET /api/pipeline/series/:id/issues`.** Accepts optional `?offset=N&limit=N`; when present, returns `{ items, total, offset, limit }`. Without the params, the endpoint still returns the legacy raw array. Eliminates the silent 1000-issue cap for long-running series.diff --git a/PLAN.md b/PLAN.mdindex b9eb1731d6..cc6bddd8a1 100644--- a/PLAN.md+++ b/PLAN.md@@ -22,9 +22,9 @@ _Nothing currently parked — pick the next item from the Backlog._### Pipeline continuity / approval-- [ ] [season-lock-aware-arc-resolve] **Make `resolveVerifyIssues` respect per-season locks.** Today the arc-level lock blocks resolve entirely. With per-season locks landed (the parent slug above), a user can unlock the arc but keep individual seasons frozen; auto-resolve would currently rewrite locked season metadata via `commitSeasonsWithRemap` → `updateSeries({ arc, seasons })`. Either (a) refuse resolve up-front with a "seasons X, Y are locked — unlock or skip" error, or (b) teach `commitSeasonsWithRemap` to preserve `locked` season payloads field-for-field on merge.-- [ ] [pipeline-text-stages-worldentitiessummary] **Add `worldEntitiesSummary` to text stages.** Zero occurrences in codebase today; a one-string canon synopsis (top-N entities by frequency, name + 1-line descriptor) keeps text-stage prompts under context budget while still giving the LLM continuity anchors.-- [ ] [bible-schema-speech-pattern-field] **Add a dedicated speech-pattern field to the character bible schema.** `voiceId` is the TTS engine pointer, not a written speech-pattern field. Add to `PROMPT_FIELDS[CHARACTER]` in `server/lib/storyBible.js:121` and pipe through extraction + script prompts.+- [x] ~~[season-lock-aware-arc-resolve] **Make `resolveVerifyIssues` respect per-season locks.**~~ Shipped via `mergeSeasonsWithLocks` inside `commitSeasonsWithRemap` (`server/services/pipeline/arcPlanner.js`) — auto-resolve and `/arc/generate` now restore locked seasons field-for-field over LLM rewrites and re-insert any locked season the LLM dropped from the new shape, mirroring the per-field arc-lock pattern.+- [x] ~~[pipeline-text-stages-worldentitiessummary] **Add `worldEntitiesSummary` to text stages.**~~ Shipped via `renderEntitiesSummary` in `server/lib/universePromptRenderers.js` (compact one-line-per-kind synopsis, 8 entries max per kind) + plumbed through `loadWorldContext` (arc context) and `textStages.buildStageContext` (text context) + migration 027 + prompt updates to `pipeline-prose.md` / `pipeline-teleplay.md` / `pipeline-comic-script.md`.+- [x] ~~[bible-schema-speech-pattern-field] **Add a dedicated speech-pattern field to the character bible schema.**~~ Shipped — `speechPattern` field added to `BIBLE_LIMITS`, `PROMPT_FIELDS[CHARACTER]`, `sanitizeCharacter`, `MERGE_CONFIG.character.userEditable`, `universeCharacterExpand`'s `STRING_FIELDS`, `universeCharacterSheet`'s rendered prompt, `CharacterDetailEditor.jsx` UI, the `universe-character-expand` prompt template + JSON contract, and the prose/teleplay/comic-script character render mustache. Migration 027 updates existing installs cleanly.### Creative Director / Audiodiff --git a/client/src/components/universe/CharacterDetailEditor.jsx b/client/src/components/universe/CharacterDetailEditor.jsxindex bb2dcf0dd7..42faa15eb1 100644--- a/client/src/components/universe/CharacterDetailEditor.jsx+++ b/client/src/components/universe/CharacterDetailEditor.jsx@@ -25,7 +25,8 @@ const SECTIONS = Object.freeze([{ name: 'pronouns', label: 'Pronouns', placeholder: 'she/her · they/them · it/its', max: L.PRONOUNS_MAX, type: 'input' },{ name: 'age', label: 'Age', placeholder: '27 · centuries old · unknown', max: L.AGE_MAX, type: 'input' },{ name: 'coreTheme', label: 'Core theme', placeholder: 'one-sentence essence', max: L.CORE_THEME_MAX, type: 'textarea' },- { name: 'speechAccent', label: 'Speech / accent', placeholder: 'clipped Edinburgh; rarely contracts; nautical metaphors', max: L.SPEECH_ACCENT_MAX, type: 'textarea' },+ { name: 'speechAccent', label: 'Accent', placeholder: 'clipped Edinburgh · Brooklyn drawl · off-world inflection', max: L.SPEECH_ACCENT_MAX, type: 'textarea' },+ { name: 'speechPattern', label: 'Speech pattern', placeholder: 'rarely contracts; nautical metaphors; trails off into ellipses when uncertain', max: L.SPEECH_PATTERN_MAX, type: 'textarea' },{ name: 'visualNotes', label: 'Visual notes (at-a-glance)', placeholder: 'layered streetwear; faded mustard + charcoal; chunky boots', max: L.VISUAL_NOTES_MAX, type: 'textarea' },],},diff --git a/client/src/lib/bibleLimits.js b/client/src/lib/bibleLimits.jsindex f0b2dc0ba8..3c126d3f9a 100644--- a/client/src/lib/bibleLimits.js+++ b/client/src/lib/bibleLimits.js@@ -16,6 +16,7 @@ export const BIBLE_LIMITS = Object.freeze({AGE_MAX: 80,CORE_THEME_MAX: 500,SPEECH_ACCENT_MAX: 500,+ SPEECH_PATTERN_MAX: 1000,VISUAL_NOTES_MAX: 1000,SILHOUETTE_NOTES_MAX: 2000,POSTURE_NOTES_MAX: 1000,diff --git a/data.sample/prompts/stages/pipeline-comic-script.md b/data.sample/prompts/stages/pipeline-comic-script.mdindex 4ee97b4f89..4a65a39f42 100644--- a/data.sample/prompts/stages/pipeline-comic-script.md+++ b/data.sample/prompts/stages/pipeline-comic-script.md@@ -10,9 +10,17 @@ You are a comics writer turning a prose draft into a publishable comic-book issu### Characters{{#series.characters}}-- **{{name}}**{{#role}} ({{role}}){{/role}} — {{#physicalDescription}}{{physicalDescription}}{{/physicalDescription}}{{^physicalDescription}}{{description}}{{/physicalDescription}}{{#personality}} | personality: {{personality}}{{/personality}}{{#background}} | background: {{background}}{{/background}}+- **{{name}}**{{#role}} ({{role}}){{/role}} — {{#physicalDescription}}{{physicalDescription}}{{/physicalDescription}}{{^physicalDescription}}{{description}}{{/physicalDescription}}{{#personality}} | personality: {{personality}}{{/personality}}{{#background}} | background: {{background}}{{/background}}{{#speechAccent}} | accent: {{speechAccent}}{{/speechAccent}}{{#speechPattern}} | speech: {{speechPattern}}{{/speechPattern}}{{/series.characters}}+### Universe at a glance++Terse roster of the linked Universe Builder's named canon — use as continuity anchors for the panels you draft. Do not contradict; you may name-check but don't invent new attributes for them.++```+{{worldEntitiesSummary}}+```+## This issue- **Number:** {{issue.number}}diff --git a/data.sample/prompts/stages/pipeline-prose.md b/data.sample/prompts/stages/pipeline-prose.mdindex b6687f79c2..ef093b56cf 100644--- a/data.sample/prompts/stages/pipeline-prose.md+++ b/data.sample/prompts/stages/pipeline-prose.md@@ -12,9 +12,17 @@ You are a short-fiction author drafting one issue / episode of an ongoing series### Characters{{#series.characters}}-- **{{name}}**{{#role}} ({{role}}){{/role}} — {{#physicalDescription}}{{physicalDescription}}{{/physicalDescription}}{{^physicalDescription}}{{description}}{{/physicalDescription}}{{#personality}} | personality: {{personality}}{{/personality}}{{#background}} | background: {{background}}{{/background}}+- **{{name}}**{{#role}} ({{role}}){{/role}} — {{#physicalDescription}}{{physicalDescription}}{{/physicalDescription}}{{^physicalDescription}}{{description}}{{/physicalDescription}}{{#personality}} | personality: {{personality}}{{/personality}}{{#background}} | background: {{background}}{{/background}}{{#speechAccent}} | accent: {{speechAccent}}{{/speechAccent}}{{#speechPattern}} | speech: {{speechPattern}}{{/speechPattern}}{{/series.characters}}+### Universe at a glance++A terse roster of the linked Universe Builder's named canon — use these as continuity anchors when scenes reference broader-than-series entities. Do not contradict; you may name-check but don't invent new attributes for them.++```+{{worldEntitiesSummary}}+```+## This issue- **Number:** {{issue.number}}diff --git a/data.sample/prompts/stages/pipeline-teleplay.md b/data.sample/prompts/stages/pipeline-teleplay.mdindex df1bd368ed..a032d959a3 100644--- a/data.sample/prompts/stages/pipeline-teleplay.md+++ b/data.sample/prompts/stages/pipeline-teleplay.md@@ -10,9 +10,17 @@ You are a TV writer adapting a prose draft into a single-episode teleplay in sta### Characters{{#series.characters}}-- **{{name}}**{{#role}} ({{role}}){{/role}} — {{#physicalDescription}}{{physicalDescription}}{{/physicalDescription}}{{^physicalDescription}}{{description}}{{/physicalDescription}}{{#personality}} | personality: {{personality}}{{/personality}}{{#background}} | background: {{background}}{{/background}}+- **{{name}}**{{#role}} ({{role}}){{/role}} — {{#physicalDescription}}{{physicalDescription}}{{/physicalDescription}}{{^physicalDescription}}{{description}}{{/physicalDescription}}{{#personality}} | personality: {{personality}}{{/personality}}{{#background}} | background: {{background}}{{/background}}{{#speechAccent}} | accent: {{speechAccent}}{{/speechAccent}}{{#speechPattern}} | speech: {{speechPattern}}{{/speechPattern}}{{/series.characters}}+### Universe at a glance++Terse roster of the linked Universe Builder's named canon — use as continuity anchors for scenes/locations the teleplay touches. Do not contradict; you may name-check but don't invent new attributes for them.++```+{{worldEntitiesSummary}}+```+## This episode- **Number:** {{issue.number}}diff --git a/data.sample/prompts/stages/universe-character-expand.md b/data.sample/prompts/stages/universe-character-expand.mdindex 148a5602a3..d306a7b359 100644--- a/data.sample/prompts/stages/universe-character-expand.md+++ b/data.sample/prompts/stages/universe-character-expand.md@@ -33,7 +33,8 @@ For every BLANK field in the character JSON above, propose a value that:- `pronouns` — short form ("she/her", "they/them", "it/its", "no pronouns — referred to as 'the Reach'").- `age` — flexible string ("27", "centuries old", "newly hatched", "unknown — appears mid-30s"). Don't force a number.- `coreTheme` — the character's one-sentence thematic essence ("a cartographer of grief", "the city's last honest broker").-- `speechAccent` — written speech pattern + accent ("clipped Edinburgh, rarely contracts; uses nautical metaphors").+- `speechAccent` — regional / cultural accent only ("clipped Edinburgh", "Brooklyn drawl", "off-world inflection — vowels stretch"). Keep narrow; the rhythm + lexicon goes in `speechPattern`.+- `speechPattern` — written speech rhythm: sentence structure, cadence, vocabulary tics, recurring phrases ("rarely contracts; uses nautical metaphors; trails off into ellipses when uncertain; never swears, prefers archaic substitutes like 'damnation'"). Distinct from `voiceId` (the TTS engine pointer) — this drives how dialogue *reads* on the page, before any voice synth.- `visualNotes` — 1–2 sentences capturing the at-a-glance silhouette and palette ("layered practical streetwear in faded mustard + charcoal; chunky boots; ever-present beanie").- `silhouetteNotes` — bulleted-as-prose distinctive shape features ("compact upper body; layered silhouette; tapered lower half; short hair adds 5cm height").- `postureNotes` — habitual posture cues ("slight forward lean; weight in left foot; shoulders loose; ready-to-move; eyes constantly scanning").@@ -61,6 +62,7 @@ Return ONLY valid JSON, no markdown fence, no commentary. Include ONLY the keys"age": "string","coreTheme": "string","speechAccent": "string",+ "speechPattern": "string","visualNotes": "string","silhouetteNotes": "string","postureNotes": "string",diff --git a/scripts/migrations/027-text-stage-prompts-entities-summary.js b/scripts/migrations/027-text-stage-prompts-entities-summary.jsnew file mode 100644index 0000000000..a25857161d--- /dev/null+++ b/scripts/migrations/027-text-stage-prompts-entities-summary.js@@ -0,0 +1,83 @@+/**+ * Two related prompt updates, bundled because they touch overlapping files:+ *+ * (a) Add `{{worldEntitiesSummary}}` block to the three per-issue text-stage+ * prompts so they receive a compact one-line-per-kind synopsis of the+ * linked Universe Builder's canon.+ *+ * (b) Pipe the new `speechPattern` (and accompanying `speechAccent`)+ * character bible field through the same three script-stage prompts ++ * the universe-character-expand prompt so dialogue carries the+ * character's prose voice on the page.+ *+ * Updates (per ACCEPTED_OLD_MD5 below):+ * - data/prompts/stages/pipeline-prose.md+ * - data/prompts/stages/pipeline-teleplay.md+ * - data/prompts/stages/pipeline-comic-script.md+ * - data/prompts/stages/universe-character-expand.md+ *+ * Why:+ * Text stages historically only got `{{#series.characters}}` (the series+ * bible). When a series is linked to a Universe Builder world, that bible+ * excludes universe-level places/objects and other characters that haven't+ * been pulled into the series canon — so scripts could namelessly drift+ * from established continuity even when the universe had a rich roster.+ * `worldEntitiesSummary` is a budget-aware alternative to the full+ * `worldCanonText` block: one tagged line per kind, capped at 8 entries.+ *+ * Separately, `speechAccent` historically conflated regional accent with+ * speech patterns (cadence/lexicon/tics). Splitting it into a dedicated+ * `speechPattern` field lets the universe-character-expand pass populate+ * them independently, and lets the three script stages quote both for+ * dialogue continuity.+ *+ * Implementation: hash-driven prompt-replace via `./_lib.js`. Idempotent.+ */++import { makePromptReplaceMigration } from './_lib.js';++export const ACCEPTED_OLD_MD5 = {+ 'pipeline-prose.md': [+ '30ac30ec2b9d3e2a9eb869c181732cc6', // post-003 / pre-027 shipped+ 'bfea5aeeb471aae9749baee765b473a7', // pre-003 (in setup-data OLD list)+ ],+ 'pipeline-teleplay.md': [+ '376f779f4687b598f1c92ca4e770fd5a', // pre-027 shipped+ '3f6fecc25573ed054b47db392250034a', // pre-shape (in setup-data OLD list)+ ],+ 'pipeline-comic-script.md': [+ '1e0af305c27d0c80c4b482d2ebcb4a0d', // post-011 / pre-027 shipped+ 'beab031951859ca13579cdb9c4dbe769', // pre-011 (in setup-data OLD list)+ '40e5fdc1a1e68a7419b7dad936366c1a', // pre-003 (in setup-data OLD list)+ ],+ 'universe-character-expand.md': [+ 'ef109eb8e12ddb664c11c790271b5139', // pre-027 shipped+ ],+};++export const NEW_SHIPPED_MD5 = {+ 'pipeline-prose.md': 'd1f8e3f1d214725b5aa67f309a81cd7d',+ 'pipeline-teleplay.md': '1280ef6b1ad68fa44070ca7478ec2a5f',+ 'pipeline-comic-script.md': '133d200d069c2e8173b7c129eea58f53',+ 'universe-character-expand.md': '67b6e73ed47f318451a730088b4cff14',+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'text-stage entities-summary + speechPattern',+ customizedHint: (filename) =>+ ` To pick up {{worldEntitiesSummary}} + {{speechPattern}} / {{speechAccent}} manually, diff:\n` ++ ` data.sample/prompts/stages/${filename}\n` ++ ` against your current:\n` ++ ` data/prompts/stages/${filename}\n` ++ ` and merge the new blocks in the same position as in the sample template.`,+ skipFooter: (count) =>+ `⚠️ ${count} prompt(s) could not be auto-updated because they were customized.\n` ++ ` The {{worldEntitiesSummary}} block + {{speechPattern}} / {{speechAccent}} renderers\n` ++ ` will not appear in those prompts until the files are merged manually. See\n` ++ ` data.sample/prompts/stages/.`,+});++export { applyMigration };+export default { up };diff --git a/scripts/migrations/027-text-stage-prompts-entities-summary.test.js b/scripts/migrations/027-text-stage-prompts-entities-summary.test.jsnew file mode 100644index 0000000000..18701656f8--- /dev/null+++ b/scripts/migrations/027-text-stage-prompts-entities-summary.test.js@@ -0,0 +1,121 @@+/**+ * Test for migration 027 — text-stage prompts gain {{worldEntitiesSummary}}+ * and pipe {{speechAccent}} / {{speechPattern}} through character renders.+ *+ * Mirrors migration 019's test scaffolding — temp-dir fixtures, the same+ * drift-catch assertion against the live data.sample bodies, and an+ * OLD→NEW upgrade branch driven by synthetic hash tables so the test+ * doesn't depend on git history.+ *+ * Picked up via the vitest include glob in server/vitest.config.js+ * (`../scripts/migrations/**\/*.test.js`).+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { createHash } from 'crypto';++import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './027-text-stage-prompts-entities-summary.js';++const md5 = (str) => createHash('md5')+ .update(str.replace(/\r\n/g, '\n').replace(/\r/g, '\n'))+ .digest('hex');++const repoRoot = join(import.meta.dirname || dirname(fileURLToPath(import.meta.url)), '..', '..');+const sampleBody = (filename) =>+ readFileSync(join(repoRoot, 'data.sample', 'prompts', 'stages', filename), 'utf-8');++const customizedBody = (filename) => `# CUSTOMIZED ${filename}\n\nuser-modified content not matching any shipped hash\n`;++describe('migration 027 — text-stage prompts entities-summary + speechPattern', () => {+ let rootDir;+ let stagesDir;+ let sampleDir;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-027-'));+ stagesDir = join(rootDir, 'data', 'prompts', 'stages');+ sampleDir = join(rootDir, 'data.sample', 'prompts', 'stages');+ mkdirSync(stagesDir, { recursive: true });+ mkdirSync(sampleDir, { recursive: true });+ for (const filename of Object.keys(NEW_SHIPPED_MD5)) {+ writeFileSync(join(sampleDir, filename), sampleBody(filename));+ }+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('no-ops when the stage prompt is missing (setup-data.js will create it)', async () => {+ await expect(migration.up({ rootDir })).resolves.not.toThrow();+ for (const filename of Object.keys(NEW_SHIPPED_MD5)) {+ expect(existsSync(join(stagesDir, filename))).toBe(false);+ }+ });++ it('skips files already at the new hash (idempotent re-run)', async () => {+ for (const filename of Object.keys(NEW_SHIPPED_MD5)) {+ writeFileSync(join(stagesDir, filename), sampleBody(filename));+ }+ const before = Object.fromEntries(+ Object.keys(NEW_SHIPPED_MD5).map((f) => [f, readFileSync(join(stagesDir, f), 'utf-8')]),+ );+ const result = await applyMigration({ rootDir });+ expect(result).toMatchObject({+ updated: 0,+ alreadyCurrent: Object.keys(NEW_SHIPPED_MD5).length,+ skipped: 0,+ });+ for (const filename of Object.keys(NEW_SHIPPED_MD5)) {+ const after = readFileSync(join(stagesDir, filename), 'utf-8');+ expect(after).toBe(before[filename]);+ }+ });++ it('NEW_SHIPPED_MD5 matches the live data.sample bodies (drift catch)', () => {+ for (const filename of Object.keys(NEW_SHIPPED_MD5)) {+ const liveHash = md5(sampleBody(filename));+ expect(liveHash).toBe(NEW_SHIPPED_MD5[filename]);+ }+ });++ it('upgrades when on-disk hash matches an accepted-old entry (synthetic fixture)', async () => {+ const filename = 'pipeline-prose.md';+ const fakeOldBody = `# synthetic pre-migration body for ${filename}\n`;+ const fakeOldHash = md5(fakeOldBody);++ writeFileSync(join(stagesDir, filename), fakeOldBody);+ const result = await applyMigration({+ rootDir,+ accepted: { [filename]: [fakeOldHash] },+ current: { [filename]: md5(sampleBody(filename)) },+ });+ expect(result).toMatchObject({ updated: 1, skipped: 0 });+ expect(readFileSync(join(stagesDir, filename), 'utf-8')).toBe(sampleBody(filename));+ });++ it('skips (does not clobber) a customized file whose hash matches neither old nor new', async () => {+ for (const filename of Object.keys(NEW_SHIPPED_MD5)) {+ writeFileSync(join(stagesDir, filename), customizedBody(filename));+ }+ await migration.up({ rootDir });+ for (const filename of Object.keys(NEW_SHIPPED_MD5)) {+ expect(readFileSync(join(stagesDir, filename), 'utf-8')).toBe(customizedBody(filename));+ }+ });++ it('exposes ACCEPTED_OLD_MD5 and NEW_SHIPPED_MD5 with consistent shapes', () => {+ expect(Object.keys(ACCEPTED_OLD_MD5).sort()).toEqual(Object.keys(NEW_SHIPPED_MD5).sort());+ for (const old of Object.values(ACCEPTED_OLD_MD5)) {+ expect(Array.isArray(old)).toBe(true);+ expect(old.length).toBeGreaterThan(0);+ for (const h of old) expect(h).toMatch(/^[0-9a-f]{32}$/);+ }+ for (const h of Object.values(NEW_SHIPPED_MD5)) {+ expect(h).toMatch(/^[0-9a-f]{32}$/);+ }+ });+});diff --git a/scripts/setup-data.js b/scripts/setup-data.jsindex 4885c4b6c0..46c3cfb1cc 100644--- a/scripts/setup-data.js+++ b/scripts/setup-data.js@@ -142,11 +142,15 @@ const SHIPPED_PROMPT_OLD_MD5 = {// 1ee44c… (post-004, pre-025) all auto-updatable to the post-025// (role/physicalDescription/personality/background plumbing) hash.'pipeline-idea-expansion.md': ['aee25112b2c596f643b17c559b772c22', '41facefbc0c0549d456bef9111f95ab9', '1ee44cf95851ff8debf18729ebcd40b4'],- 'pipeline-prose.md': 'bfea5aeeb471aae9749baee765b473a7',- // comic-script: 40e5fd… (pre-003) and beab03… (post-003, pre-011) both- // auto-updatable to the post-011 (back-cover) hash.- 'pipeline-comic-script.md': ['40e5fdc1a1e68a7419b7dad936366c1a', 'beab031951859ca13579cdb9c4dbe769'],- 'pipeline-teleplay.md': '3f6fecc25573ed054b47db392250034a',+ // prose: bfea5a… (pre-003) and 30ac30… (post-003, pre-027) both auto-+ // updatable to the post-027 ({{worldEntitiesSummary}}) hash.+ 'pipeline-prose.md': ['bfea5aeeb471aae9749baee765b473a7', '30ac30ec2b9d3e2a9eb869c181732cc6'],+ // comic-script: 40e5fd… (pre-003), beab03… (post-003, pre-011), and 1e0af3…+ // (post-011, pre-027) all auto-updatable to the post-027 ({{worldEntitiesSummary}}) hash.+ 'pipeline-comic-script.md': ['40e5fdc1a1e68a7419b7dad936366c1a', 'beab031951859ca13579cdb9c4dbe769', '1e0af305c27d0c80c4b482d2ebcb4a0d'],+ // teleplay: 3f6fec… (pre-027) auto-updatable to the post-027+ // ({{worldEntitiesSummary}}) hash. Original 376f77… is the post-027 prior.+ 'pipeline-teleplay.md': ['3f6fecc25573ed054b47db392250034a', '376f779f4687b598f1c92ca4e770fd5a'],// season-episodes: 6e349a… (pre-003) and c4928e… (post-003, pre-005) both// auto-updatable to the post-005 (shape-aware) hash.'pipeline-season-episodes.md': ['6e349ad26bed8a0ccb042571f03f03eb', 'c4928e2a5f833358116b29d2d669888d'],@@ -170,6 +174,9 @@ const SHIPPED_PROMPT_OLD_MD5 = {// hash that was the NEW shipped before this rename). Both can be// auto-bumped to the post-rename shape.'writers-room-places.md': ['7f1f80eb63d67a21161994cde115045e', '24a33628cc94d80fa5ca60831d973daf'],+ // universe-character-expand: pre-027 shipped, auto-updatable to the post-027+ // (`speechPattern` field added alongside `speechAccent`) hash.+ 'universe-character-expand.md': ['ef109eb8e12ddb664c11c790271b5139'],// CoS agent prompt: drop obsolete "# Chief of Staff Agent Briefing" header// and "You are an autonomous agent…" preamble (migration 009). Every// historical shipped hash is auto-updatable to the new sample.@@ -184,9 +191,9 @@ const SHIPPED_PROMPT_OLD_MD5 = {};const SHIPPED_PROMPT_NEW_MD5 = {'pipeline-idea-expansion.md': '1f3c5d077a5ef9a4b610335d5e3edd9c',- 'pipeline-prose.md': '30ac30ec2b9d3e2a9eb869c181732cc6',- 'pipeline-comic-script.md': '1e0af305c27d0c80c4b482d2ebcb4a0d',- 'pipeline-teleplay.md': '376f779f4687b598f1c92ca4e770fd5a',+ 'pipeline-prose.md': 'd1f8e3f1d214725b5aa67f309a81cd7d',+ 'pipeline-comic-script.md': '133d200d069c2e8173b7c129eea58f53',+ 'pipeline-teleplay.md': '1280ef6b1ad68fa44070ca7478ec2a5f','pipeline-season-episodes.md':'50c68a29c3ebc275db3095d06bd87100','pipeline-arc-overview.md': '0a1f6ffa6908522e3690c5e9e53a6ee0','pipeline-arc-verify.md': '36aa70cdfc25d7549573a4d556e7702c',@@ -195,6 +202,7 @@ const SHIPPED_PROMPT_NEW_MD5 = {'pipeline-extract-scenes.md': 'c51fb208568d0d903eb43b437478b0ba','writers-room-places.md': 'a7f68e51dd6b4421d20f5bd9d855d9b4','cos-agent-briefing.md': 'dccb392a43cbd3dac900fee12c31619a',+ 'universe-character-expand.md':'67b6e73ed47f318451a730088b4cff14',};const SHIPPED_PROMPT_FILES = Object.keys(SHIPPED_PROMPT_OLD_MD5);diff --git a/server/lib/storyBible.js b/server/lib/storyBible.jsindex 48c9d41145..6e90db8c31 100644--- a/server/lib/storyBible.js+++ b/server/lib/storyBible.js@@ -35,6 +35,11 @@ export const BIBLE_LIMITS = Object.freeze({AGE_MAX: 80,CORE_THEME_MAX: 500,SPEECH_ACCENT_MAX: 500,+ // Written speech-pattern: cadence, sentence-structure, lexical tics, vocal+ // habits — *not* the regional accent (that lives in SPEECH_ACCENT_MAX).+ // Roomier than accent because writers tend to describe rhythm + vocabulary+ // + idiom in one paragraph.+ SPEECH_PATTERN_MAX: 1000,VISUAL_NOTES_MAX: 1000,SILHOUETTE_NOTES_MAX: 2000,POSTURE_NOTES_MAX: 1000,@@ -159,7 +164,7 @@ export const BIBLE_KINDS = Object.freeze(Object.values(BIBLE_KIND));// `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', 'pronouns', 'age', 'coreTheme', 'speechAccent', 'visualNotes', 'physicalDescription', 'personality', 'background', 'silhouetteNotes', 'postureNotes', 'specialTraits', 'visualIdentity', 'motivations', 'likes', 'dislikes', 'mannerisms', 'relationships', 'skills', 'stats', 'colorPalette', 'props', 'expressions', 'handGestures', 'voiceId', 'wardrobes', 'prompt', 'tags'],+ [BIBLE_KIND.CHARACTER]: ['name', 'aliases', 'role', 'pronouns', 'age', 'coreTheme', 'speechAccent', 'speechPattern', 'visualNotes', 'physicalDescription', 'personality', 'background', 'silhouetteNotes', 'postureNotes', 'specialTraits', 'visualIdentity', 'motivations', 'likes', 'dislikes', 'mannerisms', 'relationships', 'skills', 'stats', 'colorPalette', 'props', 'expressions', 'handGestures', 'voiceId', 'wardrobes', 'prompt', 'tags'],[BIBLE_KIND.PLACE]: ['name', 'slugline', 'description', 'palette', 'era', 'weather', 'intExt', 'timeOfDay', 'recurringDetails', 'prompt', 'tags'],[BIBLE_KIND.OBJECT]: ['name', 'aliases', 'description', 'significance', 'prompt', 'tags'],});@@ -499,6 +504,11 @@ export function sanitizeCharacter(raw, { idPrefix = DEFAULT_ID_PREFIX.character,age: trimTo(raw.age, BIBLE_LIMITS.AGE_MAX),coreTheme: trimTo(raw.coreTheme, BIBLE_LIMITS.CORE_THEME_MAX),speechAccent: trimTo(raw.speechAccent, BIBLE_LIMITS.SPEECH_ACCENT_MAX),+ // Written speech-pattern (cadence, sentence-structure, lexical tics) —+ // distinct from `voiceId` (TTS engine pointer) and `speechAccent`+ // (regional/cultural accent). Used by script + script-adjacent prompts so+ // dialogue carries the character's prose voice, not just their accent.+ speechPattern: trimTo(raw.speechPattern, BIBLE_LIMITS.SPEECH_PATTERN_MAX),visualNotes: trimTo(raw.visualNotes, BIBLE_LIMITS.VISUAL_NOTES_MAX),physicalDescription,personality: trimTo(raw.personality, BIBLE_LIMITS.PERSONALITY_MAX),@@ -654,7 +664,7 @@ const MERGE_CONFIG = Object.freeze({// operational fields (`referenceSheetImageRef`, `primaryImageRef`,// `imageRefs`) intentionally aren't here — those are owned by the// render flow, not the prose extractor.- 'pronouns', 'age', 'coreTheme', 'speechAccent', 'visualNotes',+ 'pronouns', 'age', 'coreTheme', 'speechAccent', 'speechPattern', 'visualNotes','silhouetteNotes', 'postureNotes', 'specialTraits', 'visualIdentity','motivations', 'likes', 'dislikes', 'mannerisms', 'relationships', 'skills','stats', 'colorPalette', 'props', 'expressions', 'handGestures',diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.jsindex 1b6f6e213c..a3281654e6 100644--- a/server/lib/storyBible.test.js+++ b/server/lib/storyBible.test.js@@ -274,6 +274,7 @@ describe('storyBible — sanitizeCharacter', () => {expect(out.age).toBe('');expect(out.coreTheme).toBe('');expect(out.speechAccent).toBe('');+ expect(out.speechPattern).toBe('');expect(out.visualNotes).toBe('');expect(out.silhouetteNotes).toBe('');expect(out.postureNotes).toBe('');@@ -302,6 +303,7 @@ describe('storyBible — sanitizeCharacter', () => {age: '27',coreTheme: 'cartographer of grief',speechAccent: 'clipped Edinburgh',+ speechPattern: 'rarely contracts; nautical metaphors; ends statements as questions',visualNotes: 'layered streetwear',silhouetteNotes: 'compact upper body',postureNotes: 'slight forward lean',@@ -318,6 +320,7 @@ describe('storyBible — sanitizeCharacter', () => {expect(out.age).toBe('27');expect(out.coreTheme).toBe('cartographer of grief');expect(out.skills).toBe('conversational Mandarin, sleight-of-hand');+ expect(out.speechPattern).toBe('rarely contracts; nautical metaphors; ends statements as questions');});it('caps every new string field at its BIBLE_LIMITS bound', () => {diff --git a/server/lib/universePromptRenderers.js b/server/lib/universePromptRenderers.jsindex e246c61222..65d757c2f7 100644--- a/server/lib/universePromptRenderers.js+++ b/server/lib/universePromptRenderers.js@@ -117,3 +117,79 @@ export function renderCanonForPrompt(world) {}return sections.join('\n\n');}++// Per-kind caps for the compact entity summary. The summary is meant for+// per-issue text stages (prose/teleplay/comic-script) where the full canon+// dump would dominate the prompt — keep one short line per kind so the LLM+// gets continuity anchors without the budget hit.+export const ENTITIES_SUMMARY_MAX_PER_KIND = 8;+export const ENTITIES_SUMMARY_DESCRIPTOR_MAX = 80;++const truncOneLine = (s) => {+ if (typeof s !== 'string') return '';+ const flat = s.trim().replace(/\s+/g, ' ');+ if (!flat) return '';+ if (flat.length <= ENTITIES_SUMMARY_DESCRIPTOR_MAX) return flat;+ return `${flat.slice(0, ENTITIES_SUMMARY_DESCRIPTOR_MAX - 1).trimEnd()}…`;+};++// Pick the most useful 1-line descriptor available per kind. Characters lead+// with role + a sliver of physicalDescription/personality; places use a slice+// of description; objects pull from significance or description. The goal is+// a quick orientation glance, not a substitute for the full canon block.+const summarizeCharacter = (c) => {+ const role = c.role ? `${c.role}` : '';+ const body = truncOneLine(c.physicalDescription || c.personality || c.description || c.background || '');+ if (role && body) return `${c.name} (${role} — ${body})`;+ if (role) return `${c.name} (${role})`;+ if (body) return `${c.name} (${body})`;+ return c.name;+};++const summarizePlace = (p) => {+ const label = p.name || p.slugline || '(unnamed)';+ const desc = truncOneLine(p.description || p.recurringDetails || '');+ return desc ? `${label} (${desc})` : label;+};++const summarizeObject = (o) => {+ const desc = truncOneLine(o.significance || o.description || '');+ return desc ? `${o.name} (${desc})` : o.name;+};++const SUMMARY_SECTIONS = [+ { field: 'characters', header: 'Characters', formatEntry: summarizeCharacter },+ { field: 'places', header: 'Places', formatEntry: summarizePlace },+ { field: 'objects', header: 'Objects', formatEntry: summarizeObject },+];++/**+ * Render a compact one-line-per-kind synopsis of the universe's named canon.+ *+ * Shape: each non-empty kind becomes `<Header>: name (descriptor); name; …`+ * joined with newlines. Top-N entries per kind (canon list order = LLM-+ * generated importance order). Returns an empty string when there is no+ * canon — callers gate against that for the `(none)` placeholder.+ *+ * Distinct from `renderCanonForPrompt`:+ * - canon block: multi-line, rich metadata per entry, intended for arc-+ * level prompts that benefit from the full bible.+ * - this summary: terse one-line tags meant for per-issue text stages+ * (prose/teleplay/comic-script) where the budget can't afford the full+ * dump but the LLM still needs continuity anchors.+ */+export function renderEntitiesSummary(world, { maxPerKind = ENTITIES_SUMMARY_MAX_PER_KIND } = {}) {+ if (!world || typeof world !== 'object') return '';+ const lines = [];+ for (const { field, header, formatEntry } of SUMMARY_SECTIONS) {+ const entries = Array.isArray(world[field]) ? world[field] : [];+ if (!entries.length) continue;+ const shown = entries.slice(0, maxPerKind);+ const hidden = entries.length - shown.length;+ const tags = shown.map(formatEntry).filter(Boolean);+ if (!tags.length) continue;+ const joined = tags.join('; ');+ lines.push(hidden > 0 ? `${header}: ${joined}; (+${hidden} more)` : `${header}: ${joined}`);+ }+ return lines.join('\n');+}diff --git a/server/lib/universePromptRenderers.test.js b/server/lib/universePromptRenderers.test.jsnew file mode 100644index 0000000000..3ec02f2c0e--- /dev/null+++ b/server/lib/universePromptRenderers.test.js@@ -0,0 +1,100 @@+import { describe, it, expect } from 'vitest';+import {+ renderEntitiesSummary,+ ENTITIES_SUMMARY_MAX_PER_KIND,+ ENTITIES_SUMMARY_DESCRIPTOR_MAX,+} from './universePromptRenderers.js';++describe('renderEntitiesSummary', () => {+ it('returns empty string for missing/invalid worlds', () => {+ expect(renderEntitiesSummary(null)).toBe('');+ expect(renderEntitiesSummary(undefined)).toBe('');+ expect(renderEntitiesSummary('not an object')).toBe('');+ expect(renderEntitiesSummary({})).toBe('');+ });++ it('renders one line per non-empty kind, joined with newlines', () => {+ const out = renderEntitiesSummary({+ characters: [{ name: 'Mira', role: 'surveyor', physicalDescription: 'short, broad-shouldered' }],+ places: [{ name: 'The Foundry', description: 'industrial district' }],+ objects: [{ name: 'Salt Crystal', significance: 'signal-decoder relic' }],+ });+ expect(out).toContain('Characters: Mira (surveyor — short, broad-shouldered)');+ expect(out).toContain('Places: The Foundry (industrial district)');+ expect(out).toContain('Objects: Salt Crystal (signal-decoder relic)');+ expect(out.split('\n')).toHaveLength(3);+ });++ it('omits kinds with zero entries', () => {+ const out = renderEntitiesSummary({+ characters: [{ name: 'Mira', role: 'surveyor' }],+ places: [],+ });+ expect(out).toContain('Characters: Mira (surveyor)');+ expect(out).not.toContain('Places');+ expect(out).not.toContain('Objects');+ });++ it('falls back from physicalDescription → personality → description → background', () => {+ const out = renderEntitiesSummary({+ characters: [+ { name: 'Only personality', personality: 'cunning and quiet' },+ { name: 'Only background', background: 'born in the foundry' },+ { name: 'Bare' },+ ],+ });+ expect(out).toContain('Only personality (cunning and quiet)');+ expect(out).toContain('Only background (born in the foundry)');+ expect(out).toContain('Bare');+ // Bare character with no descriptors shouldn't render parens+ expect(out).not.toContain('Bare ()');+ });++ it(`caps at ${ENTITIES_SUMMARY_MAX_PER_KIND} entries per kind with a (+N more) tag`, () => {+ const extra = Array.from({ length: ENTITIES_SUMMARY_MAX_PER_KIND + 3 }, (_, i) => ({+ name: `C${i + 1}`,+ role: 'role',+ }));+ const out = renderEntitiesSummary({ characters: extra });+ expect(out).toContain('C1 (role)');+ expect(out).toContain(`C${ENTITIES_SUMMARY_MAX_PER_KIND} (role)`);+ expect(out).not.toContain(`C${ENTITIES_SUMMARY_MAX_PER_KIND + 1}`);+ expect(out).toContain('(+3 more)');+ });++ it('honors a custom maxPerKind option', () => {+ const out = renderEntitiesSummary(+ { characters: [{ name: 'A' }, { name: 'B' }, { name: 'C' }] },+ { maxPerKind: 1 },+ );+ expect(out).toContain('A');+ expect(out).not.toContain('B');+ expect(out).toContain('(+2 more)');+ });++ it(`truncates over-long descriptors at ${ENTITIES_SUMMARY_DESCRIPTOR_MAX} chars with an ellipsis`, () => {+ const long = 'x'.repeat(ENTITIES_SUMMARY_DESCRIPTOR_MAX + 50);+ const out = renderEntitiesSummary({+ characters: [{ name: 'Mira', personality: long }],+ });+ // Descriptor body length stays bounded; trailing ellipsis present.+ const match = out.match(/Mira \(([^)]+)\)/);+ expect(match).toBeTruthy();+ expect(match[1].length).toBeLessThanOrEqual(ENTITIES_SUMMARY_DESCRIPTOR_MAX);+ expect(match[1]).toMatch(/…$/);+ });++ it('uses place slugline as label when name is absent', () => {+ const out = renderEntitiesSummary({+ places: [{ slugline: 'INT. FOUNDRY - NIGHT', description: 'the heart' }],+ });+ expect(out).toContain('INT. FOUNDRY - NIGHT (the heart)');+ });++ it('flattens multi-line descriptors to a single line', () => {+ const out = renderEntitiesSummary({+ characters: [{ name: 'Jonas', personality: 'fierce\n\nrelentless' }],+ });+ expect(out).toContain('Jonas (fierce relentless)');+ });+});diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.jsindex 66cfbb9943..84c7a60e88 100644--- a/server/services/pipeline/arcPlanner.js+++ b/server/services/pipeline/arcPlanner.js@@ -39,7 +39,7 @@ import { recommendStructure, describeStructure } from '../../lib/seasonStructureimport { LENGTH_PROFILE_NAMES, DEFAULT_LENGTH_PROFILE } from '../../lib/issueLength.js';import { getUniverse } from '../universeBuilder.js';import { getSeriesCanon } from './seriesCanon.js';-import { renderCategoriesForPrompt, renderCompositesForPrompt, renderCanonForPrompt } from '../../lib/universePromptRenderers.js';+import { renderCategoriesForPrompt, renderCompositesForPrompt, renderCanonForPrompt, renderEntitiesSummary } from '../../lib/universePromptRenderers.js';export const ERR_VALIDATION = 'PIPELINE_ARC_VALIDATION';const makeErr = (message, code) => Object.assign(new Error(message), { code });@@ -74,6 +74,12 @@ function renderPriorSeason(s, priorIssues) {return `${header}\n\nEpisode beats:\n${lines}`;}+// Shared placeholder for world-context fields when the series has no linked+// Universe Builder world. Exported so per-issue context builders+// (textStages.buildStageContext) render the same string instead of drifting+// to a near-duplicate phrasing.+export const NO_LINKED_UNIVERSE_PLACEHOLDER = '(none — series has no linked Universe Builder world)';+// The world is the canonical source for factions, characters, environments,// etc. — without this, the arc planner would only see the series' own// characters/places/objects which are usually empty pre-prose.@@ -104,6 +110,11 @@ async function loadWorldContext(universeId) {// name. Separate from categories because the LLM should treat these as// first-class entities, not exploratory variations.worldCanonText: renderCanonForPrompt(world) || '(none)',+ // Compact one-line-per-kind synopsis of canon — intended for text stages+ // (prose/teleplay/comic-script) where the full canon dump would dominate+ // the prompt. Arc-level prompts also receive it so a template author can+ // pick whichever level of detail fits the section being grounded.+ worldEntitiesSummary: renderEntitiesSummary(world) || '(none)',};}@@ -120,9 +131,10 @@ const EMPTY_WORLD_CONTEXT = {worldStyleNotes: '',worldInfluencesEmbrace: '(none)',worldInfluencesAvoid: '(none)',- worldCategoriesText: '(none — series has no linked Universe Builder world)',+ worldCategoriesText: NO_LINKED_UNIVERSE_PLACEHOLDER,worldCompositesText: '(none)',- worldCanonText: '(none — series has no linked Universe Builder world)',+ worldCanonText: NO_LINKED_UNIVERSE_PLACEHOLDER,+ worldEntitiesSummary: NO_LINKED_UNIVERSE_PLACEHOLDER,};// Resolve world context, accepting an optional preloaded value so callers@@ -981,6 +993,44 @@ export function mergeArcWithLocks(currentArc, nextArc, lockedFields) {return merged;}+// Preserve per-season locks. For every locked season in `currentSeasons`:+// - if the LLM proposed an entry with the same id, replace it with the+// existing locked record field-for-field (LLM's title/logline/etc. are+// discarded);+// - if the LLM dropped it entirely, re-insert it so it survives the resolve.+// Unlocked seasons (and brand-new entries the LLM minted) pass through. The+// caller still funnels the result through `sanitizeSeasonList`, which re-sorts+// by `number` ascending and dedups by id.+//+// Mirrors `mergeArcWithLocks`'s contract: locks are an *enforcement* gate, not+// a workflow signal — the arc-level `series.locked.arc` check up the stack+// remains the all-or-nothing block; this lets users freeze individual seasons+// while still letting auto-resolve rewrite the rest of the arc.+export function mergeSeasonsWithLocks(currentSeasons, nextSeasons) {+ if (!Array.isArray(nextSeasons)) return nextSeasons;+ if (!Array.isArray(currentSeasons)) return nextSeasons;+ const lockedById = new Map();+ for (const s of currentSeasons) {+ if (s?.locked === true && s.id) lockedById.set(s.id, s);+ }+ if (lockedById.size === 0) return nextSeasons;+ const seen = new Set();+ const merged = [];+ for (const next of nextSeasons) {+ const locked = next?.id ? lockedById.get(next.id) : null;+ if (locked) {+ merged.push(locked);+ seen.add(locked.id);+ } else {+ merged.push(next);+ }+ }+ for (const [id, locked] of lockedById) {+ if (!seen.has(id)) merged.push(locked);+ }+ return merged;+}+/*** Persist a new `arc` + `seasons[]` onto a series, migrating any child issues* whose `seasonId` referenced a season that the new shape dropped or renamed.@@ -1010,10 +1060,16 @@ export async function commitSeasonsWithRemap(currentSeries, { arc, seasons }) {);}const mergedArc = mergeArcWithLocks(latestSeries.arc, arc, latestSeries.locked?.arcFields);- const newIds = new Set((seasons || []).map((s) => s.id));+ // Per-season locks: restore any locked existing seasons over LLM-proposed+ // rewrites, and re-insert any locked seasons the LLM dropped. Re-sanitize+ // so the locked records merge with the new shape (sort by number, dedup).+ const mergedSeasons = sanitizeSeasonList(+ mergeSeasonsWithLocks(latestSeries.seasons, seasons),+ );+ const newIds = new Set(mergedSeasons.map((s) => s.id));const droppedOldSeasons = (latestSeries.seasons || []).filter((s) => !newIds.has(s.id));const oldIds = new Set((latestSeries.seasons || []).map((s) => s.id));- const newlyMintedSeasons = (seasons || []).filter((s) => !oldIds.has(s.id));+ const newlyMintedSeasons = mergedSeasons.filter((s) => !oldIds.has(s.id));const remap = buildSeasonRemap(droppedOldSeasons, newlyMintedSeasons);const droppedIdSet = new Set(droppedOldSeasons.map((s) => s.id));const reassignList = droppedIdSet.size@@ -1032,7 +1088,7 @@ export async function commitSeasonsWithRemap(currentSeries, { arc, seasons }) {// the exact orphan state this helper was written to prevent.let updated;await withReexportSuppressed('series', seriesId, async () => {- updated = await updateSeries(seriesId, { arc: mergedArc, seasons });+ updated = await updateSeries(seriesId, { arc: mergedArc, seasons: mergedSeasons });for (const iss of reassignList) {const target = remap.get(iss.seasonId) ?? null;await updateIssue(iss.id, { seasonId: target }, { skipRenumber: true });@@ -1118,4 +1174,5 @@ export const __testing = {renderVolumeIssue,buildNeighborVolumes,mergeArcWithLocks,+ mergeSeasonsWithLocks,};diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.jsindex cf832e45ef..f2a9d1614c 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -856,6 +856,125 @@ describe('arcPlanner — commitSeasonsWithRemap', () => {});});+describe('arcPlanner — mergeSeasonsWithLocks', () => {+ it('replaces an LLM-proposed season with the existing locked record when ids match', () => {+ const current = [+ { id: 'sea-a', number: 1, title: 'Locked Title', logline: 'locked log', locked: true },+ { id: 'sea-b', number: 2, title: 'Unlocked', logline: 'old log', locked: false },+ ];+ const next = [+ { id: 'sea-a', number: 1, title: 'LLM rewrite', logline: 'LLM log' },+ { id: 'sea-b', number: 2, title: 'Unlocked rewritten', logline: 'new log' },+ ];+ const merged = planner.__testing.mergeSeasonsWithLocks(current, next);+ expect(merged[0]).toBe(current[0]);+ expect(merged[0].title).toBe('Locked Title');+ expect(merged[1].title).toBe('Unlocked rewritten');+ });++ it('re-inserts a locked season that the LLM dropped from the new shape', () => {+ const current = [+ { id: 'sea-a', number: 1, title: 'Drop me', locked: true },+ { id: 'sea-b', number: 2, title: 'Keep me', locked: false },+ ];+ const next = [+ { id: 'sea-b', number: 2, title: 'Keep me' },+ ];+ const merged = planner.__testing.mergeSeasonsWithLocks(current, next);+ expect(merged).toHaveLength(2);+ expect(merged.find((s) => s.id === 'sea-a')).toBe(current[0]);+ });++ it('returns next unchanged when no current season is locked', () => {+ const current = [{ id: 'sea-a', number: 1, locked: false }];+ const next = [{ id: 'sea-a', number: 1, title: 'rewrite' }];+ expect(planner.__testing.mergeSeasonsWithLocks(current, next)).toBe(next);+ });++ it('returns next unchanged when currentSeasons is not an array', () => {+ const next = [{ id: 'sea-a', number: 1 }];+ expect(planner.__testing.mergeSeasonsWithLocks(undefined, next)).toBe(next);+ expect(planner.__testing.mergeSeasonsWithLocks(null, next)).toBe(next);+ });++ it('returns nextSeasons untouched when nextSeasons is not an array', () => {+ expect(planner.__testing.mergeSeasonsWithLocks([{ id: 'a', locked: true }], null)).toBeNull();+ expect(planner.__testing.mergeSeasonsWithLocks([{ id: 'a', locked: true }], undefined)).toBeUndefined();+ });+});++describe('arcPlanner — commitSeasonsWithRemap (season locks)', () => {+ beforeEach(() => {+ fileStore.clear();+ uuidCounter = 0;+ stageRunnerSpy = undefined;+ });++ it('preserves a locked season verbatim when the LLM tries to rewrite its content', async () => {+ const s = await setupSeries();+ const s1 = await seasonsSvc.createSeason(s.id, {+ title: 'Locked Title',+ logline: 'locked logline',+ synopsis: 'locked synopsis',+ episodeCountTarget: 3,+ number: 1,+ });+ await seasonsSvc.updateSeason(s.id, s1.id, { locked: true });+ const cur = await seriesSvc.getSeries(s.id);+ const out = await planner.commitSeasonsWithRemap(cur, {+ arc: { logline: 'L', summary: '', themes: [], protagonistArc: '', shape: null, status: 'draft' },+ seasons: [+ // LLM tries to rewrite the locked season's content under the same id.+ { id: s1.id, number: 1, title: 'LLM rewrite', logline: 'LLM logline', synopsis: 'LLM synopsis', endingHook: '', episodeCountTarget: 9, themes: [] },+ ],+ });+ const persisted = out.series.seasons.find((x) => x.id === s1.id);+ expect(persisted.title).toBe('Locked Title');+ expect(persisted.logline).toBe('locked logline');+ expect(persisted.synopsis).toBe('locked synopsis');+ expect(persisted.episodeCountTarget).toBe(3);+ expect(persisted.locked).toBe(true);+ });++ it('re-inserts a locked season the LLM dropped, with no issue reassignment', async () => {+ const s = await setupSeries();+ const s1 = await seasonsSvc.createSeason(s.id, { title: 'Locked', episodeCountTarget: 3, number: 1 });+ await seasonsSvc.updateSeason(s.id, s1.id, { locked: true });+ const i1 = await issuesSvc.createIssue({ seriesId: s.id, seasonId: s1.id, title: 'Pilot' });+ const cur = await seriesSvc.getSeries(s.id);+ const out = await planner.commitSeasonsWithRemap(cur, {+ arc: { logline: 'L', summary: '', themes: [], protagonistArc: '', shape: null, status: 'draft' },+ // LLM proposed dropping the locked season entirely.+ seasons: [],+ });+ expect(out.series.seasons.map((x) => x.id)).toContain(s1.id);+ expect(out.reassignedIssueCount).toBe(0);+ const finalI1 = await issuesSvc.getIssue(i1.id);+ expect(finalI1.seasonId).toBe(s1.id);+ });++ it('still rewrites unlocked sibling seasons while preserving the locked one', async () => {+ const s = await setupSeries();+ const locked = await seasonsSvc.createSeason(s.id, { title: 'Frozen', episodeCountTarget: 4, number: 1 });+ await seasonsSvc.updateSeason(s.id, locked.id, { locked: true });+ const unlocked = await seasonsSvc.createSeason(s.id, { title: 'Editable', episodeCountTarget: 4, number: 2 });+ const cur = await seriesSvc.getSeries(s.id);+ const out = await planner.commitSeasonsWithRemap(cur, {+ arc: { logline: 'L', summary: '', themes: [], protagonistArc: '', shape: null, status: 'draft' },+ seasons: [+ { id: locked.id, number: 1, title: 'LLM rewrite of frozen', logline: '', synopsis: '', endingHook: '', episodeCountTarget: 1, themes: [] },+ { id: unlocked.id, number: 2, title: 'Editable v2', logline: 'updated', synopsis: '', endingHook: '', episodeCountTarget: 5, themes: [] },+ ],+ });+ const frozenAfter = out.series.seasons.find((x) => x.id === locked.id);+ const editableAfter = out.series.seasons.find((x) => x.id === unlocked.id);+ expect(frozenAfter.title).toBe('Frozen');+ expect(frozenAfter.locked).toBe(true);+ expect(editableAfter.title).toBe('Editable v2');+ expect(editableAfter.episodeCountTarget).toBe(5);+ });+});+describe('arcPlanner — mergeArcWithLocks', () => {it('replaces locked fields with the current arc values', () => {const current = { logline: 'a', summary: 'b', themes: ['t1'], protagonistArc: 'c', shape: 's1' };diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.jsindex cd2a228b60..1a1cd6646e 100644--- a/server/services/pipeline/textStages.js+++ b/server/services/pipeline/textStages.js@@ -19,8 +19,10 @@ import { getSeries } from './series.js';import { extractCanonFromProse } from '../universeCanon.js';import { getIssue, listIssues, updateStage, assertStageUnlocked, TEXT_STAGE_IDS } from './issues.js';import { getSeriesCanon } from './seriesCanon.js';-import { compareIssuesByPosition } from './arcPlanner.js';+import { getUniverse } from '../universeBuilder.js';+import { compareIssuesByPosition, NO_LINKED_UNIVERSE_PLACEHOLDER } from './arcPlanner.js';import { computeIssueTargets } from '../../lib/issueLength.js';+import { renderEntitiesSummary } from '../../lib/universePromptRenderers.js';const STAGE_TO_TEMPLATE = Object.freeze({idea: 'pipeline-idea-expansion',@@ -134,7 +136,7 @@ async function buildIdeaContextAugment(series, issue) {* bible (`series.*`) and every *prior* text stage's content (`stages.*`).* Visual stages aren't included — text templates don't need rendered images.*/-function buildStageContext({ series, canon, issue, stageId, seedInput }) {+function buildStageContext({ series, canon, world, issue, stageId, seedInput }) {const stages = {};for (const id of TEXT_STAGE_IDS) {if (id === stageId) break; // only include stages BEFORE the current one@@ -146,6 +148,14 @@ function buildStageContext({ series, canon, issue, stageId, seedInput }) {content: (cur.input?.trim() || cur.output?.trim() || ''),};}+ // Compact one-line-per-kind synopsis of the linked universe's canon. Lets+ // per-issue text prompts reference named entities without paying the full+ // canon-block token cost — `series.characters` already covers the bible-+ // sized character context, this adds places/objects + other characters not+ // pulled into the series-canon for continuity anchors.+ const worldEntitiesSummary = world+ ? (renderEntitiesSummary(world) || '(none)')+ : NO_LINKED_UNIVERSE_PLACEHOLDER;return {series: {name: series.name,@@ -159,6 +169,7 @@ function buildStageContext({ series, canon, issue, stageId, seedInput }) {number: issue.number,title: issue.title,},+ worldEntitiesSummary,// Fed into every text template via {{lengthTargets.*}}. Always populated// (defaults to 'standard') so templates can use the fields unconditionally.lengthTargets: computeIssueTargets(issue),@@ -186,7 +197,13 @@ export async function generateStage(issueId, stageId, options = {}) {const template = STAGE_TO_TEMPLATE[stageId];const issue = await getIssue(issueId);const series = await getSeries(issue.seriesId);- const canon = await getSeriesCanon(series);+ // Universe canon is best-effort — an orphaned series (no universeId) or a+ // missing universe record just skips the entities summary instead of+ // failing the run.+ const [canon, world] = await Promise.all([+ getSeriesCanon(series),+ series.universeId ? getUniverse(series.universeId).catch(() => null) : Promise.resolve(null),+ ]);// Per-stage editorial lock — refuse before touching the stage record so a// locked stage doesn't get bumped to 'generating' status only to be reset.@@ -196,7 +213,7 @@ export async function generateStage(issueId, stageId, options = {}) {await updateStage(issueId, stageId, { status: 'generating', errorMessage: '' });- const ctx = buildStageContext({ series, canon, issue, stageId, seedInput: options.seedInput });+ const ctx = buildStageContext({ series, canon, world, issue, stageId, seedInput: options.seedInput });if (stageId === 'idea') {Object.assign(ctx, await buildIdeaContextAugment(series, issue));}diff --git a/server/services/pipeline/textStages.test.js b/server/services/pipeline/textStages.test.jsindex 082232ecc8..59984495ce 100644--- a/server/services/pipeline/textStages.test.js+++ b/server/services/pipeline/textStages.test.js@@ -55,6 +55,7 @@ vi.mock('../promptService.js', () => ({const issuesSvc = await import('./issues.js');const seriesSvc = await import('./series.js');const seasonsSvc = await import('./seasons.js');+const universeSvc = await import('../universeBuilder.js');const textStages = await import('./textStages.js');// Strip the `RENDERED:<stage>:` prefix that the mocked buildPrompt prepends@@ -136,6 +137,31 @@ describe('pipeline text stage generator', () => {expect(after.stages.idea.locked).toBe(true);});+ it('prompt context carries worldEntitiesSummary fallback when series has no universe link', async () => {+ const { issue } = await seed();+ await textStages.generateStage(issue.id, 'idea');+ const ctx = ctxFromCall(llmCalls[0]);+ expect(ctx.worldEntitiesSummary).toBe('(none — series has no linked Universe Builder world)');+ });++ it('prompt context carries a rendered worldEntitiesSummary when series links a universe', async () => {+ const { series, issue } = await seed();+ const world = await universeSvc.createUniverse({ name: 'Salt Verse' });+ await universeSvc.updateUniverse(world.id, {+ characters: [+ { name: 'Mira', role: 'surveyor', physicalDescription: 'broad-shouldered' },+ { name: 'Jonas', role: 'foreman', personality: 'cunning' },+ ],+ places: [{ name: 'The Foundry', description: 'industrial district' }],+ });+ await seriesSvc.updateSeries(series.id, { universeId: world.id });+ await textStages.generateStage(issue.id, 'idea');+ const ctx = ctxFromCall(llmCalls[0]);+ expect(ctx.worldEntitiesSummary).toContain('Mira (surveyor — broad-shouldered)');+ expect(ctx.worldEntitiesSummary).toContain('Jonas (foreman — cunning)');+ expect(ctx.worldEntitiesSummary).toContain('The Foundry (industrial district)');+ });+it('prompt context carries lengthTargets from a named non-default profile (extended)', async () => {const { series } = await seed();// Create an issue with the 'extended' profile — distinct from 'standard' sodiff --git a/server/services/universeCharacterExpand.js b/server/services/universeCharacterExpand.jsindex 3a29d6e905..d781265e96 100644--- a/server/services/universeCharacterExpand.js+++ b/server/services/universeCharacterExpand.js@@ -21,7 +21,7 @@ import { shortId } from '../lib/fileUtils.js';// Adding a new extended field on `sanitizeCharacter` requires adding it here// too — otherwise the expand response key is silently dropped.const STRING_FIELDS = Object.freeze([- 'pronouns', 'age', 'coreTheme', 'speechAccent', 'visualNotes',+ 'pronouns', 'age', 'coreTheme', 'speechAccent', 'speechPattern', 'visualNotes','silhouetteNotes', 'postureNotes', 'specialTraits', 'visualIdentity','motivations', 'likes', 'dislikes', 'mannerisms', 'relationships', 'skills',]);diff --git a/server/services/universeCharacterExpand.test.js b/server/services/universeCharacterExpand.test.jsindex 5a1d8acbf8..55022099f9 100644--- a/server/services/universeCharacterExpand.test.js+++ b/server/services/universeCharacterExpand.test.js@@ -89,13 +89,13 @@ describe('universeCharacterExpand — applyExpansion (no-clobber merge semanticsit('respects the full extended-field set (smoke check the field list stays in sync)', () => {const target = {- name: 'Vale', pronouns: '', age: '', coreTheme: '', speechAccent: '', visualNotes: '',+ name: 'Vale', pronouns: '', age: '', coreTheme: '', speechAccent: '', speechPattern: '', visualNotes: '',silhouetteNotes: '', postureNotes: '', specialTraits: '', visualIdentity: '',motivations: '', likes: '', dislikes: '', mannerisms: '', relationships: '', skills: '',stats: [], colorPalette: [], props: [], expressions: [], handGestures: [],};const content = {- pronouns: 'she/her', age: '27', coreTheme: 't', speechAccent: 'a', visualNotes: 'v',+ pronouns: 'she/her', age: '27', coreTheme: 't', speechAccent: 'a', speechPattern: 'sp', visualNotes: 'v',silhouetteNotes: 's', postureNotes: 'p', specialTraits: 'st', visualIdentity: 'vi',motivations: 'm', likes: 'l', dislikes: 'd', mannerisms: 'mn', relationships: 'r', skills: 'sk',stats: [{ label: 'L', value: 'V' }],@@ -105,8 +105,9 @@ describe('universeCharacterExpand — applyExpansion (no-clobber merge semanticshandGestures: [{ name: 'n' }],};const { updatedFields } = applyExpansion(target, content);- // 15 strings + 5 lists = 20 fields total in the expand contract.- expect(updatedFields).toHaveLength(20);+ // 16 strings + 5 lists = 21 fields total in the expand contract.+ expect(updatedFields).toHaveLength(21);+ expect(updatedFields).toContain('speechPattern');});it('REGRESSION: list proposals whose rows all fail bible sanitization are NOT marked as updated', () => {diff --git a/server/services/universeCharacterSheet.js b/server/services/universeCharacterSheet.jsindex 4d6ec32056..720aced2ce 100644--- a/server/services/universeCharacterSheet.js+++ b/server/services/universeCharacterSheet.js@@ -89,6 +89,7 @@ export function buildCharacterReferenceSheetPrompt(universe, character) {const age = trim(character.age);const personality = trim(character.personality);const speechAccent = trim(character.speechAccent);+ const speechPattern = trim(character.speechPattern);const coreTheme = trim(character.coreTheme);const visualNotes = trim(character.visualNotes);@@ -99,7 +100,8 @@ export function buildCharacterReferenceSheetPrompt(universe, character) {pronouns ? `Pronouns: ${pronouns}.` : '',role ? `Role: ${role}.` : '',personality ? `Personality: ${personality}.` : '',- speechAccent ? `Speech: ${speechAccent}.` : '',+ speechAccent ? `Accent: ${speechAccent}.` : '',+ speechPattern ? `Speech pattern: ${speechPattern}.` : '',coreTheme ? `Core theme: ${coreTheme}.` : '',visualNotes ? `Visual notes: ${visualNotes}.` : '',].filter(Boolean).join(' ');