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): arc + volume + neighbor-issue context for beat-sheet generation
[._.]/ Adam Eivy839361b85b5c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex a1db9eec24..4c5cb03dcb 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,38 @@## Added+- **Beat-sheet expansion — arc / volume / neighbor-issue context block.**+ The `idea` text stage previously generated each issue's beats in isolation+ against the series bible + the user's seed. It now sees the whole frame a+ human editor has open while writing beats: the series arc (logline /+ summary / protagonist arc / themes when populated), the parent volume's+ logline / synopsis / `endingHook` / `episodeCountTarget` / themes, this+ issue's `arcRole` + position-in-volume, the immediate prior + next issue+ in the same volume (beats when expanded, synopsis when not — sourced+ from the current state of each neighbor so regenerating mid-volume picks+ up whatever's been written since), and the prior volume's `endingHook`+ when this is the opening issue of its volume. Regeneration is by design+ current-state-aware: re-running beat generation on issue 3 after issue 4+ is expanded will read issue 4's beats as the "next issue" context. Other+ text stages (prose, comicScript, teleplay) don't get the augment — they+ derive from beats which already encode this. **Files:** new+ `buildIdeaContextAugment` + `shapeNeighborForIdeaPrompt` in+ `server/services/pipeline/textStages.js`, wired into `generateStage`+ only for `stageId === 'idea'`; new `arcRole` field persisted on the+ issue (`server/services/pipeline/issues.js` sanitizer + create + update,+ schema in `server/routes/pipeline.js`, season-episodes commit forwards+ `ep.arcRole`); `ARC_ROLES` promoted from arcPlanner-local to a shared+ export in `server/lib/storyArc.js`; `compareIssuesByPosition` exported+ from arcPlanner.js so the augmenter reuses the canonical issue sort.+ Prompt template rewritten with `{{#arc}}` / `{{#volume}}` / `{{#priorIssue}}`+ / `{{#nextIssue}}` / `{{#priorVolume}}` / `{{#arcRole}}` /+ `{{#positionInVolume}}` Mustache sections that each gate independently on+ presence. New migration `data/migrations/004-augment-idea-expansion-context.js`+ updates installs from the post-003 hash to the new template; the drift+ warning in `scripts/setup-data.js` now accepts array-valued OLD hashes+ so multi-migration lineages still trigger "run migrations" instead of+ false-positive "customized" warnings.+- **Series Pipeline — per-volume Validate volume continuity pass.**Complement to the cross-volume Verify arc pass: a new "Validate volume"button on each season/volume row runs a deeper, narrower continuity checkdiff --git a/data.sample/prompts/stages/pipeline-idea-expansion.md b/data.sample/prompts/stages/pipeline-idea-expansion.mdindex 8f91e9929b..d2d0cb8412 100644--- a/data.sample/prompts/stages/pipeline-idea-expansion.md+++ b/data.sample/prompts/stages/pipeline-idea-expansion.md@@ -20,11 +20,101 @@ You are a story consultant who turns a rough seed idea into a tight beat sheet f*(No characters defined yet — invent placeholders only if absolutely required.)*{{/series.characters}}+{{#arc}}+## Whole-series arc++- **Series logline:** {{logline}}+{{#themesCsv}}- **Themes:** {{themesCsv}}+{{/themesCsv}}{{#protagonistArc}}- **Protagonist arc:** {{protagonistArc}}+{{/protagonistArc}}{{#summary}}- **Arc summary:** {{summary}}+{{/summary}}++The beat sheet you write must move the protagonist arc forward and stay within the named themes — do NOT introduce a major new theme the arc never references.+{{/arc}}++{{#volume}}+## This volume / season++- **Volume {{number}} — "{{title}}"**+{{#logline}}- **Volume logline:** {{logline}}+{{/logline}}{{#synopsis}}- **Volume synopsis:** {{synopsis}}+{{/synopsis}}{{#endingHook}}- **Volume ending hook (the volume's FINAL issue must pay this off):** {{endingHook}}+{{/endingHook}}{{#themesCsv}}- **Volume themes:** {{themesCsv}}+{{/themesCsv}}- **Issue / episode count target:** {{episodeCountTarget}}+{{/volume}}+## This issue / episode- **Number:** {{issue.number}}- **Working title:** {{issue.title}}-- **Length profile:** {{lengthTargets.profile}} — target {{lengthTargets.pageTarget}}-page comic / {{lengthTargets.minutesTarget}}-minute episode+{{#arcRole}}- **Arc role within the volume:** **{{.}}**+{{/arcRole}}{{#positionInVolume}}- **Position in volume:** issue {{ordinal}} of {{total}}.+{{/positionInVolume}}- **Length profile:** {{lengthTargets.profile}} — target {{lengthTargets.pageTarget}}-page comic / {{lengthTargets.minutesTarget}}-minute episode++{{#arcRole}}+Write beats appropriate to the arc role above:++- `pilot` — opens the world; introduces the volume's central question+- `complication` — raises stakes and complicates the protagonist's plan+- `midpoint` — flips a major premise or reveals new information+- `b-plot` — advances a secondary thread while the A-plot rests+- `all-is-lost` — strips the protagonist of their advantage at the lowest point+- `finale` — pays off the volume's ending hook and lands the emotional arc+{{/arcRole}}++{{#priorVolume}}+## Previous volume ended on++Volume {{number}} — "{{title}}" — closed with this hook: **{{endingHook}}**++This is the *opening* issue of the next volume. Your first beat should pick up directly from that hook (don't retell — react). The protagonist's state at the top must be consistent with where the prior volume left them.+{{/priorVolume}}++{{#priorIssue}}+## Prior issue in this volume (immediate predecessor)++Issue #{{number}} — "{{title}}"{{#arcRole}} (arc role: **{{.}}**){{/arcRole}}++{{#beats}}+Beat sheet:++```+{{.}}+```++{{/beats}}{{#synopsis}}+Synopsis (no beats yet):++```+{{.}}+```++{{/synopsis}}+Your opening beat must follow naturally from how this issue closed. Don't repeat its closing image; advance from it.+{{/priorIssue}}++{{#nextIssue}}+## Next issue in this volume (immediate successor)++Issue #{{number}} — "{{title}}"{{#arcRole}} (arc role: **{{.}}**){{/arcRole}}++{{#beats}}+Beat sheet:++```+{{.}}+```++{{/beats}}{{#synopsis}}+Synopsis (no beats yet):++```+{{.}}+```++{{/synopsis}}+Your closing beat / cliffhanger must hand cleanly into this next issue. The protagonist's state, location, and outstanding stakes at the end of your beat sheet should set up its opening without contradicting it.+{{/nextIssue}}## Rough seed from the userdiff --git a/data/migrations/004-augment-idea-expansion-context.js b/data/migrations/004-augment-idea-expansion-context.jsnew file mode 100644index 0000000000..16e2def394--- /dev/null+++ b/data/migrations/004-augment-idea-expansion-context.js@@ -0,0 +1,93 @@+/**+ * Augment `pipeline-idea-expansion.md` with arc / volume / neighbor-issue+ * context blocks. The beat-sheet expander now sees the whole-series arc, the+ * parent volume's logline / synopsis / endingHook, the immediately-prior+ * issue's beats (or synopsis when un-expanded), and the immediately-next+ * issue's beats / synopsis — same shape a human editor has open while+ * writing beats.+ *+ * Strategy mirrors migration 003: replace the installed file only when its+ * hash still matches the previous shipped version (= the migration-003 NEW+ * hash). Customized files are skipped with a manual-merge warning.+ */++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');+};++// The version shipped after migration 003 — the only state this migration+// is willing to auto-update from.+const OLD_SHIPPED_MD5 = {+ 'pipeline-idea-expansion.md': '41facefbc0c0549d456bef9111f95ab9',+};++// The version shipped with this migration — used to detect "already applied"+// on re-runs.+const NEW_SHIPPED_MD5 = {+ 'pipeline-idea-expansion.md': '1ee44cf95851ff8debf18729ebcd40b4',+};++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;++ 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) {+ console.log(`📄 pipeline stage prompt ${filename}: not present in data/, will be created by setup-data.js`);+ 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 auto-update.\n` ++ ` To pick up the new arc / volume / neighbor-issue context blocks, diff:\n` ++ ` data.sample/prompts/stages/${filename}\n` ++ ` against your current:\n` ++ ` data/prompts/stages/${filename}\n` ++ ` and merge the {{#arc}}, {{#volume}}, {{#priorIssue}}, {{#nextIssue}},\n` ++ ` {{#priorVolume}}, {{#arcRole}}, and {{#positionInVolume}} sections.`,+ );+ skipped++;+ continue;+ }++ const sampleContent = await readFile(samplePath, 'utf-8');+ await writeFile(dataPath, sampleContent);+ console.log(`✅ updated pipeline stage prompt: ${filename}`);+ updated++;+ }++ if (updated > 0) {+ console.log(`📝 idea-expansion context migration: ${updated} updated, ${alreadyCurrent} already current, ${skipped} skipped (customized)`);+ } else if (skipped > 0) {+ console.log(`📝 idea-expansion context migration: file customized (${skipped} skipped)`);+ } else {+ console.log(`📝 idea-expansion context migration: already up to date`);+ }+ },+};diff --git a/scripts/setup-data.js b/scripts/setup-data.jsindex 819ab6598e..f07b4e50c9 100644--- a/scripts/setup-data.js+++ b/scripts/setup-data.js@@ -122,21 +122,20 @@ if (!existsSync(migrationsDir)) {// 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).//-// Hash constants mirror data/migrations/003-update-pipeline-stage-prompts.js so we-// can distinguish three cases without importing that module:-// • hash === OLD_SHIPPED_MD5 → auto-updatable, migration not yet applied-// • hash === NEW_SHIPPED_MD5 → already up to date (migration applied or manual merge done)-// • neither → customized, needs manual merge-// Update these whenever 003 (or a successor migration) changes the hashes.+// 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.const PIPELINE_LENGTH_OLD_MD5 = {- 'pipeline-idea-expansion.md': 'aee25112b2c596f643b17c559b772c22',+ // 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',};const PIPELINE_LENGTH_NEW_MD5 = {- 'pipeline-idea-expansion.md': '41facefbc0c0549d456bef9111f95ab9',+ 'pipeline-idea-expansion.md': '1ee44cf95851ff8debf18729ebcd40b4','pipeline-prose.md': '30ac30ec2b9d3e2a9eb869c181732cc6','pipeline-comic-script.md': 'beab031951859ca13579cdb9c4dbe769','pipeline-teleplay.md': '376f779f4687b598f1c92ca4e770fd5a',@@ -160,7 +159,9 @@ if (existsSync(sampleStagesDir) && existsSync(dataStagesDir)) {if (!existsSync(dataPath)) continue; // missing files handled aboveconst dataMd5 = md5(readFileSync(dataPath, 'utf8'));if (dataMd5 === PIPELINE_LENGTH_NEW_MD5[f]) continue; // already up to date- if (dataMd5 === PIPELINE_LENGTH_OLD_MD5[f]) {+ const oldExpected = PIPELINE_LENGTH_OLD_MD5[f];+ const oldHashes = Array.isArray(oldExpected) ? oldExpected : [oldExpected];+ if (oldHashes.includes(dataMd5)) {autoUpdatable.push(f);} else {customized.push(f);diff --git a/server/lib/storyArc.js b/server/lib/storyArc.jsindex 33fe14d8c3..7b24ebcb72 100644--- a/server/lib/storyArc.js+++ b/server/lib/storyArc.js@@ -38,6 +38,11 @@ export const ARC_LIMITS = Object.freeze({export const ARC_STATUSES = Object.freeze(['draft', 'verified']);export const SEASON_STATUSES = Object.freeze(['draft', 'verified', 'in-production', 'complete']);+// Per-episode arc roles produced by the season-episodes generator and+// persisted on the issue so downstream stages (idea-expansion in particular)+// 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`.diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex 1f0e80aa3a..c58007d1f3 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -56,7 +56,7 @@ import {} from '../lib/issueLength.js';import { llmSchema } from './universeBuilder.js';import { BIBLE_KIND } from '../lib/storyBible.js';-import { ARC_LIMITS, ARC_STATUSES, ARC_SHAPE_IDS, SEASON_STATUSES } from '../lib/storyArc.js';+import { ARC_LIMITS, ARC_STATUSES, ARC_SHAPE_IDS, ARC_ROLES, SEASON_STATUSES } from '../lib/storyArc.js';const router = Router();@@ -239,6 +239,7 @@ const issuePatchSchema = z.object({// ordinal within that season. `null` clears the assignment.seasonId: z.string().trim().min(1).max(issuesSvc.SEASON_ID_MAX).nullable().optional(),arcPosition: z.number().int().min(0).max(issuesSvc.ARC_POSITION_MAX).nullable().optional(),+ arcRole: z.enum(ARC_ROLES).nullable().optional(),// Per-issue length profile. Drives the prompt-template size targets// (beats / prose words / page count / minute count). pageTarget +// minutesTarget are only meaningful when lengthProfile === 'custom'.@@ -601,6 +602,10 @@ router.post('/series/:id/seasons/:seasonId/episodes/generate', asyncHandler(asyn// don't collide.seasonId: req.params.seasonId,arcPosition: ep.number,+ // `arcRole` carries the LLM's pilot / complication / midpoint / etc.+ // classification forward so the idea-expansion prompt can size beats+ // to the role (a finale needs a different cadence than a complication).+ arcRole: ep.arcRole,// Episode-level length sizing from the season-episodes LLM pass.// Defaults to 'standard' inside the issue sanitizer when missing.lengthProfile: ep.lengthProfile,diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.jsindex c424ac5034..850f61ab2c 100644--- a/server/services/pipeline/arcPlanner.js+++ b/server/services/pipeline/arcPlanner.js@@ -24,7 +24,7 @@ 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 } from '../../lib/storyArc.js';+import { sanitizeArc, sanitizeSeasonList, sanitizeSeason, buildSeason, ARC_ROLES as ARC_ROLE_LIST } 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';@@ -35,7 +35,7 @@ export const ERR_VALIDATION = 'PIPELINE_ARC_VALIDATION';const makeErr = (message, code) => Object.assign(new Error(message), { code });const VERIFY_SEVERITIES = new Set(['high', 'medium', 'low']);-const ARC_ROLES = new Set(['pilot', 'complication', 'midpoint', 'b-plot', 'all-is-lost', 'finale']);+const ARC_ROLES = new Set(ARC_ROLE_LIST);// Season-episode generation must produce concrete preset profiles only — the// 'custom' sentinel needs companion pageTarget/minutesTarget values the LLM is// not asked to invent, so a 'custom' here would silently render as 'standard'@@ -112,7 +112,7 @@ async function resolveWorldContext(series, preloaded) {// Canonical issue sort: arcPosition first (issues seeded by the season-// episode generator carry sequential positions), then series number as a// tiebreaker for issues that were created ad-hoc and never got a position.-const compareIssuesByPosition = (a, b) =>+export const compareIssuesByPosition = (a, b) =>(a.arcPosition ?? 9999) - (b.arcPosition ?? 9999) || (a.number || 0) - (b.number || 0);// Series + world + arc fields shared by every arc-level prompt context.diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex b5ef0f8035..c8c3f7786c 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -26,6 +26,7 @@ import {CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX,} from '../../lib/issueLength.js';import { sanitizeOrigin } from '../../lib/sharingOrigin.js';+import { ARC_ROLES } from '../../lib/storyArc.js';import { emitRecordUpdated } from '../sharing/recordEvents.js';// Lazy resolution — see series.js for context.@@ -205,6 +206,9 @@ const sanitizeIssue = (raw) => {const arcPosition = Number.isFinite(raw.arcPosition)? Math.max(0, Math.min(ARC_POSITION_MAX, Math.floor(raw.arcPosition))): null;+ // LLM-assigned role within the volume — drives beat-sheet cadence+ // (finale vs. complication need very different shapes).+ const arcRole = ARC_ROLES.includes(raw.arcRole) ? raw.arcRole : null;// Defaults to 'standard' so pre-field issues keep the prior 22pg/24min sizing.// pageTarget/minutesTarget are only consumed when lengthProfile==='custom',// but we persist them on every profile so the picker can remember a previous@@ -228,6 +232,7 @@ const sanitizeIssue = (raw) => {status,seasonId,arcPosition,+ arcRole,lengthProfile,pageTarget,minutesTarget,@@ -306,6 +311,7 @@ export function createIssue(input = {}) {// (and any future caller wiring an issue to a season at create time).seasonId: 'seasonId' in input ? input.seasonId : null,arcPosition: 'arcPosition' in input ? input.arcPosition : null,+ arcRole: 'arcRole' in input ? input.arcRole : null,lengthProfile: 'lengthProfile' in input ? input.lengthProfile : undefined,pageTarget: 'pageTarget' in input ? input.pageTarget : null,minutesTarget: 'minutesTarget' in input ? input.minutesTarget : null,@@ -414,6 +420,7 @@ export function updateIssue(id, patch = {}) {...('status' in patch ? { status: patch.status } : {}),...('seasonId' in patch ? { seasonId: patch.seasonId } : {}),...('arcPosition' in patch ? { arcPosition: patch.arcPosition } : {}),+ ...('arcRole' in patch ? { arcRole: patch.arcRole } : {}),...('lengthProfile' in patch ? { lengthProfile: patch.lengthProfile } : {}),...('pageTarget' in patch ? { pageTarget: patch.pageTarget } : {}),...('minutesTarget' in patch ? { minutesTarget: patch.minutesTarget } : {}),diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.jsindex 5449754124..511b2ddcc7 100644--- a/server/services/pipeline/textStages.js+++ b/server/services/pipeline/textStages.js@@ -16,8 +16,9 @@import { runStagedLLM } from '../../lib/stageRunner.js';import { getSeries, extractAndMergeIntoSeries } from './series.js';-import { getIssue, updateStage, TEXT_STAGE_IDS } from './issues.js';+import { getIssue, listIssues, updateStage, TEXT_STAGE_IDS } from './issues.js';import { getSeriesCanon } from './seriesCanon.js';+import { compareIssuesByPosition } from './arcPlanner.js';import { computeIssueTargets } from '../../lib/issueLength.js';const STAGE_TO_TEMPLATE = Object.freeze({@@ -27,6 +28,106 @@ const STAGE_TO_TEMPLATE = Object.freeze({teleplay: 'pipeline-teleplay',});+// Set exactly one of `beats` / `synopsis` per neighbor so the prompt's+// beat-level guidance doesn't leak into synopsis-only entries (the template+// gates on each field independently).+function shapeNeighborForIdeaPrompt(iss) {+ if (!iss) return null;+ const beats = (iss.stages?.idea?.output || '').trim();+ const synopsis = (iss.stages?.idea?.input || '').trim();+ const base = {+ number: iss.number,+ title: iss.title,+ arcPosition: iss.arcPosition,+ arcRole: iss.arcRole || null,+ };+ return beats ? { ...base, beats } : { ...base, synopsis };+}++// Mirrors the writer's working frame when drafting beats: whole-series arc+// + parent volume + immediate-neighbor issues. Other text stages (prose,+// comicScript, teleplay) don't need it — they derive from beats which+// already encode it.+async function buildIdeaContextAugment(series, issue) {+ const seasons = Array.isArray(series.seasons) ? series.seasons : [];+ const season = issue.seasonId ? seasons.find((s) => s.id === issue.seasonId) : null;++ // Arc block — only when the series actually has generated arc content+ // (shape-only arcs aren't enough context for the LLM to lean on).+ const arc = series.arc;+ const hasArcText = !!(arc && (arc.logline || arc.summary || arc.protagonistArc || arc.themes?.length));+ const arcBlock = hasArcText+ ? {+ logline: arc.logline || '',+ summary: arc.summary || '',+ protagonistArc: arc.protagonistArc || '',+ themesCsv: Array.isArray(arc.themes) ? arc.themes.join(', ') : '',+ }+ : null;++ if (!season) {+ return {+ arc: arcBlock,+ volume: null,+ arcRole: issue.arcRole || null,+ positionInVolume: null,+ priorIssue: null,+ nextIssue: null,+ priorVolume: null,+ };+ }++ const allIssues = await listIssues({ seriesId: series.id });+ const volumeIssues = allIssues+ .filter((i) => i.seasonId === season.id)+ .sort(compareIssuesByPosition);+ const idx = volumeIssues.findIndex((i) => i.id === issue.id);+ const priorIssue = idx > 0 ? shapeNeighborForIdeaPrompt(volumeIssues[idx - 1]) : null;+ const nextIssue = idx >= 0 && idx < volumeIssues.length - 1+ ? shapeNeighborForIdeaPrompt(volumeIssues[idx + 1])+ : null;+ const positionInVolume = idx >= 0+ ? { ordinal: idx + 1, total: volumeIssues.length }+ : null;++ // Prior volume — only relevant when this issue opens its volume (no prior+ // siblings within the same volume). Use the season number sequence (not+ // creation order) so out-of-order seasons still produce the right neighbor.+ let priorVolume = null;+ if (idx <= 0) {+ const sortedSeasons = seasons+ .slice()+ .sort((a, b) => (a.number || 0) - (b.number || 0));+ const seasonIdx = sortedSeasons.findIndex((s) => s.id === season.id);+ if (seasonIdx > 0) {+ const prev = sortedSeasons[seasonIdx - 1];+ priorVolume = {+ number: prev.number,+ title: prev.title || '',+ endingHook: prev.endingHook || '',+ };+ }+ }++ return {+ arc: arcBlock,+ volume: {+ number: season.number,+ title: season.title || '',+ logline: season.logline || '',+ synopsis: season.synopsis || '',+ endingHook: season.endingHook || '',+ episodeCountTarget: season.episodeCountTarget || 0,+ themesCsv: Array.isArray(season.themes) ? season.themes.join(', ') : '',+ },+ arcRole: issue.arcRole || null,+ positionInVolume,+ priorIssue,+ nextIssue,+ priorVolume,+ };+}+/*** Build the variable bag fed into the stage template. Includes the series* bible (`series.*`) and every *prior* text stage's content (`stages.*`).@@ -89,6 +190,9 @@ export async function generateStage(issueId, stageId, options = {}) {await updateStage(issueId, stageId, { status: 'generating', errorMessage: '' });const ctx = buildStageContext({ series, canon, issue, stageId, seedInput: options.seedInput });+ if (stageId === 'idea') {+ Object.assign(ctx, await buildIdeaContextAugment(series, issue));+ }// Catch only at this boundary so the stage record persists the failure// before the error bubbles to the caller — without this, an LLM throw@@ -135,4 +239,4 @@ export async function generateStage(issueId, stageId, options = {}) {}// Export internals for tests.-export const __testing = { buildStageContext, STAGE_TO_TEMPLATE };+export const __testing = { buildStageContext, buildIdeaContextAugment, shapeNeighborForIdeaPrompt, STAGE_TO_TEMPLATE };diff --git a/server/services/pipeline/textStages.test.js b/server/services/pipeline/textStages.test.jsindex 06fa6d2ddc..e69520a01d 100644--- a/server/services/pipeline/textStages.test.js+++ b/server/services/pipeline/textStages.test.js@@ -54,8 +54,13 @@ vi.mock('../promptService.js', () => ({const issuesSvc = await import('./issues.js');const seriesSvc = await import('./series.js');+const seasonsSvc = await import('./seasons.js');const textStages = await import('./textStages.js');+// Strip the `RENDERED:<stage>:` prefix that the mocked buildPrompt prepends+// so the asserted-against context is the bare JSON tree.+const ctxFromCall = (call) => JSON.parse(call.prompt.replace(/^RENDERED:[^:]+:/, ''));+describe('pipeline text stage generator', () => {beforeEach(() => {fileStore.clear();@@ -140,6 +145,183 @@ describe('pipeline text stage generator', () => {expect(lt.beatsMax).toBe(16);});+ // ---- idea-stage context augment (arc / volume / neighbor) ----+ // Covers buildIdeaContextAugment via the public generateStage entry so we+ // exercise the same path the LLM caller hits, not an internal helper.++ it('idea context: omits arc / volume / neighbors when issue is ungrouped + series has no arc', async () => {+ const { issue } = await seed();+ await textStages.generateStage(issue.id, 'idea');+ const ctx = ctxFromCall(llmCalls[0]);+ expect(ctx.arc).toBe(null);+ expect(ctx.volume).toBe(null);+ expect(ctx.priorIssue).toBe(null);+ expect(ctx.nextIssue).toBe(null);+ expect(ctx.priorVolume).toBe(null);+ expect(ctx.positionInVolume).toBe(null);+ expect(ctx.arcRole).toBe(null);+ });++ it('idea context: surfaces arc block only when arc has generated text (shape-only arc is ignored)', async () => {+ const { series, issue } = await seed();+ // Shape-only arc — sanitizer preserves it but it carries no text. Must NOT+ // surface as `arc` context (the prompt asks for protagonist arc + themes).+ await seriesSvc.updateSeries(series.id, { arc: { shape: 'man-in-hole' } });+ await textStages.generateStage(issue.id, 'idea');+ expect(ctxFromCall(llmCalls[0]).arc).toBe(null);++ llmCalls.length = 0;+ await seriesSvc.updateSeries(series.id, {+ arc: { logline: 'whole-arc pitch', protagonistArc: 'falls and rises', themes: ['legacy'], shape: 'man-in-hole' },+ });+ await textStages.generateStage(issue.id, 'idea');+ const ctx2 = ctxFromCall(llmCalls[0]);+ expect(ctx2.arc).toMatchObject({+ logline: 'whole-arc pitch',+ protagonistArc: 'falls and rises',+ themesCsv: 'legacy',+ });+ });++ it('idea context: volume + position-in-volume + arcRole when issue is grouped', async () => {+ const { series } = await seed();+ await seriesSvc.updateSeries(series.id, { arc: { logline: 'L' } });+ const sea = await seasonsSvc.createSeason(series.id, {+ title: 'V1', logline: 'volume logline', synopsis: 'volume synopsis',+ endingHook: 'the bridge falls', episodeCountTarget: 8,+ });+ const i1 = await issuesSvc.createIssue({+ seriesId: series.id, title: 'Pilot', seasonId: sea.id, arcPosition: 1, arcRole: 'pilot',+ });+ const i2 = await issuesSvc.createIssue({+ seriesId: series.id, title: 'Complication', seasonId: sea.id, arcPosition: 2, arcRole: 'complication',+ });+ await issuesSvc.createIssue({+ seriesId: series.id, title: 'Midpoint', seasonId: sea.id, arcPosition: 3, arcRole: 'midpoint',+ });++ await textStages.generateStage(i2.id, 'idea');+ const ctx = ctxFromCall(llmCalls[0]);+ expect(ctx.volume).toMatchObject({+ number: sea.number,+ title: 'V1',+ logline: 'volume logline',+ endingHook: 'the bridge falls',+ episodeCountTarget: 8,+ });+ expect(ctx.arcRole).toBe('complication');+ expect(ctx.positionInVolume).toEqual({ ordinal: 2, total: 3 });+ expect(ctx.priorIssue).toMatchObject({ title: 'Pilot', arcRole: 'pilot', arcPosition: 1 });+ expect(ctx.nextIssue).toMatchObject({ title: 'Midpoint', arcRole: 'midpoint', arcPosition: 3 });+ });++ it('idea context: neighbor exposes beats when expanded, synopsis when not', async () => {+ const { series } = await seed();+ await seriesSvc.updateSeries(series.id, { arc: { logline: 'L' } });+ const sea = await seasonsSvc.createSeason(series.id, { title: 'V1', logline: 'l' });+ // Prior issue: has expanded beats (idea.output filled).+ await issuesSvc.createIssue({+ seriesId: series.id, title: 'Prior', seasonId: sea.id, arcPosition: 1,+ stages: { idea: { input: 'prior seed', output: 'beat 1\nbeat 2', status: 'ready' } },+ });+ // Current issue (the one we're generating beats for).+ const cur = await issuesSvc.createIssue({+ seriesId: series.id, title: 'Current', seasonId: sea.id, arcPosition: 2,+ });+ // Next issue: synopsis-only (idea.input only).+ await issuesSvc.createIssue({+ seriesId: series.id, title: 'Next', seasonId: sea.id, arcPosition: 3,+ stages: { idea: { input: 'next synopsis only', status: 'edited' } },+ });++ await textStages.generateStage(cur.id, 'idea');+ const ctx = ctxFromCall(llmCalls[0]);+ expect(ctx.priorIssue).toMatchObject({ title: 'Prior', beats: expect.stringContaining('beat 1') });+ expect(ctx.priorIssue).not.toHaveProperty('synopsis');+ expect(ctx.nextIssue).toMatchObject({ title: 'Next', synopsis: 'next synopsis only' });+ expect(ctx.nextIssue).not.toHaveProperty('beats');+ });++ it('idea context: first issue of a volume sees priorVolume.endingHook, no priorIssue', async () => {+ const { series } = await seed();+ await seriesSvc.updateSeries(series.id, { arc: { logline: 'L' } });+ const v1 = await seasonsSvc.createSeason(series.id, {+ title: 'V1', logline: 'one', endingHook: 'the city ignites',+ });+ const v2 = await seasonsSvc.createSeason(series.id, { title: 'V2', logline: 'two' });+ // Issue in v1 to populate it (not the issue we're generating for).+ await issuesSvc.createIssue({+ seriesId: series.id, title: 'V1 Ep 1', seasonId: v1.id, arcPosition: 1,+ });+ // First issue of v2 — should see priorVolume but no priorIssue.+ const v2head = await issuesSvc.createIssue({+ seriesId: series.id, title: 'V2 Ep 1', seasonId: v2.id, arcPosition: 1,+ });++ await textStages.generateStage(v2head.id, 'idea');+ const ctx = ctxFromCall(llmCalls[0]);+ expect(ctx.priorIssue).toBe(null);+ expect(ctx.priorVolume).toEqual({ number: v1.number, title: 'V1', endingHook: 'the city ignites' });+ });++ it('idea context: middle-of-volume issue has no priorVolume even if a prior volume exists', async () => {+ const { series } = await seed();+ await seriesSvc.updateSeries(series.id, { arc: { logline: 'L' } });+ const v1 = await seasonsSvc.createSeason(series.id, { title: 'V1', endingHook: 'hook1' });+ const v2 = await seasonsSvc.createSeason(series.id, { title: 'V2' });+ await issuesSvc.createIssue({ seriesId: series.id, title: 'V1 Ep 1', seasonId: v1.id, arcPosition: 1 });+ await issuesSvc.createIssue({ seriesId: series.id, title: 'V2 Ep 1', seasonId: v2.id, arcPosition: 1 });+ const mid = await issuesSvc.createIssue({+ seriesId: series.id, title: 'V2 Ep 2', seasonId: v2.id, arcPosition: 2,+ });+ await textStages.generateStage(mid.id, 'idea');+ const ctx = ctxFromCall(llmCalls[0]);+ expect(ctx.priorVolume).toBe(null);+ expect(ctx.priorIssue).toMatchObject({ title: 'V2 Ep 1' });+ });++ it('idea context: last issue of a volume has no nextIssue', async () => {+ const { series } = await seed();+ await seriesSvc.updateSeries(series.id, { arc: { logline: 'L' } });+ const sea = await seasonsSvc.createSeason(series.id, { title: 'V1' });+ await issuesSvc.createIssue({ seriesId: series.id, title: 'A', seasonId: sea.id, arcPosition: 1 });+ const last = await issuesSvc.createIssue({+ seriesId: series.id, title: 'B', seasonId: sea.id, arcPosition: 2,+ });+ await textStages.generateStage(last.id, 'idea');+ const ctx = ctxFromCall(llmCalls[0]);+ expect(ctx.nextIssue).toBe(null);+ expect(ctx.priorIssue).toMatchObject({ title: 'A' });+ });++ it('idea context: a regenerated issue sees the CURRENT state of neighbors, not the original', async () => {+ // Confirms the user's stated workflow: re-running beat generation on+ // issue N pulls whatever beats issue N+1 currently has, even if those+ // beats were written after the original generation of N.+ const { series } = await seed();+ await seriesSvc.updateSeries(series.id, { arc: { logline: 'L' } });+ const sea = await seasonsSvc.createSeason(series.id, { title: 'V1' });+ const a = await issuesSvc.createIssue({ seriesId: series.id, title: 'A', seasonId: sea.id, arcPosition: 1 });+ const b = await issuesSvc.createIssue({ seriesId: series.id, title: 'B', seasonId: sea.id, arcPosition: 2 });++ // First pass: A regenerated when B is empty.+ await textStages.generateStage(a.id, 'idea');+ expect(ctxFromCall(llmCalls[0]).nextIssue).toMatchObject({ title: 'B' });+ expect(ctxFromCall(llmCalls[0]).nextIssue).not.toHaveProperty('beats');++ // Now fill B with beats and regenerate A — the new context for A must+ // include B's beats, not the empty state we saw the first pass.+ await issuesSvc.updateStage(b.id, 'idea', { status: 'ready', output: 'beat alpha\nbeat omega' });+ llmCalls.length = 0;+ await textStages.generateStage(a.id, 'idea');+ expect(ctxFromCall(llmCalls[0]).nextIssue).toMatchObject({+ title: 'B',+ beats: expect.stringContaining('beat alpha'),+ });+ });++ // -- end idea-stage context augment --+it('prompt context carries derived lengthTargets for the custom profile', async () => {const { series } = await seed();// 44 pages is 2× the standard 22-page baseline, so all derived ranges