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): Vonnegut story shape drives arc, verify, episode pacing
[._.]/ Adam Eivyd4002a3972d5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 4c5cb03dcb..a519cfd1fa 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,48 @@## Added+- **Story shape is now load-bearing across arc planning.** The Vonnegut+ shape picker on the series arc was previously decorative — picked, rendered+ as a sparkline, then ignored by every LLM prompt. Now the picked shape (or+ the LLM's proposed shape when the user hasn't picked one) flows into all+ five arc-planning passes as `{{{shapeGuidance}}}` (rendered curve ++ per-shape beat guidance) plus per-volume `{{shapePosition}}` /+ `{{volumeShapePosition}}` (where this season/volume sits on the curve so+ episode pacing and volume-internal beats follow the right trajectory):+ - `pipeline-arc-overview` — honor-or-propose mode. With a pre-pick the LLM+ must trace the curve and round-trip `shape` in the JSON. Without a pick+ the LLM proposes one from the 8 ids and returns it in the JSON.+ - `pipeline-season-episodes` — episode beats ramp / fall / plateau the+ direction the season's curve placement demands, not just by `arcRole`.+ - `pipeline-arc-verify` — new "story-shape adherence" check (rule 7/8)+ flags volumes whose ending hook contradicts the curve.+ - `pipeline-volume-verify` — new volume-internal adherence check + per-+ volume curve placement context.+ - `pipeline-arc-resolve` — preserves picked shape during auto-resolve.++ **Files:** new `ARC_SHAPES` catalog + `getArcShape` / `renderArcShapeGuidance`+ / `describeArcShapePositionForSeason` in `server/lib/storyArc.js` (points+ arrays kept in sync with the client `STORY_SHAPES` via a parity test);+ `buildArcBaseContext` / `buildArcOverviewContext` / `buildSeasonEpisodesContext`+ / `buildVolumeVerifyContext` in `server/services/pipeline/arcPlanner.js`+ thread shape into prompt contexts; both `data.sample/` and `data/`+ copies of the five prompts updated (resolve added to `data.sample/` for+ the first time — it previously only existed in `data/`); migration+ `005-shape-aware-arc-prompts.js` auto-applies the new templates when the+ installed copy still matches the pre-change shipped hash, skips with a+ manual-merge warning when customized; drift-warning hashes in+ `scripts/setup-data.js` extended to include the new lineage. 16 new tests+ (3 in `storyArc.test.js`, 5 in `arcPlanner.test.js`) lock the catalog+ shape, the position helper edge cases, both overview modes, and the+ season-episodes + volume-verify shape-context wiring.++- **`generateArcOverview` preserves an existing `arc.shape` on regenerate.**+ Sibling `resolveVerifyIssues` already had the right preservation pattern+ (`shape: content?.arc?.shape ?? series.arc.shape ?? null`); the regenerate+ path missed it, so every "Regenerate arc" click wiped a Vonnegut shape+ the user (or the LLM) had picked. **Files:** `server/services/pipeline/arcPlanner.js`+ + regression test in `arcPlanner.test.js`.+- **Beat-sheet expansion — arc / volume / neighbor-issue context block.**The `idea` text stage previously generated each issue's beats in isolationagainst the series bible + the user's seed. It now sees the whole frame adiff --git a/data.sample/prompts/stages/pipeline-arc-overview.md b/data.sample/prompts/stages/pipeline-arc-overview.mdindex 8817915c61..5de9f114c8 100644--- a/data.sample/prompts/stages/pipeline-arc-overview.md+++ b/data.sample/prompts/stages/pipeline-arc-overview.md@@ -1,9 +1,20 @@# Pipeline — Series Arc Overview-You are a senior story editor sketching the **top-level multi-season story spine** for a new series. The user has a series bible (name, logline, premise, characters, target format, target issue count) but no decided arc shape — you propose one. The output gets persisted as `series.arc` + `series.seasons[]` and feeds every downstream per-season + per-episode prompt.+You are a senior story editor sketching the **top-level multi-season story spine** for a new series. The user has a series bible (name, logline, premise, characters, target format, target issue count). The output gets persisted as `series.arc` + `series.seasons[]` and feeds every downstream per-season + per-episode prompt.This is the most expensive single call in the pipeline (you reason over the full series scope) so be deliberate.+## Story shape (Vonnegut)++{{{shapeGuidance}}}++{{#pickedShapeId}}+The user has pre-picked this shape. Your `seasonOutlines` MUST trace this fortune curve — each volume's logline and endingHook should reflect its position on the curve (low → rising → peak → falling → recovery → triumph, etc., per the shape's beats). Include `"shape": "{{pickedShapeId}}"` verbatim in your JSON output so the picked shape round-trips.+{{/pickedShapeId}}+{{^pickedShapeId}}+No shape pre-picked. Choose the single Vonnegut shape that best matches the premise's emotional trajectory (allowed: {{allowedShapeIdsCsv}}). Your `seasonOutlines` MUST trace the chosen curve. Return your pick as `"shape": "..."` in the JSON output — exactly one of the allowed ids.+{{/pickedShapeId}}+## Series bible- **Name:** {{series.name}}@@ -48,6 +59,7 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c"summary": "string (~500 words, multi-paragraph plain text — escape newlines as \\n)","themes": ["string", "..."],"protagonistArc": "string (character growth across all seasons)",+ "shape": "one of: rags-to-riches | tragedy | man-in-hole | icarus | cinderella | oedipus | boy-meets-girl | creation-story","seasonOutlines": [{"number": 1,diff --git a/data.sample/prompts/stages/pipeline-arc-resolve.md b/data.sample/prompts/stages/pipeline-arc-resolve.mdnew file mode 100644index 0000000000..58e01aaa52--- /dev/null+++ b/data.sample/prompts/stages/pipeline-arc-resolve.md@@ -0,0 +1,113 @@+# Pipeline — Arc Verification Auto-Resolve++You are a senior story editor cleaning up a planned series so it passes verification. The user ran a continuity pass against their arc + volumes/seasons and got back a list of structural findings. Your job is to rewrite the arc + volume outlines so every finding is resolved, while preserving as much of the user's original work as possible.++Every series is published as both a graphic novel (issues → volumes) AND a TV series (episodes → seasons). One issue == one episode; one volume == one season. Your edits must work for both.++## Series bible++- **Name:** {{series.name}}+- **Logline:** {{series.logline}}+- **Premise:**++```+{{series.premise}}+```++## Linked World — canonical entities++The arc is grounded in this World Builder world: **{{worldName}}**. When you rewrite synopses, ground them in these entities by name. If a finding flagged "world entity drift", swap the made-up entity for the closest match below.++### World entity categories++```+{{worldCategoriesText}}+```++### World composite reference sheets++```+{{worldCompositesText}}+```++{{> bible-deference }}++## Current arc++- **Whole-series logline:** {{arc.logline}}+- **Themes:** {{arc.themesCsv}}+- **Protagonist arc:**++```+{{arc.protagonistArc}}+```++- **Arc summary:**++```+{{arc.summary}}+```++## Story shape (Vonnegut)++{{{shapeGuidance}}}++When rewriting the arc + volume synopses, preserve the picked shape — do not change `arc.shape`. The volume-level fortune trajectory must still trace this curve after your edits.++## Current volumes + issues++```json+{{seasonsTreeJson}}+```++## Structural recommendation++The recommended structure for this issue budget is **{{recommendedStructure}}** ({{recommendedSeasonCount}} volumes, per-volume counts {{recommendedPerSeasonJson}}). Comic-as-TV industry norm is 6–10 issues per volume; deviate from this only if a finding explicitly demands it.++## Findings to resolve++The verification pass flagged these problems. Resolve **every** one of them in your output:++```json+{{findingsJson}}+```++## How to resolve++1. **Read each finding's `problem` + `suggestion`.** The suggestion is a hint, not gospel — feel free to take a different path if it cleans up the arc better, but the resulting arc MUST make the finding go away.+2. **Volume-count-vs-weight mismatches** (the most common finding) — usually the right fix is to **trim or expand a volume's `synopsis`** so it matches its `episodeCountTarget`, OR adjust `episodeCountTarget` toward the structural recommendation. Don't split a volume into two unless the structural recommendation calls for more volumes than currently exist.+3. **Character contradictions** — adjust the offending volume's `synopsis` (or the protagonist arc) so the contradiction disappears. Do not silently delete the contradicting beat — replace it with one that preserves the dramatic intent.+4. **Dropped subplots** — add the missing payoff to a later volume's `synopsis` or `endingHook`, OR remove the dangling setup from the earlier volume if the payoff would derail the arc.+5. **Unresolved finale hooks / theme drift** — surface the missing theme or arc payoff in the final volume's `synopsis`.+6. **Preserve volume `id`** for every existing volume you keep. Only assign no `id` to brand-new volumes you are adding. If you remove a volume, simply omit it from the response — the server will reconcile child issues separately.+7. **Do NOT edit per-episode (issue) records.** Those are the user's hand-authored scripts. If a finding only resolves by deleting issues, write that in the `notes` field instead of doing it.++## Output contract++Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:++```json+{+ "arc": {+ "logline": "string",+ "summary": "string (~500 words, multi-paragraph; escape newlines as \\n)",+ "themes": ["string", "..."],+ "protagonistArc": "string"+ },+ "seasons": [+ {+ "id": "sea-... (omit only for brand-new volumes)",+ "number": 1,+ "title": "string",+ "logline": "string",+ "synopsis": "string",+ "endingHook": "string",+ "episodeCountTarget": 8,+ "themes": ["string"]+ }+ ],+ "notes": "string (optional — flag any finding you could only partially resolve, and explain why. Empty string if every finding is fully addressed.)"+}+```++The `seasons[]` array must be the FULL list of volumes you want the series to have after the resolve — not a delta. Any current volume not in the response is treated as removed.diff --git a/data.sample/prompts/stages/pipeline-arc-verify.md b/data.sample/prompts/stages/pipeline-arc-verify.mdindex e67c77ce10..aea8ffff6f 100644--- a/data.sample/prompts/stages/pipeline-arc-verify.md+++ b/data.sample/prompts/stages/pipeline-arc-verify.md@@ -31,6 +31,10 @@ You are a continuity editor doing a cross-season pass on a planned series. The u{{arc.summary}}```+## Story shape (Vonnegut)++{{{shapeGuidance}}}+## Seasons + episodes```json@@ -47,6 +51,7 @@ Walk the seasons in order. Score each season + each episode against the arc. Spe4. **Unresolved hooks at the series finale.** The final season ends without paying off the whole-arc logline, protagonist arc, or any of the major themes.5. **Arc-role imbalance.** A season with 8 episodes and zero `pilot` / `finale` `arcRole` entries (or two `pilot`s / two `finale`s).6. **Theme drift.** A theme is named in `arc.themes` but doesn't appear in any season synopsis or episode logline.+7. **Story-shape adherence.** If a Vonnegut shape was selected (see "Story shape" above — skip this check if none was selected), verify the season-level fortune trajectory traces that curve. Flag volumes whose `endingHook` lands at a fortune level that contradicts the curve (e.g. a "rags-to-riches" volume ending lower than it opened, a "tragedy" volume ending in unambiguous triumph, an "icarus" arc whose crash never comes). The whole-series finale must land at the shape's terminal level.## Output contractdiff --git a/data.sample/prompts/stages/pipeline-season-episodes.md b/data.sample/prompts/stages/pipeline-season-episodes.mdindex fb48729260..b946b100c5 100644--- a/data.sample/prompts/stages/pipeline-season-episodes.md+++ b/data.sample/prompts/stages/pipeline-season-episodes.md@@ -25,6 +25,14 @@ You are a writers-room showrunner planning the **episode-by-episode breakdown fo- **Themes:** {{arc.themesCsv}}+## Story shape (Vonnegut) — this season's curve placement++{{{shapeGuidance}}}++**This season's expected emotional placement:** {{shapePosition}}++Pace the episodes you write so the season's fortune trajectory matches this placement. The first episode should open near the *level* implied by the prior season's ending, the finale episode should land at the *level* implied by this season's ending hook, and the in-between beats should bend the curve in the right direction — even when the per-episode `arcRole` would otherwise read as neutral.+{{> bible-deference }}## Prior seasons (continuity — do not contradict)diff --git a/data.sample/prompts/stages/pipeline-volume-verify.md b/data.sample/prompts/stages/pipeline-volume-verify.mdindex 3aa6380c03..22e4e1cb26 100644--- a/data.sample/prompts/stages/pipeline-volume-verify.md+++ b/data.sample/prompts/stages/pipeline-volume-verify.md@@ -48,6 +48,12 @@ The arc was authored against this World Builder world: **{{worldName}}**. Contin{{arc.summary}}```+## Story shape (Vonnegut) — full arc + this volume's placement++{{{shapeGuidance}}}++**This volume's expected emotional placement within the curve:** {{volumeShapePosition}}+## This volume- **Volume / Season number:** {{volume.number}}@@ -88,6 +94,7 @@ Walk the volume in issue / episode order. Score each issue against the volume's6. **Cast economy.** A character introduced in this volume that gets exactly one beat and is never seen again. Or a major character from the bible / world that the volume's issues never use despite a thematic fit.7. **World entity drift (volume scope).** This volume's issues name factions / characters / locations that don't exist in the linked world (suggest renaming to a real entity).8. **Length-vs-weight mismatch.** Issue count target says 8 but the synopsis is summarizable in 3 beats, or vice versa. (Cross-volume pass already checks the whole arc — only flag here when it's obvious from this volume in isolation.)+9. **Volume-internal shape adherence.** If a Vonnegut shape was selected (see "Story shape" above — skip this check if none was selected), this volume's beats must trace the segment of the curve described under "This volume's expected emotional placement." Flag a volume whose final issue lands at a fortune level that contradicts the curve placement (e.g. a "rags-to-riches" volume 2 of 3 ending lower than it opened, or a "man-in-hole" midpoint volume that never reaches the nadir).DO NOT flag problems that are properly cross-volume in nature (a character introduced in volume 1 paying off in volume 4 — that's the arc verify's job, not yours). Stay inside this volume's walls; the only outside-the-walls checks allowed are #5 (boundary continuity with the immediate neighbors shown above).diff --git a/data/migrations/005-shape-aware-arc-prompts.js b/data/migrations/005-shape-aware-arc-prompts.jsnew file mode 100644index 0000000000..c6ba7428dd--- /dev/null+++ b/data/migrations/005-shape-aware-arc-prompts.js@@ -0,0 +1,122 @@+/**+ * Make the pipeline arc + season + verify + resolve prompts Vonnegut-shape+ * aware. Adds `{{{shapeGuidance}}}` (the rendered curve + per-position+ * guidance) and, where applicable, `{{shapePosition}}` / `{{volumeShapePosition}}`+ * (the per-volume placement on the picked curve) to:+ *+ * pipeline-arc-overview — propose-or-honor block + `shape` in JSON output+ * pipeline-season-episodes — per-season curve placement, episode pacing rule+ * pipeline-arc-verify — new "story-shape adherence" check+ * pipeline-volume-verify — per-volume placement + volume-internal adherence check+ * pipeline-arc-resolve — preserve picked shape during auto-resolve+ *+ * Strategy mirrors migration 003: replace the installed file only when its+ * hash still matches the previous shipped version. Customized files are+ * skipped with a manual-merge warning.+ *+ * `pipeline-arc-resolve.md` was never previously in data.sample/ (it shipped+ * in `27ef3c27` but only landed in `data/`). The OLD hash here is the+ * stable content of that pre-sample-installed copy; users who never received+ * it will get the new file copied in by setup-data.js on the next run.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { createHash } from 'crypto';++const md5 = (str) => {+ const normalized = str.replace(/\r\n/g, '\n').replace(/\r/g, '\n');+ return createHash('md5').update(normalized).digest('hex');+};++const OLD_SHIPPED_MD5 = {+ 'pipeline-arc-overview.md': '6a3ecab43d1f46b7ef9aab6c69ea0326',+ 'pipeline-arc-verify.md': '52e31abc93e3105176236fcaa5d1575a',+ 'pipeline-volume-verify.md': 'c6ea28e972ad6e229bafb2d602b4dda3',+ 'pipeline-season-episodes.md': 'c4928e2a5f833358116b29d2d669888d',+ 'pipeline-arc-resolve.md': '87bc5c01f1a8a97b681727a38b05edc6',+};++const NEW_SHIPPED_MD5 = {+ 'pipeline-arc-overview.md': 'd34d72b8e49ba303d38607845dd87f1c',+ 'pipeline-arc-verify.md': 'ff56d8387162017e08d5d0491060ddd6',+ 'pipeline-volume-verify.md': '03f3c874cb80e1c98abcf03168fa7a92',+ 'pipeline-season-episodes.md': '50c68a29c3ebc275db3095d06bd87100',+ 'pipeline-arc-resolve.md': 'a8677bbe1eb38f871fb152a5b0fec7c6',+};++export default {+ async up({ rootDir }) {+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');+ const sampleDir = join(rootDir, 'data.sample', 'prompts', 'stages');++ let updated = 0;+ let alreadyCurrent = 0;+ let skipped = 0;+ let created = 0;++ for (const filename of Object.keys(OLD_SHIPPED_MD5)) {+ const dataPath = join(stagesDir, filename);+ const samplePath = join(sampleDir, filename);++ const existing = await readFile(dataPath, 'utf-8').catch((err) => {+ if (err.code !== 'ENOENT') throw err;+ return null;+ });++ if (existing === null) {+ // File missing from data/ — copy from sample so the shape-aware+ // prompt is in place on next server boot. setup-data.js would do this+ // too on its next pass, but running it here keeps the migration+ // self-contained for the case where it executes before setup-data.+ const sampleContent = await readFile(samplePath, 'utf-8').catch(() => null);+ if (sampleContent != null) {+ await writeFile(dataPath, sampleContent);+ console.log(`📄 created shape-aware prompt: ${filename}`);+ created++;+ }+ continue;+ }++ const existingMd5 = md5(existing);++ if (existingMd5 === NEW_SHIPPED_MD5[filename]) {+ alreadyCurrent++;+ continue;+ }++ if (existingMd5 !== OLD_SHIPPED_MD5[filename]) {+ console.warn(+ `⚠️ pipeline stage prompt ${filename} has been customized — skipping shape-aware auto-update.\n` ++ ` To apply the Vonnegut shape variables manually, diff:\n` ++ ` data.sample/prompts/stages/${filename}\n` ++ ` against your current:\n` ++ ` data/prompts/stages/${filename}\n` ++ ` and merge the {{{shapeGuidance}}} block (and {{shapePosition}} / {{volumeShapePosition}} where applicable).`,+ );+ skipped++;+ continue;+ }++ const sampleContent = await readFile(samplePath, 'utf-8');+ await writeFile(dataPath, sampleContent);+ console.log(`✅ updated pipeline stage prompt: ${filename}`);+ updated++;+ }++ const total = updated + alreadyCurrent + skipped + created;+ console.log(+ `📝 shape-aware prompt migration: ${updated} updated, ${created} created, ` ++ `${alreadyCurrent} already current, ${skipped} skipped (customized) — ${total} files checked`,+ );++ if (skipped > 0) {+ console.warn(+ `\n⚠️ ${skipped} prompt(s) could not be auto-updated because they were customized.\n` ++ ` Shape-aware features will work for un-customized prompts; the customized\n` ++ ` ones will continue using their existing templates (without the\n` ++ ` {{{shapeGuidance}}} block) until you merge manually.`,+ );+ }+ },+};diff --git a/scripts/setup-data.js b/scripts/setup-data.jsindex f07b4e50c9..54b3d6b815 100644--- a/scripts/setup-data.js+++ b/scripts/setup-data.js@@ -118,28 +118,39 @@ if (!existsSync(migrationsDir)) {// existing installs won't pick up because setup-data.js only copies *missing*// files.//-// NOTE: only the five files managed by data/migrations/003-update-pipeline-stage-prompts.js-// are checked here — scanning all stage prompts would produce misleading warnings for-// prompts that have no migration counterpart (e.g. cd-evaluate.md, writers-room prompts).+// NOTE: only the files managed by data/migrations/003+ are checked here —+// scanning all stage prompts would produce misleading warnings for prompts+// that have no migration counterpart (e.g. cd-evaluate.md, writers-room prompts).//// Mirror data/migrations/003+ NEW/OLD hashes. Array values let the check-// recognize multi-migration lineages (file evolved through 003 → 004); a-// user at an intermediate hash still gets the "run migrations" prompt.+// recognize multi-migration lineages (file evolved through 003 → 004 → 005);+// a user at any intermediate hash still gets the "run migrations" prompt.const PIPELINE_LENGTH_OLD_MD5 = {// idea-expansion: aee… (pre-003) and 41fa… (post-003, pre-004) both// auto-updatable to the post-004 hash.'pipeline-idea-expansion.md': ['aee25112b2c596f643b17c559b772c22', '41facefbc0c0549d456bef9111f95ab9'],'pipeline-prose.md': 'bfea5aeeb471aae9749baee765b473a7','pipeline-comic-script.md': '40e5fdc1a1e68a7419b7dad936366c1a',- 'pipeline-teleplay.md': '3f6fecc25573ed054b47db392250034a',- 'pipeline-season-episodes.md':'6e349ad26bed8a0ccb042571f03f03eb',+ 'pipeline-teleplay.md': '3f6fecc25573ed054b47db392250034a',+ // 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'],+ // Shape-aware additions (migration 005).+ 'pipeline-arc-overview.md': '6a3ecab43d1f46b7ef9aab6c69ea0326',+ 'pipeline-arc-verify.md': '52e31abc93e3105176236fcaa5d1575a',+ 'pipeline-volume-verify.md': 'c6ea28e972ad6e229bafb2d602b4dda3',+ 'pipeline-arc-resolve.md': '87bc5c01f1a8a97b681727a38b05edc6',};const PIPELINE_LENGTH_NEW_MD5 = {'pipeline-idea-expansion.md': '1ee44cf95851ff8debf18729ebcd40b4','pipeline-prose.md': '30ac30ec2b9d3e2a9eb869c181732cc6','pipeline-comic-script.md': 'beab031951859ca13579cdb9c4dbe769',- 'pipeline-teleplay.md': '376f779f4687b598f1c92ca4e770fd5a',- 'pipeline-season-episodes.md':'c4928e2a5f833358116b29d2d669888d',+ 'pipeline-teleplay.md': '376f779f4687b598f1c92ca4e770fd5a',+ 'pipeline-season-episodes.md':'50c68a29c3ebc275db3095d06bd87100',+ 'pipeline-arc-overview.md': 'd34d72b8e49ba303d38607845dd87f1c',+ 'pipeline-arc-verify.md': 'ff56d8387162017e08d5d0491060ddd6',+ 'pipeline-volume-verify.md': '03f3c874cb80e1c98abcf03168fa7a92',+ 'pipeline-arc-resolve.md': 'a8677bbe1eb38f871fb152a5b0fec7c6',};const PIPELINE_LENGTH_PROMPTS = Object.keys(PIPELINE_LENGTH_OLD_MD5);diff --git a/server/lib/storyArc.js b/server/lib/storyArc.jsindex 7b24ebcb72..ad47a97326 100644--- a/server/lib/storyArc.js+++ b/server/lib/storyArc.js@@ -43,20 +43,165 @@ export const SEASON_STATUSES = Object.freeze(['draft', 'verified', 'in-productio// know whether they're writing a pilot vs. midpoint vs. finale episode.export const ARC_ROLES = Object.freeze(['pilot', 'complication', 'midpoint', 'b-plot', 'all-is-lost', 'finale']);-// Kurt Vonnegut's eight story shapes. The server only validates the id; the-// client owns the display metadata (label, point series for the sparkline).-// Keep this list in sync with `client/src/components/pipeline/StoryShapes.jsx`.-export const ARC_SHAPE_IDS = Object.freeze([- 'rags-to-riches',- 'tragedy',- 'man-in-hole',- 'icarus',- 'cinderella',- 'oedipus',- 'boy-meets-girl',- 'creation-story',+// Kurt Vonnegut's eight story shapes. The client owns the sparkline rendering+// but the points + descriptions live here too so prompt contexts have a+// consistent, deterministic story of what each shape *means* in terms of the+// protagonist's emotional fortune across the arc.+//+// Keep `points` arrays in sync with `client/src/components/pipeline/StoryShapes.jsx`+// — the unit test `storyArc.test.js` asserts they remain identical.+export const ARC_SHAPES = Object.freeze([+ {+ id: 'rags-to-riches',+ label: 'Rags to Riches',+ description: 'Steady monotonic rise from misfortune to triumph.',+ points: [-1, -0.7, -0.4, -0.1, 0.3, 0.7, 1],+ guidance: 'The protagonist\'s fortune climbs monotonically across the arc. Every volume must end better than it began. Setbacks happen but never reverse the overall climb. Open in a low/constrained state; finale lands in unambiguous triumph.',+ },+ {+ id: 'tragedy',+ label: 'Tragedy',+ description: 'Steady fall from good fortune to ruin.',+ points: [1, 0.7, 0.4, 0.1, -0.3, -0.7, -1],+ guidance: 'The protagonist\'s fortune falls monotonically across the arc. Open in a high/privileged state; each volume erodes it further. Brief upticks are allowed but never recover the loss. Finale lands in unambiguous ruin or loss.',+ },+ {+ id: 'man-in-hole',+ label: 'Man in Hole',+ description: 'Falls into trouble, climbs out better than before.',+ points: [0.4, 0, -0.6, -1, -0.5, 0.3, 0.9],+ guidance: 'Open near baseline-good. Plunge to the arc\'s nadir around the midpoint (Volume 2 of 3, midseason of a 1-volume run). Climb out steadily; finale lands higher than the opening. The protagonist is changed by what they survived.',+ },+ {+ id: 'icarus',+ label: 'Icarus',+ description: 'Soars high, then crashes.',+ points: [-0.4, 0.2, 0.7, 1, 0.5, -0.2, -1],+ guidance: 'Rise sharply through the first half of the arc to a peak near the midpoint, then fall just as sharply. Finale lands lower than the opening. The crash should feel earned by the over-reach, not arbitrary.',+ },+ {+ id: 'cinderella',+ label: 'Cinderella',+ description: 'Rises, suffers a setback, soars to the highest peak.',+ points: [-0.7, -0.3, 0.2, 0.5, -0.3, 0.4, 1],+ guidance: 'Open low. Rise through the first half to a modest high, then suffer a sharp reversal around two-thirds in (the "all is lost" beat). Recovery in the final stretch reaches a higher peak than the first rise. Finale is unambiguous triumph.',+ },+ {+ id: 'oedipus',+ label: 'Oedipus',+ description: 'Falls, briefly recovers, falls again to the worst.',+ points: [0.3, -0.2, -0.7, 0.2, 0.5, 0, -1],+ guidance: 'Open near baseline. Fall to a first low in the first third, recover apparently in the middle, then fall further to the arc\'s nadir at the finale. The second fall must reframe the apparent recovery as illusion or trap.',+ },+ {+ id: 'boy-meets-girl',+ label: 'Boy Meets Girl',+ description: 'Gets the thing, loses it, gets it back for good.',+ points: [0, 0.6, 0.9, 0.2, -0.5, 0.3, 0.9],+ guidance: 'Open at baseline. Get the thing (relationship, goal, identity) early; lose it around two-thirds in; reclaim it permanently by the finale. Three-act emotional rhythm: gain, loss, restored gain. Finale is unambiguous reunion or restoration.',+ },+ {+ id: 'creation-story',+ label: 'Creation Story',+ description: 'Stepped ascent — each plateau is a new world.',+ points: [-1, -1, -0.4, -0.4, 0.3, 0.3, 1],+ guidance: 'Stepped monotonic ascent. Each volume ends at a *new plateau* — qualitatively different from the previous, not just incrementally better. Plateaus matter as much as the climbs; finale is the highest plateau.',+ },]);+export const ARC_SHAPE_IDS = Object.freeze(ARC_SHAPES.map((s) => s.id));++const ARC_SHAPES_BY_ID = new Map(ARC_SHAPES.map((s) => [s.id, s]));++export function getArcShape(id) {+ return ARC_SHAPES_BY_ID.get(id) || null;+}++/**+ * Convert the 7-point fortune curve to a human label at a given normalized+ * position (0..1). The LLM gets words it can reason about — "low", "rising",+ * "peak" — instead of a raw float that doesn't translate into beats.+ */+function describeFortuneLevel(v) {+ if (v >= 0.75) return 'peak / triumphant';+ if (v >= 0.35) return 'high / favorable';+ if (v >= -0.15) return 'near baseline';+ if (v >= -0.55) return 'low / strained';+ return 'nadir / ruinous';+}++function describeFortuneMovement(prev, curr) {+ const delta = curr - prev;+ if (delta >= 0.4) return 'sharp climb';+ if (delta >= 0.12) return 'steady climb';+ if (delta <= -0.4) return 'sharp fall';+ if (delta <= -0.12) return 'steady fall';+ return 'plateau';+}++// Sample the 7-point series at a normalized index (0..n-1, fractional allowed)+// with linear interpolation. Returns 0 when the shape is unknown so callers+// get a defined number even off the happy path.+function sampleShapePoints(points, idx) {+ if (!Array.isArray(points) || points.length === 0) return 0;+ const clamped = Math.max(0, Math.min(points.length - 1, idx));+ const lo = Math.floor(clamped);+ const hi = Math.min(points.length - 1, lo + 1);+ const t = clamped - lo;+ return points[lo] * (1 - t) + points[hi] * t;+}++/**+ * Describe one season's expected emotional position within an arc shape.+ * Returns null when shape is unknown or totals are invalid — the prompt+ * builder then renders a "no shape selected" fallback.+ *+ * `seasonNumber` and `totalSeasons` are 1-based; `seasonNumber=1, totalSeasons=3`+ * maps to ~point[1] in a 7-point series, etc.+ */+export function describeArcShapePositionForSeason(shapeId, seasonNumber, totalSeasons) {+ const shape = getArcShape(shapeId);+ if (!shape) return null;+ if (!Number.isFinite(totalSeasons) || !Number.isFinite(seasonNumber)) return null;+ const n = Math.floor(totalSeasons);+ const k = Math.floor(seasonNumber);+ if (n < 1 || k < 1 || k > n) return null;+ const pts = shape.points;+ // Map season index → point index. Season 1 of 1 hits the midpoint; season 1+ // of N hits the start, season N of N hits the end.+ const normalized = n === 1 ? (pts.length - 1) / 2 : ((k - 1) / (n - 1)) * (pts.length - 1);+ const curr = sampleShapePoints(pts, normalized);+ const prev = k > 1 ? sampleShapePoints(pts, ((k - 2) / (n - 1)) * (pts.length - 1)) : null;+ const level = describeFortuneLevel(curr);+ const movement = prev == null ? 'opening position' : describeFortuneMovement(prev, curr);+ return {+ level,+ movement,+ fortune: Number(curr.toFixed(2)),+ summary: `Volume ${k} of ${n} in a "${shape.label}" arc — emotional fortune should sit at ${level} (${movement}).`,+ };+}++/**+ * Block of arc-level shape guidance for prompt contexts. Returns a multi-line+ * string when the series has a picked shape, or null when it doesn't — the+ * prompt template treats null as "no shape selected; propose one if helpful."+ */+export function renderArcShapeGuidance(shapeId) {+ const shape = getArcShape(shapeId);+ if (!shape) return null;+ return `Picked story shape: **${shape.label}** (${shape.id}). ${shape.description}\n\nShape guidance: ${shape.guidance}`;+}++// Convenience for prompt contexts that only need the one-line position summary+// (not the full {level, movement, fortune} object). Returns null when shape /+// season / totals are missing, so callers can OR-fallback to a context-+// specific "no shape" string while keeping that fallback text at the call site.+export function renderArcShapePositionSummary(shapeId, seasonNumber, totalSeasons) {+ const position = describeArcShapePositionForSeason(shapeId, seasonNumber, totalSeasons);+ return position ? position.summary : null;+}+const SEASON_ID_PREFIX = 'sea-';// `id` of an existing season as written by us. Used by `sanitizeSeason` so// callers (route patch handlers, season service) accept either an id wediff --git a/server/lib/storyArc.test.js b/server/lib/storyArc.test.jsindex d77814d94f..9953d5c77d 100644--- a/server/lib/storyArc.test.js+++ b/server/lib/storyArc.test.js@@ -6,7 +6,18 @@ vi.mock('crypto', async () => {return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };});-const { sanitizeArc, sanitizeSeason, sanitizeSeasonList, buildSeason, ARC_LIMITS } = await import('./storyArc.js');+const {+ sanitizeArc,+ sanitizeSeason,+ sanitizeSeasonList,+ buildSeason,+ ARC_LIMITS,+ ARC_SHAPES,+ ARC_SHAPE_IDS,+ getArcShape,+ renderArcShapeGuidance,+ describeArcShapePositionForSeason,+} = await import('./storyArc.js');describe('storyArc — sanitizeArc', () => {it('returns null for null/undefined/non-objects', () => {@@ -156,6 +167,102 @@ describe('storyArc — sanitizeSeasonList', () => {});});+describe('storyArc — Vonnegut shape catalog', () => {+ it('exports all 8 shapes, ids match the curve definitions', () => {+ expect(ARC_SHAPES).toHaveLength(8);+ expect(ARC_SHAPE_IDS).toEqual(ARC_SHAPES.map((s) => s.id));+ for (const shape of ARC_SHAPES) {+ expect(shape.id).toMatch(/^[a-z][a-z-]+$/);+ expect(shape.label).toBeTruthy();+ expect(shape.description).toBeTruthy();+ expect(shape.guidance.length).toBeGreaterThan(50);+ expect(shape.points).toHaveLength(7);+ // Each point in [-1, 1]+ for (const p of shape.points) {+ expect(p).toBeGreaterThanOrEqual(-1);+ expect(p).toBeLessThanOrEqual(1);+ }+ }+ });++ // Lock the server-side `points` arrays to the client's `STORY_SHAPES`+ // definitions so the sparkline and the prompt guidance stay in sync.+ // (CLAUDE.md: "Keep `points` arrays in sync with client/.../StoryShapes.jsx".)+ it('points arrays match the client-side STORY_SHAPES curves', () => {+ const CLIENT_POINTS = {+ 'rags-to-riches': [-1, -0.7, -0.4, -0.1, 0.3, 0.7, 1],+ 'tragedy': [1, 0.7, 0.4, 0.1, -0.3, -0.7, -1],+ 'man-in-hole': [0.4, 0, -0.6, -1, -0.5, 0.3, 0.9],+ 'icarus': [-0.4, 0.2, 0.7, 1, 0.5, -0.2, -1],+ 'cinderella': [-0.7, -0.3, 0.2, 0.5, -0.3, 0.4, 1],+ 'oedipus': [0.3, -0.2, -0.7, 0.2, 0.5, 0, -1],+ 'boy-meets-girl': [0, 0.6, 0.9, 0.2, -0.5, 0.3, 0.9],+ 'creation-story': [-1, -1, -0.4, -0.4, 0.3, 0.3, 1],+ };+ for (const shape of ARC_SHAPES) {+ expect(shape.points).toEqual(CLIENT_POINTS[shape.id]);+ }+ });++ it('getArcShape returns the matching record or null', () => {+ expect(getArcShape('cinderella').label).toBe('Cinderella');+ expect(getArcShape('bogus')).toBe(null);+ expect(getArcShape(null)).toBe(null);+ });++ it('renderArcShapeGuidance returns null for unknown / missing shapes', () => {+ expect(renderArcShapeGuidance(null)).toBe(null);+ expect(renderArcShapeGuidance('')).toBe(null);+ expect(renderArcShapeGuidance('bogus')).toBe(null);+ });++ it('renderArcShapeGuidance produces a labeled, multi-line guidance block', () => {+ const out = renderArcShapeGuidance('rags-to-riches');+ expect(out).toContain('Rags to Riches');+ expect(out).toContain('rags-to-riches');+ expect(out).toContain('monotonically');+ });+});++describe('storyArc — describeArcShapePositionForSeason', () => {+ it('returns null for unknown shape or invalid totals', () => {+ expect(describeArcShapePositionForSeason('bogus', 1, 3)).toBe(null);+ expect(describeArcShapePositionForSeason('rags-to-riches', 0, 3)).toBe(null);+ expect(describeArcShapePositionForSeason('rags-to-riches', 4, 3)).toBe(null);+ expect(describeArcShapePositionForSeason('rags-to-riches', 1, 0)).toBe(null);+ });++ it('places season 1 of N at the opening, season N of N at the terminal', () => {+ const opening = describeArcShapePositionForSeason('rags-to-riches', 1, 3);+ const finale = describeArcShapePositionForSeason('rags-to-riches', 3, 3);+ expect(opening.fortune).toBeLessThan(-0.5); // opens at the bottom+ expect(finale.fortune).toBeGreaterThan(0.5); // ends at the top+ expect(opening.movement).toBe('opening position');+ expect(finale.movement).toContain('climb');+ });++ it('detects the man-in-hole midpoint as the nadir', () => {+ // Volume 2 of 3 in man-in-hole hits the deepest point in the 7-pt curve.+ const mid = describeArcShapePositionForSeason('man-in-hole', 2, 3);+ expect(mid.level).toMatch(/nadir|low/);+ expect(mid.movement).toContain('fall');+ });++ it('handles single-season arcs by sampling the curve midpoint', () => {+ const only = describeArcShapePositionForSeason('icarus', 1, 1);+ expect(only).not.toBe(null);+ expect(only.movement).toBe('opening position');+ // icarus midpoint is the peak+ expect(only.fortune).toBeGreaterThan(0.5);+ });++ it('summary string names the volume and the shape', () => {+ const out = describeArcShapePositionForSeason('cinderella', 2, 3);+ expect(out.summary).toContain('Volume 2 of 3');+ expect(out.summary).toContain('Cinderella');+ });+});+describe('storyArc — buildSeason', () => {it('always produces a sea- prefixed id and fresh timestamps', () => {uuidCounter = 100;diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.jsindex 850f61ab2c..cf4aa958f2 100644--- a/server/services/pipeline/arcPlanner.js+++ b/server/services/pipeline/arcPlanner.js@@ -24,7 +24,16 @@ import { ServerError } from '../../lib/errorHandler.js';import { getSeries, updateSeries } from './series.js';import { listIssues } from './issues.js';import { getSeason } from './seasons.js';-import { sanitizeArc, sanitizeSeasonList, sanitizeSeason, buildSeason, ARC_ROLES as ARC_ROLE_LIST } from '../../lib/storyArc.js';+import {+ sanitizeArc,+ sanitizeSeasonList,+ sanitizeSeason,+ buildSeason,+ ARC_ROLES as ARC_ROLE_LIST,+ ARC_SHAPE_IDS,+ renderArcShapeGuidance,+ renderArcShapePositionSummary,+} from '../../lib/storyArc.js';import { recommendStructure, describeStructure } from '../../lib/seasonStructure.js';import { LENGTH_PROFILE_NAMES, DEFAULT_LENGTH_PROFILE } from '../../lib/issueLength.js';import { getUniverse } from '../universeBuilder.js';@@ -118,9 +127,12 @@ export const compareIssuesByPosition = (a, b) =>// Series + world + arc fields shared by every arc-level prompt context.// Pulled out so verify-arc and verify-volume don't drift on what counts as// "the bible block" — both passes must see the same series identity.+const SHAPE_GUIDANCE_NONE = '(no Vonnegut story shape selected — the verifier should not flag shape adherence)';+async function buildArcBaseContext(series, preloadedWorld) {const arc = series.arc || {};const world = await resolveWorldContext(series, preloadedWorld);+ const shapeGuidance = renderArcShapeGuidance(arc.shape) || SHAPE_GUIDANCE_NONE;return {series: {name: series.name,@@ -133,7 +145,9 @@ async function buildArcBaseContext(series, preloadedWorld) {summary: arc.summary || '',protagonistArc: arc.protagonistArc || '',themesCsv: Array.isArray(arc.themes) ? arc.themes.join(', ') : '',+ shape: arc.shape || '',},+ shapeGuidance,};}@@ -142,8 +156,17 @@ async function buildArcBaseContext(series, preloadedWorld) {// defaulting to 3 seasons regardless of total count.async function buildArcOverviewContext(series, preloadedWorld) {const structure = recommendStructure(series.issueCountTarget);- const world = await resolveWorldContext(series, preloadedWorld);- const canon = await getSeriesCanon(series);+ const [world, canon] = await Promise.all([+ resolveWorldContext(series, preloadedWorld),+ getSeriesCanon(series),+ ]);+ const arc = series.arc || {};+ // Two-mode prompt: when arc.shape is set the prompt's `{{#pickedShapeId}}`+ // section fires (honor mode); when it's empty the `{{^pickedShapeId}}`+ // inverted section fires (propose mode). promptTemplate.js treats `''` as+ // falsy per Mustache spec, so the empty string is the right sentinel.+ const shapeGuidance = renderArcShapeGuidance(arc.shape)+ || `(no shape selected — you must propose one of: ${ARC_SHAPE_IDS.join(', ')}. Return your pick as the JSON field "shape". Choose the shape that best matches the premise's emotional trajectory.)`;return {series: {name: series.name,@@ -158,6 +181,9 @@ async function buildArcOverviewContext(series, preloadedWorld) {: '(no target episode count set — propose 1–3 volumes based on premise weight)',recommendedSeasonCount: structure ? structure.seasons : '',recommendedPerSeasonJson: structure ? JSON.stringify(structure.perSeason) : '[]',+ shapeGuidance,+ pickedShapeId: arc.shape || '',+ allowedShapeIdsCsv: ARC_SHAPE_IDS.join(', '),existingCharactersJson: JSON.stringify(canon.characters, null, 2),existingSettingsJson: JSON.stringify(canon.settings, null, 2),existingObjectsJson: JSON.stringify(canon.objects, null, 2),@@ -202,11 +228,15 @@ export async function generateArcOverview(seriesId, options = {}) {// Build the canonical arc + seasons shape from the LLM payload. We send// both back to the caller so the route can persist in one updateSeries// call (or hand the user a preview before committing).+ // `shape` is the user's Vonnegut pick — the overview prompt doesn't ask+ // the LLM for it, so without this fallback a regenerate would wipe the+ // pick. Mirrors `resolveVerifyIssues` further down.const arc = sanitizeArc({logline: content?.logline || '',summary: content?.summary || '',themes: content?.themes,protagonistArc: content?.protagonistArc || '',+ shape: content?.shape ?? series.arc?.shape ?? null,status: 'draft',});const seasons = shapeSeasonOutlines(content?.seasonOutlines);@@ -231,8 +261,14 @@ async function buildSeasonEpisodesContext(series, season, priorSeasons, priorIssconst priorSeasonsContext = priorSeasons.length === 0? '(this is the first season — no prior context)': priorSeasons.map((s) => renderPriorSeason(s, priorIssues)).join('\n\n');- const world = await resolveWorldContext(series, preloadedWorld);- const canon = await getSeriesCanon(series);+ const [world, canon] = await Promise.all([+ resolveWorldContext(series, preloadedWorld),+ getSeriesCanon(series),+ ]);+ const totalSeasons = (series.seasons || []).length || 1;+ const arcGuidance = renderArcShapeGuidance(arc.shape) || SHAPE_GUIDANCE_NONE;+ const shapePosition = renderArcShapePositionSummary(arc.shape, season.number, totalSeasons)+ || '(no story shape selected — pace episode beats by arcRole only)';return {series: {name: series.name,@@ -245,7 +281,10 @@ async function buildSeasonEpisodesContext(series, season, priorSeasons, priorIsslogline: arc.logline || '',protagonistArc: arc.protagonistArc || '',themesCsv,+ shape: arc.shape || '',},+ shapeGuidance: arcGuidance,+ shapePosition,priorSeasonsContext,season: {number: season.number,@@ -517,6 +556,12 @@ async function buildVolumeVerifyContext(series, season, preloadedWorld) {.filter((iss) => iss.seasonId === season.id).sort(compareIssuesByPosition).map(renderVolumeIssue);+ // Volume-specific curve placement layered on top of base's arc-wide+ // shapeGuidance so the verifier can flag "this volume inverts the expected+ // fortune at its position."+ const totalSeasons = (series.seasons || []).length || 1;+ const volumeShapePosition = renderArcShapePositionSummary(series.arc?.shape, season.number, totalSeasons)+ || '(no story shape selected — do not flag shape adherence for this volume)';return {...base,volume: {@@ -528,6 +573,7 @@ async function buildVolumeVerifyContext(series, season, preloadedWorld) {episodeCountTarget: season.episodeCountTarget ?? '',themesCsv: Array.isArray(season.themes) ? season.themes.join(', ') : '',},+ volumeShapePosition,neighborsJson: JSON.stringify(buildNeighborVolumes(series.seasons, season.id), null, 2),volumeIssuesJson: JSON.stringify(volumeIssues, null, 2),};diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.jsindex 8f92fe508a..9e9891aa43 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -105,6 +105,45 @@ describe('arcPlanner — generateArcOverview', () => {expect(out.seasons.map((s) => s.title)).toEqual(['Pilot', 'Aftermath']);});+ it('preserves an existing arc.shape when regenerating (LLM does not return shape)', async () => {+ const s = await setupSeries({ arc: { shape: 'rags-to-riches', logline: 'seed', status: 'draft' } });+ stageRunnerSpy = vi.fn(async () => ({+ content: { logline: 'New L', summary: 'New S', themes: [], protagonistArc: '', seasonOutlines: [] },+ runId: 'r1', providerId: 'p', model: 'm',+ }));+ const out = await planner.generateArcOverview(s.id);+ expect(out.arc?.shape).toBe('rags-to-riches');+ });++ it('overview context tells the LLM to HONOR the picked shape', async () => {+ const s = await setupSeries({ arc: { shape: 'cinderella', logline: 'seed', status: 'draft' } });+ stageRunnerSpy = vi.fn(async () => ({+ content: { logline: 'L', summary: 'S', themes: [], protagonistArc: 'A', seasonOutlines: [] },+ runId: 'r1', providerId: 'p', model: 'm',+ }));+ await planner.generateArcOverview(s.id);+ const ctx = stageRunnerSpy.mock.calls[0][1];+ // pickedShapeId drives the prompt's {{#pickedShapeId}} section — truthy = honor mode.+ expect(ctx.pickedShapeId).toBe('cinderella');+ expect(ctx.shapeGuidance).toContain('Cinderella');+ expect(ctx.allowedShapeIdsCsv).toContain('cinderella');+ });++ it('overview context tells the LLM to PROPOSE a shape when none is set', async () => {+ const s = await setupSeries(); // arc null+ stageRunnerSpy = vi.fn(async () => ({+ content: { logline: 'L', summary: 'S', themes: [], protagonistArc: 'A', shape: 'icarus', seasonOutlines: [] },+ runId: 'r1', providerId: 'p', model: 'm',+ }));+ const out = await planner.generateArcOverview(s.id);+ const ctx = stageRunnerSpy.mock.calls[0][1];+ // Empty pickedShapeId triggers the prompt's {{^pickedShapeId}} branch (propose mode).+ expect(ctx.pickedShapeId).toBe('');+ expect(ctx.shapeGuidance).toMatch(/no shape selected/i);+ // LLM-proposed shape round-trips into the persisted arc.+ expect(out.arc?.shape).toBe('icarus');+ });+it('returns null arc when every identifying field is empty', async () => {const s = await setupSeries();stageRunnerSpy = vi.fn(async () => ({@@ -220,6 +259,26 @@ describe('arcPlanner — generateSeasonEpisodes', () => {expect(ctx.priorSeasonsContext).toContain('first season');});+ it('passes shape guidance + per-season curve position into the episodes context', async () => {+ const { series, seasons } = await setupSeriesWithSeasons();+ await seriesSvc.updateSeries(series.id, { arc: { shape: 'man-in-hole', logline: 'L', status: 'draft' } });+ stageRunnerSpy = vi.fn(async () => ({ content: { episodes: [] }, runId: 'r1', providerId: 'p', model: 'm' }));+ await planner.generateSeasonEpisodes(series.id, seasons[1].id);+ const ctx = stageRunnerSpy.mock.calls[0][1];+ expect(ctx.shapeGuidance).toContain('Man in Hole');+ expect(ctx.shapePosition).toContain('Volume 2 of 2');+ expect(ctx.arc.shape).toBe('man-in-hole');+ });++ it('shape-position falls back to a neutral note when no shape is selected', async () => {+ const { series, seasons } = await setupSeriesWithSeasons();+ stageRunnerSpy = vi.fn(async () => ({ content: { episodes: [] }, runId: 'r1', providerId: 'p', model: 'm' }));+ await planner.generateSeasonEpisodes(series.id, seasons[0].id);+ const ctx = stageRunnerSpy.mock.calls[0][1];+ expect(ctx.shapePosition).toMatch(/no story shape selected/i);+ expect(ctx.shapeGuidance).toMatch(/no Vonnegut story shape selected/i);+ });+it('rejects ERR_VALIDATION when the season has neither logline nor synopsis', async () => {const s = await setupSeries();const bare = await seasonsSvc.createSeason(s.id, { title: 'Bare', number: 1 });@@ -469,6 +528,30 @@ describe('arcPlanner — verifyVolume', () => {const out = await planner.verifyVolume(s.id, sea.id);expect(out.issues.map((i) => i.problem)).toEqual(['real but tiny']);});++ it('threads the shape + per-volume curve placement into the verifier context', async () => {+ const s = await setupSeries();+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L', shape: 'icarus', status: 'draft' } });+ const v1 = await seasonsSvc.createSeason(s.id, { title: 'V1', number: 1, logline: 'l1' });+ await seasonsSvc.createSeason(s.id, { title: 'V2', number: 2, logline: 'l2' });+ await seasonsSvc.createSeason(s.id, { title: 'V3', number: 3, logline: 'l3' });+ stageRunnerSpy = vi.fn(async () => ({ content: { issues: [] }, runId: 'r', providerId: 'p', model: 'm' }));+ await planner.verifyVolume(s.id, v1.id);+ const ctx = stageRunnerSpy.mock.calls[0][1];+ expect(ctx.shapeGuidance).toContain('Icarus');+ expect(ctx.volumeShapePosition).toContain('Volume 1 of 3');+ expect(ctx.volumeShapePosition).toContain('Icarus');+ });++ it('shape position falls back to a neutral note when no shape is selected', async () => {+ const s = await setupSeries();+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L', status: 'draft' } });+ const v1 = await seasonsSvc.createSeason(s.id, { title: 'V1', number: 1, logline: 'l1' });+ stageRunnerSpy = vi.fn(async () => ({ content: { issues: [] }, runId: 'r', providerId: 'p', model: 'm' }));+ await planner.verifyVolume(s.id, v1.id);+ const ctx = stageRunnerSpy.mock.calls[0][1];+ expect(ctx.volumeShapePosition).toMatch(/no story shape selected/i);+ });});describe('arcPlanner — resolveVerifyIssues', () => {