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
fix(pipeline): strengthen narrative quality gates (#4461)
[._.]/ Adam Eivy1e40d1b01e5b
diff --git a/.changelog/next/fixed-series-autopilot-quality.md b/.changelog/next/fixed-series-autopilot-quality.mdnew file mode 100644index 0000000000..cda8d9f30d--- /dev/null+++ b/.changelog/next/fixed-series-autopilot-quality.md@@ -0,0 +1 @@+- Keep repaired episode plans concise, block outline-only canon readiness, stale completeness findings after manuscript or narrative-reference edits, and refresh series thumbnails when issue covers changediff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsxindex 3256786e57..2bc93ea0c6 100644--- a/client/src/components/pipeline/AutopilotPanel.jsx+++ b/client/src/components/pipeline/AutopilotPanel.jsx@@ -1,8 +1,8 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { Link } from 'react-router';import {- Rocket, Loader2, X, Sliders, ShieldCheck, AlertCircle, CheckCircle2,- PauseCircle, Play, ScanSearch, ChevronRight, ChevronDown,+ Rocket, Loader2, X, Sliders, AlertCircle, CheckCircle2,+ PauseCircle, Play, ChevronRight, ChevronDown,} from 'lucide-react';import toast from '../ui/Toast';import { usePipelineProgress } from '../../hooks/usePipelineProgress';@@ -14,7 +14,6 @@ import {getPipelineAutopilotStatus,getPipelineAutopilotModelMetrics,pipelineAutopilotSseUrl,- getPipelineSeriesCanonReadiness,getPipelineSeries,listPipelineIssues,getProviders,@@ -26,6 +25,7 @@ import { autopilotStepLabel, describeAutopilotVerification, autopilotMarkerTermiimport Pill from '../ui/Pill';import ProviderModelSelector from '../ProviderModelSelector';import AutopilotMilestones from './AutopilotMilestones';+import CanonReadinessPanel from './CanonReadinessPanel';import SeriesAutopilotSchedule from './SeriesAutopilotSchedule';import { severityColor } from './constants.js';@@ -550,8 +550,6 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate// scheduled unattended runs of every series. Always starts unticked, so// clearing locks is a fresh, deliberate choice each run.const [unlockForRun, setUnlockForRun] = useState(false);- const [canon, setCanon] = useState(null);- const [canonLoading, setCanonLoading] = useState(false);// Per-run provider/model override. '' = "use the series default", i.e. the// provider picked in the series header (`series.llm`), falling back to the// install's active provider — the same chain the server resolves in@@ -939,14 +937,6 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdatesetPausePending(result?.pauseRequested === true);}, [seriesId]);- const checkCanon = useCallback(async () => {- setCanonLoading(true);- const report = await getPipelineSeriesCanonReadiness(seriesId, { silent: true })- .catch((err) => { toast.error(err.message || 'Canon check failed'); return null; });- setCanonLoading(false);- if (report) setCanon(report);- }, [seriesId]);-if (!seriesId) return null;const ap = series.autopilot;@@ -1504,42 +1494,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate) : null}{/* Production readiness (canon descriptive integrity) */}- <div className="px-3 pb-3 border-t border-port-border pt-2">- <div className="flex items-center gap-2">- <ShieldCheck size={13} className="text-gray-400" />- <span className="text-xs text-gray-300">Production readiness — are all drawn characters/places/objects described?</span>- <button- type="button"- onClick={checkCanon}- disabled={canonLoading}- className="ml-auto inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-300 hover:text-white border border-port-border bg-port-bg hover:border-port-accent/40 disabled:opacity-40"- >- {canonLoading ? <Loader2 size={12} className="animate-spin" /> : <ScanSearch size={12} />}- Check- </button>- </div>- {canon ? (- canon.ready ? (- <p className="mt-2 text-xs text-port-success flex items-center gap-1.5">- <CheckCircle2 size={12} /> Every noun that gets drawn has a description.- </p>- ) : (- <div className="mt-2 space-y-2">- <p className="text-xs text-port-warning">- {canon.undescribed.length} noun(s) appear where they'd be drawn but have no description — fix before generating art:- </p>- {canon.blockingIssues.map((bi) => (- <div key={bi.issueId} className="text-xs">- <Link to={`/pipeline/issues/${bi.issueId}/nouns`} className="text-port-accent hover:underline">- #{bi.number} {bi.title || ''} →- </Link>- <span className="text-gray-400"> {bi.none.map((n) => `${n.name} (${n.kind})`).join(', ')}</span>- </div>- ))}- </div>- )- ) : null}- </div>+ <CanonReadinessPanel seriesId={seriesId} /></div>);}diff --git a/client/src/components/pipeline/AutopilotPanel.test.jsx b/client/src/components/pipeline/AutopilotPanel.test.jsxindex 417bcecce8..ff84dea0ac 100644--- a/client/src/components/pipeline/AutopilotPanel.test.jsx+++ b/client/src/components/pipeline/AutopilotPanel.test.jsx@@ -1029,4 +1029,43 @@ describe('AutopilotPanel', () => {const link = screen.getByRole('link', { name: /#3 Backdoor/i });expect(link).toHaveAttribute('href', '/pipeline/issues/iss-9/nouns');});++ it('explains that outline-only issues are missing a visual source', async () => {+ getPipelineSeriesCanonReadiness.mockResolvedValue({+ ready: false,+ undescribed: [],+ blockingIssues: [{+ issueId: 'iss-2', number: 2, title: 'Threshold', none: [],+ blockingReason: 'missing-visual-source', missingSourceStages: ['comicScript'],+ }],+ });+ renderPanel({ id: 's1', targetFormat: 'comic' });+ await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());+ fireEvent.click(screen.getByRole('button', { name: /^check$/i }));++ expect(await screen.findByText(/outline or prose draft cannot prove canon is ready/i)).toBeInTheDocument();+ expect(screen.getByRole('link', { name: /#2 Threshold/i }))+ .toHaveAttribute('href', '/pipeline/issues/iss-2/comicScript');+ });++ it('shows visual-source and canon-noun blockers for the same issue', async () => {+ getPipelineSeriesCanonReadiness.mockResolvedValue({+ ready: false,+ undescribed: [{ id: 'c1', name: 'Kai', kind: 'character' }],+ blockingIssues: [{+ issueId: 'iss-2', number: 2, title: 'Threshold',+ none: [{ id: 'c1', name: 'Kai', kind: 'character' }],+ blockingReason: 'missing-visual-source', missingSourceStages: ['teleplay'],+ }],+ });+ renderPanel({ id: 's1', targetFormat: 'hybrid' });+ await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());+ fireEvent.click(screen.getByRole('button', { name: /^check$/i }));++ expect(await screen.findByText(/Kai \(character\)/i)).toBeInTheDocument();+ expect(screen.getByRole('link', { name: /Threshold — visual script/i }))+ .toHaveAttribute('href', '/pipeline/issues/iss-2/teleplay');+ expect(screen.getByRole('link', { name: /Threshold — canon nouns/i }))+ .toHaveAttribute('href', '/pipeline/issues/iss-2/nouns');+ });});diff --git a/client/src/components/pipeline/CanonReadinessPanel.jsx b/client/src/components/pipeline/CanonReadinessPanel.jsxnew file mode 100644index 0000000000..766b6af2b3--- /dev/null+++ b/client/src/components/pipeline/CanonReadinessPanel.jsx@@ -0,0 +1,86 @@+import { useCallback, useState } from 'react';+import { Link } from 'react-router';+import { CheckCircle2, Loader2, ScanSearch, ShieldCheck } from 'lucide-react';+import toast from '../ui/Toast';+import { getPipelineSeriesCanonReadiness } from '../../services/api';++export default function CanonReadinessPanel({ seriesId }) {+ const [canon, setCanon] = useState(null);+ const [canonLoading, setCanonLoading] = useState(false);++ const checkCanon = useCallback(async () => {+ setCanonLoading(true);+ const report = await getPipelineSeriesCanonReadiness(seriesId, { silent: true })+ .catch((err) => { toast.error(err.message || 'Canon check failed'); return null; });+ setCanonLoading(false);+ if (report) setCanon(report);+ }, [seriesId]);++ return (+ <div className="px-3 pb-3 border-t border-port-border pt-2">+ <div className="flex items-center gap-2">+ <ShieldCheck size={13} className="text-gray-400" />+ <span className="text-xs text-gray-300">Production readiness — are all drawn characters/places/objects described?</span>+ <button+ type="button"+ onClick={checkCanon}+ disabled={canonLoading}+ className="ml-auto inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-300 hover:text-white border border-port-border bg-port-bg hover:border-port-accent/40 disabled:opacity-40"+ >+ {canonLoading ? <Loader2 size={12} className="animate-spin" /> : <ScanSearch size={12} />}+ Check+ </button>+ </div>+ {canon ? (+ canon.ready ? (+ <p className="mt-2 text-xs text-port-success flex items-center gap-1.5">+ <CheckCircle2 size={12} /> Every noun that gets drawn has a description.+ </p>+ ) : (+ <div className="mt-2 space-y-2">+ {(canon.blockingIssues || []).some((bi) => bi.blockingReason === 'missing-visual-source') ? (+ <p className="text-xs text-port-warning">+ Some issues have no finished visual script yet. An outline or prose draft cannot prove canon is ready for rendering.+ </p>+ ) : null}+ {(canon.undescribed || []).length > 0 ? (+ <p className="text-xs text-port-warning">+ {canon.undescribed.length} noun(s) appear where they'd be drawn but have no description — fix before generating art:+ </p>+ ) : null}+ {(canon.blockingIssues || []).map((bi) => (+ <div key={bi.issueId} className="space-y-1">+ {(bi.missingSourceStages || []).length > 0 ? (+ <div className="text-xs">+ <Link+ to={`/pipeline/issues/${bi.issueId}/${bi.missingSourceStages[0]}`}+ className="text-port-accent hover:underline"+ >+ #{bi.number} {bi.title || ''} — visual script →+ </Link>+ <span className="text-gray-400">+ {' '}missing {bi.missingSourceStages.join(' + ')}+ </span>+ </div>+ ) : null}+ {(bi.none || []).length > 0 ? (+ <div className="text-xs">+ <Link+ to={`/pipeline/issues/${bi.issueId}/nouns`}+ className="text-port-accent hover:underline"+ >+ #{bi.number} {bi.title || ''} — canon nouns →+ </Link>+ <span className="text-gray-400">+ {' '}{bi.none.map((n) => `${n.name} (${n.kind})`).join(', ')}+ </span>+ </div>+ ) : null}+ </div>+ ))}+ </div>+ )+ ) : null}+ </div>+ );+}diff --git a/data.reference/prompts/stages/pipeline-arc-resolve.md b/data.reference/prompts/stages/pipeline-arc-resolve.mdindex cbc8b70517..13ae79b8ba 100644--- a/data.reference/prompts/stages/pipeline-arc-resolve.md+++ b/data.reference/prompts/stages/pipeline-arc-resolve.md@@ -172,11 +172,11 @@ Resolve the findings above with edits that cannot re-create any of these. Concre5. **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.6. **Unresolved finale hooks / theme drift** — surface the missing theme or arc payoff in the final volume's `synopsis`.7. **Preserve volume `id`** for every existing volume you edit. Only assign no `id` to brand-new volumes you are adding. Never delete a volume — if a finding could only be resolved by removing one, write that in the `notes` field instead of doing it.-8. **Correct an episode synopsis when the contradiction *originates* in that episode.** Sometimes a finding can't be fixed at the volume level because the wrong content lives in a specific episode's `synopsis` — e.g. an episode stages an event that a later volume reserves as its own "first" occurrence, or a promised through-line silently disappears from the episodes that should carry it. In those cases the only convergent fix is to rewrite the offending episode's `synopsis` so it stops contradicting the rest of the arc. Return those rewrites in the `episodes[]` output array below, keyed by `seasonNumber` + `episodeNumber`. These are early planning synopses (no script has been drafted yet), so editing them is safe and is preferred over papering over the conflict at the volume level. Rules: edit an episode synopsis ONLY when a finding genuinely originates there; make the smallest change that removes the contradiction while preserving the episode's dramatic purpose; never delete an episode (omit it from `episodes[]` to leave it untouched). If a finding could only be resolved by removing issues entirely, write that in the `notes` field instead of doing it.+8. **Correct an episode synopsis when the contradiction *originates* in that episode.** Sometimes a finding can't be fixed at the volume level because the wrong content lives in a specific episode's `synopsis` — e.g. an episode stages an event that a later volume reserves as its own "first" occurrence, or a promised through-line silently disappears from the episodes that should carry it. In those cases the only convergent fix is to rewrite the offending episode's `synopsis` so it stops contradicting the rest of the arc. Return those rewrites in the `episodes[]` output array below, keyed by `seasonNumber` + `episodeNumber`. These are early planning synopses (no script has been drafted yet), so editing them is safe and is preferred over papering over the conflict at the volume level. Rules: edit an episode synopsis ONLY when a finding genuinely originates there; make the smallest change that removes the contradiction while preserving the episode's one dramatic purpose; **replace or compact conflicting language instead of appending another caveat, exception, permission, or ledger entry**; never delete an episode (omit it from `episodes[]` to leave it untouched). Target roughly 150–300 words and never exceed 4,000 characters for one episode synopsis. If a finding could only be resolved by removing issues entirely, write that in the `notes` field instead of doing it.9. **Return only the records you actually edited, and key every one of them to a finding.** `characterArcs[]`, `seasons[]`, and `episodes[]` are SPARSE patch lists: include a character arc only if you corrected it, a volume only if you changed it, an episode only if you rewrote it, and the `arc` block only if you changed the arc itself. Every entry — including `arc` — carries `resolves: ["f2", ...]`, the ids of the findings that edit closes. An edit that names no finding is discarded by the server, so do not return untouched records "for completeness": that is the single biggest source of NEW contradictions, because every untargeted rewrite is a chance to break something the verification pass had not flagged.10. **Patch long prose with exact text replacements; never return it wholesale.** Set top-level `patchMode` to `"exact-text-v1"`. For an existing arc, change `summary` only through `summaryEdits[]` and `protagonistArc` only through `protagonistArcEdits[]`. For an existing volume, change `synopsis` only through `synopsisEdits[]` and `endingHook` only through `endingHookEdits[]`. Each edit is `{ "find": "an exact unique excerpt copied verbatim from the current field", "replace": "the complete corrected excerpt" }`. Use the shortest excerpt that is still unique, normally one sentence or clause. The server rejects a missing or repeated `find`, so copy punctuation and whitespace exactly. To insert text, include a nearby unique sentence in both `find` and `replace`; to delete text, use an empty `replace`. Apply no more than 12 replacements per field. Never put a full stored summary, protagonist arc, or synopsis in `find` or `replace`: that recreates the wholesale-rewrite failure this contract prevents. A short one-clause `endingHook` may be matched whole when no smaller unique excerpt exists. Short fields such as title/logline/themes/count may still be returned directly when a finding names them.11. **Within an edited record, return only the fields that must change.** A character arc patch must repeat its existing `characterId` (or exact `characterName` when it has no ID), then include only changed top-level fields and changed transitions. Every transition patch must repeat its existing `id`; omit untouched transitions. To remove a transition that is itself the contradiction, return its `id` plus `"delete": true`. Omit every untouched key instead of paraphrasing the stored value "for completeness". The server preserves omitted fields and IDs. This field-level sparsity is load-bearing: rewriting an unrelated field can create the next round's contradiction even when the targeted finding was fixed.-12. **Stay inside the measured field budgets and end every replacement cleanly.** Hard limits are: arc logline 500 characters; arc summary 8,000; protagonist arc 4,000; volume logline 500; volume synopsis 8,000; volume ending hook 1,000. Use the exact `current` / `max` / `remaining` values above: for each field, the combined replacement delta (`replace.length - find.length`) must not exceed `remaining`. Prefer a shorter correction or delete redundant wording nearby when the field has little headroom. Every `replace` must end at a complete clause or sentence. Never rely on the server to truncate prose. Keep a volume synopsis near 200 words when that can carry the issue allocation; expand only as much as the finding genuinely requires.+12. **Stay inside the measured field budgets and end every replacement cleanly.** Hard limits are: arc logline 500 characters; arc summary 8,000; protagonist arc 4,000; volume logline 500; volume synopsis 8,000; volume ending hook 1,000; episode synopsis 4,000. Use the exact `current` / `max` / `remaining` values above: for each field, the combined replacement delta (`replace.length - find.length`) must not exceed `remaining`. Prefer a shorter correction or delete redundant wording nearby when the field has little headroom. Every `replace` must end at a complete clause or sentence. Never rely on the server to truncate prose. Keep a volume synopsis near 200 words when that can carry the issue allocation, and an episode synopsis roughly 150–300 words; expand only as much as the finding genuinely requires.## Output contractdiff --git a/data.reference/prompts/stages/pipeline-arc-verify.md b/data.reference/prompts/stages/pipeline-arc-verify.mdindex 38ac5de98f..afc34e0a19 100644--- a/data.reference/prompts/stages/pipeline-arc-verify.md+++ b/data.reference/prompts/stages/pipeline-arc-verify.md@@ -120,6 +120,27 @@ Score each volume + each episode against the arc. Specifically check:- resource quantities, deadlines, extensions, and who approves them;- the issue/episode where each irreversible character choice happens, so a milestone is neither spent early nor repeated;- issue/episode load, so independent climaxes have room for setup, resistance, choice, and consequence.+10. **Dramatic economy.** Once episodes exist, each synopsis needs a concrete+ goal, obstacle, consequential choice, and changed situation. Flag a plan+ dominated by permissions, ledgers, clauses, exceptions, or repeated+ statements of what nobody may do. Procedural precision can support a turn;+ it is not a substitute for one. Adjacent episodes must not resolve the same+ conflict by making another authority relinquish control.+11. **Planning altitude and metadata fit.** An episode synopsis is a drafting+ seed, not a near-manuscript or a running continuity appendix. Roughly+ 150–300 words is usually enough; above 450 words is a medium concern unless+ the episode demonstrably needs the complexity, and above 700 is high. Flag+ append-only caveats, duplicated facts, or minor procedures that bury the+ dramatic turn. The title, `arcRole`, and `lengthProfile` must describe what+ the episode actually does — especially pilot, midpoint, all-is-lost, and+ finale labels. The numeric `pageTarget` and `minutesTarget` are the+ materialized scope for both presets and custom profiles; judge whether the+ planned action can actually fill that space without padding or compression.+12. **Premise-engine continuity.** Track every major quest or promise in the+ originating premise across the whole series. A survival, rescue, romance,+ or institutional subplot must not silently erase a co-equal search, mystery,+ relationship, or personal need. The finale may defer an engine only through+ a visible choice that preserves a credible next step or payoff.## Output contractdiff --git a/data.reference/prompts/stages/pipeline-volume-verify.md b/data.reference/prompts/stages/pipeline-volume-verify.mdindex e204ad2448..aa72cee1da 100644--- a/data.reference/prompts/stages/pipeline-volume-verify.md+++ b/data.reference/prompts/stages/pipeline-volume-verify.md@@ -103,8 +103,28 @@ Walk the volume in issue / episode order. Score each issue against the volume's7. **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).+10. **Dramatic economy.** Each synopsis needs a concrete goal, obstacle,+ consequential choice, and changed situation. Flag issues dominated by+ permissions, ledgers, clauses, exceptions, or repeated statements of what+ nobody may do. Procedure can sharpen a conflict; it cannot replace action+ and choice. Adjacent issues should not solve the same dramatic problem with+ cosmetically different rules.+11. **Planning altitude and metadata fit.** A synopsis is a compact drafting+ seed. Roughly 150–300 words is usually enough; above 450 words is a medium+ concern unless the issue truly carries unusual complexity, and above 700 is+ high. Flag append-only continuity caveats, duplicated facts, and minor+ procedure that buries the turn. The title, `arcRole`, and `lengthProfile`+ must match the issue's actual function. The numeric `pageTarget` and+ `minutesTarget` are the materialized scope for both presets and custom+ profiles; judge whether the planned action fits that space without padding+ or compression.+12. **Active story engines.** Every major quest or promise active at the start+ of this volume must advance, be consciously traded off, or receive a clear+ deferral beat before the ending. A louder survival or institutional plot+ must not make a co-equal search, mystery, relationship, or personal need+ disappear between issues.++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) and #12 solely to identify engines explicitly established as active in the supplied full-arc or volume-entry context. Do not judge a payoff scheduled for a later volume.## Output contractdiff --git a/scripts/migrations/005-shape-aware-arc-prompts.js b/scripts/migrations/005-shape-aware-arc-prompts.jsindex 5b2be95590..a235cd74e9 100644--- a/scripts/migrations/005-shape-aware-arc-prompts.js+++ b/scripts/migrations/005-shape-aware-arc-prompts.js@@ -52,10 +52,10 @@ export const ACCEPTED_OLD_MD5 = {export const NEW_SHIPPED_MD5 = {'pipeline-arc-overview.md': '5ed760caaf3cf88916ec28b220e2f590', // post-250 arc spine checkpoint- 'pipeline-arc-verify.md': '9f32e91bd33b97d30e1cbb2e697f4fc3', // post-263 world category canon- 'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940', // post-019+ 'pipeline-arc-verify.md': 'a397f158fd9c0dca1c8dbe62df253f70', // post-274 planning economy+ 'pipeline-volume-verify.md': '9c0839d7fe1760c0891464afd4a3b8fd', // post-274 planning economy'pipeline-season-episodes.md': 'a88e8e78a949b7aaf500d03314e2ea0b', // post-172 (structure rules)- 'pipeline-arc-resolve.md': 'aa2e463ebe0857859d79aa0c6ccb0256', // post-267 (character-arc budgets)+ 'pipeline-arc-resolve.md': '638b988c84b3e5599f7a2ce09fa149ce', // post-274 planning economy};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/019-arc-volume-prompts-canon-context.js b/scripts/migrations/019-arc-volume-prompts-canon-context.jsindex 0ca80e3bdc..79bcf02edc 100644--- a/scripts/migrations/019-arc-volume-prompts-canon-context.js+++ b/scripts/migrations/019-arc-volume-prompts-canon-context.js@@ -63,9 +63,9 @@ export const ACCEPTED_OLD_MD5 = {export const NEW_SHIPPED_MD5 = {'pipeline-arc-overview.md': '5ed760caaf3cf88916ec28b220e2f590', // post-250 arc spine checkpoint- 'pipeline-arc-verify.md': '9f32e91bd33b97d30e1cbb2e697f4fc3', // post-263 world category canon- 'pipeline-arc-resolve.md': 'aa2e463ebe0857859d79aa0c6ccb0256', // post-267 (character-arc budgets)- 'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940', // post-019+ 'pipeline-arc-verify.md': 'a397f158fd9c0dca1c8dbe62df253f70', // post-274 planning economy+ 'pipeline-arc-resolve.md': '638b988c84b3e5599f7a2ce09fa149ce', // post-274 planning economy+ 'pipeline-volume-verify.md': '9c0839d7fe1760c0891464afd4a3b8fd', // post-274 planning economy};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/023-resolve-prompt-episode-anchor.js b/scripts/migrations/023-resolve-prompt-episode-anchor.jsindex fbe4bc681b..338b42c153 100644--- a/scripts/migrations/023-resolve-prompt-episode-anchor.js+++ b/scripts/migrations/023-resolve-prompt-episode-anchor.js@@ -39,7 +39,7 @@ export const ACCEPTED_OLD_MD5 = {// drift-catch test stays green against the live data.reference sample; a fresh// install at the pre-123 hash still advances cleanly via the accepted-OLD list.export const NEW_SHIPPED_MD5 = {- 'pipeline-arc-resolve.md': 'aa2e463ebe0857859d79aa0c6ccb0256', // post-267 (character-arc budgets)+ 'pipeline-arc-resolve.md': '638b988c84b3e5599f7a2ce09fa149ce', // post-274 planning economy};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/123-arc-resolve-episode-corrections.js b/scripts/migrations/123-arc-resolve-episode-corrections.jsindex c31ab69f5a..fcaf1e5ad2 100644--- a/scripts/migrations/123-arc-resolve-episode-corrections.js+++ b/scripts/migrations/123-arc-resolve-episode-corrections.js@@ -28,7 +28,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-arc-resolve.md': 'aa2e463ebe0857859d79aa0c6ccb0256', // post-267 (character-arc budgets)+ 'pipeline-arc-resolve.md': '638b988c84b3e5599f7a2ce09fa149ce', // post-274 planning economy};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/245-arc-resolve-finding-keyed-patches.js b/scripts/migrations/245-arc-resolve-finding-keyed-patches.jsindex 5b23f22a31..8420b4eac3 100644--- a/scripts/migrations/245-arc-resolve-finding-keyed-patches.js+++ b/scripts/migrations/245-arc-resolve-finding-keyed-patches.js@@ -28,7 +28,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-arc-resolve.md': 'aa2e463ebe0857859d79aa0c6ccb0256', // post-267 (character-arc budgets)+ 'pipeline-arc-resolve.md': '638b988c84b3e5599f7a2ce09fa149ce', // post-274 planning economy};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/250-arc-spine-checkpoint-prompts.js b/scripts/migrations/250-arc-spine-checkpoint-prompts.jsindex b210f6e99f..58f91819cd 100644--- a/scripts/migrations/250-arc-spine-checkpoint-prompts.js+++ b/scripts/migrations/250-arc-spine-checkpoint-prompts.js@@ -18,7 +18,7 @@ export const ACCEPTED_OLD_MD5 = {export const NEW_SHIPPED_MD5 = {'pipeline-arc-overview.md': '5ed760caaf3cf88916ec28b220e2f590',- 'pipeline-arc-verify.md': '9f32e91bd33b97d30e1cbb2e697f4fc3', // post-263 world category canon+ 'pipeline-arc-verify.md': 'a397f158fd9c0dca1c8dbe62df253f70', // post-274 planning economy};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/251-arc-resolve-field-sparsity.js b/scripts/migrations/251-arc-resolve-field-sparsity.jsindex 35d7f1bcb2..2237ac0822 100644--- a/scripts/migrations/251-arc-resolve-field-sparsity.js+++ b/scripts/migrations/251-arc-resolve-field-sparsity.js@@ -12,7 +12,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-arc-resolve.md': 'aa2e463ebe0857859d79aa0c6ccb0256', // post-267 (character-arc budgets)+ 'pipeline-arc-resolve.md': '638b988c84b3e5599f7a2ce09fa149ce', // post-274 planning economy};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/252-arc-resolve-avoid-list.js b/scripts/migrations/252-arc-resolve-avoid-list.jsindex dfb6536087..7e79e8df6a 100644--- a/scripts/migrations/252-arc-resolve-avoid-list.js+++ b/scripts/migrations/252-arc-resolve-avoid-list.js@@ -14,7 +14,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-arc-resolve.md': 'aa2e463ebe0857859d79aa0c6ccb0256', // post-267 (character-arc budgets)+ 'pipeline-arc-resolve.md': '638b988c84b3e5599f7a2ce09fa149ce', // post-274 planning economy};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/253-arc-resolve-spine-scope.js b/scripts/migrations/253-arc-resolve-spine-scope.jsindex 2bc2312c70..f8d739a7e6 100644--- a/scripts/migrations/253-arc-resolve-spine-scope.js+++ b/scripts/migrations/253-arc-resolve-spine-scope.js@@ -16,7 +16,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-arc-resolve.md': 'aa2e463ebe0857859d79aa0c6ccb0256', // post-267 (character-arc budgets)+ 'pipeline-arc-resolve.md': '638b988c84b3e5599f7a2ce09fa149ce', // post-274 planning economy};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/254-arc-resolve-character-arcs.js b/scripts/migrations/254-arc-resolve-character-arcs.jsindex 1114889f38..cb3cfdee51 100644--- a/scripts/migrations/254-arc-resolve-character-arcs.js+++ b/scripts/migrations/254-arc-resolve-character-arcs.js@@ -15,7 +15,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-arc-resolve.md': 'aa2e463ebe0857859d79aa0c6ccb0256',+ 'pipeline-arc-resolve.md': '638b988c84b3e5599f7a2ce09fa149ce',};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/258-arc-resolve-exact-text-patches.js b/scripts/migrations/258-arc-resolve-exact-text-patches.jsindex 3f026331d9..b06175f7c0 100644--- a/scripts/migrations/258-arc-resolve-exact-text-patches.js+++ b/scripts/migrations/258-arc-resolve-exact-text-patches.js@@ -14,7 +14,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-arc-resolve.md': 'aa2e463ebe0857859d79aa0c6ccb0256',+ 'pipeline-arc-resolve.md': '638b988c84b3e5599f7a2ce09fa149ce',};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/259-arc-resolve-text-budgets.js b/scripts/migrations/259-arc-resolve-text-budgets.jsindex 5d11f6c43b..918f1093ef 100644--- a/scripts/migrations/259-arc-resolve-text-budgets.js+++ b/scripts/migrations/259-arc-resolve-text-budgets.js@@ -11,7 +11,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-arc-resolve.md': 'aa2e463ebe0857859d79aa0c6ccb0256',+ 'pipeline-arc-resolve.md': '638b988c84b3e5599f7a2ce09fa149ce',};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/260-arc-resolve-isolated-repairs.js b/scripts/migrations/260-arc-resolve-isolated-repairs.jsindex 5431fa0aac..84d4f1069b 100644--- a/scripts/migrations/260-arc-resolve-isolated-repairs.js+++ b/scripts/migrations/260-arc-resolve-isolated-repairs.js@@ -17,7 +17,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-arc-resolve.md': 'aa2e463ebe0857859d79aa0c6ccb0256',+ 'pipeline-arc-resolve.md': '638b988c84b3e5599f7a2ce09fa149ce',};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/261-exhaustive-arc-verification.js b/scripts/migrations/261-exhaustive-arc-verification.jsindex e4538c8ebc..87306d0d64 100644--- a/scripts/migrations/261-exhaustive-arc-verification.js+++ b/scripts/migrations/261-exhaustive-arc-verification.js@@ -20,7 +20,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-arc-verify.md': '9f32e91bd33b97d30e1cbb2e697f4fc3', // post-263 world category canon+ 'pipeline-arc-verify.md': 'a397f158fd9c0dca1c8dbe62df253f70', // post-274 planning economy};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/263-arc-verify-world-category-canon.js b/scripts/migrations/263-arc-verify-world-category-canon.jsindex 430223d870..af87238874 100644--- a/scripts/migrations/263-arc-verify-world-category-canon.js+++ b/scripts/migrations/263-arc-verify-world-category-canon.js@@ -26,7 +26,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-arc-verify.md': '9f32e91bd33b97d30e1cbb2e697f4fc3',+ 'pipeline-arc-verify.md': 'a397f158fd9c0dca1c8dbe62df253f70',};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/267-arc-resolve-character-arc-budgets.js b/scripts/migrations/267-arc-resolve-character-arc-budgets.jsindex cdf0297459..878be2653d 100644--- a/scripts/migrations/267-arc-resolve-character-arc-budgets.js+++ b/scripts/migrations/267-arc-resolve-character-arc-budgets.js@@ -17,7 +17,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-arc-resolve.md': 'aa2e463ebe0857859d79aa0c6ccb0256',+ 'pipeline-arc-resolve.md': '638b988c84b3e5599f7a2ce09fa149ce',};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/275-pipeline-planning-economy.js b/scripts/migrations/275-pipeline-planning-economy.jsnew file mode 100644index 0000000000..99acd7994b--- /dev/null+++ b/scripts/migrations/275-pipeline-planning-economy.js@@ -0,0 +1,46 @@+/**+ * Keep arc verification and repair at episode-planning altitude.+ *+ * Continuity repair used the 200k generic stage-input ceiling even though+ * episode generation capped a synopsis at 4k. Repeated verifier rounds could+ * therefore grow a concise drafting seed into a procedural near-manuscript,+ * while the judges had no explicit dramatic-economy or synopsis-size check.+ * Publish the new shared budget and the goal/obstacle/choice/consequence,+ * metadata-fit, and premise-engine checks to customized installs.+ */++import { makePromptReplaceMigration } from './_lib.js';++export const ACCEPTED_OLD_MD5 = {+ 'pipeline-arc-resolve.md': ['aa2e463ebe0857859d79aa0c6ccb0256'],+ 'pipeline-arc-verify.md': [+ '9f32e91bd33b97d30e1cbb2e697f4fc3',+ '90712f66ec68061ebed2147044e5baee',+ ],+ 'pipeline-volume-verify.md': [+ '49458d36700cb94e34806d536ffe2940',+ '3e8a8f00d5faaee9d8e08a49d801b812',+ ],+};++export const NEW_SHIPPED_MD5 = {+ 'pipeline-arc-resolve.md': '638b988c84b3e5599f7a2ce09fa149ce',+ 'pipeline-arc-verify.md': 'a397f158fd9c0dca1c8dbe62df253f70',+ 'pipeline-volume-verify.md': '9c0839d7fe1760c0891464afd4a3b8fd',+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'pipeline planning economy',+ customizedHint: (filename) => filename === 'pipeline-arc-resolve.md'+ ? ` To upgrade it manually, diff data.reference/prompts/stages/${filename}\n` ++ ` against data/prompts/stages/${filename}, enforce the shared 4,000-character\n` ++ ` episode-synopsis budget, and replace or compact conflicting language instead of appending.\n`+ : ` To upgrade it manually, diff data.reference/prompts/stages/${filename}\n` ++ ` against data/prompts/stages/${filename} and add the planning-altitude,\n` ++ ` dramatic-economy, metadata-fit, and premise-engine rules.`,+});++export { applyMigration };+export default { up };diff --git a/scripts/migrations/275-pipeline-planning-economy.test.js b/scripts/migrations/275-pipeline-planning-economy.test.jsnew file mode 100644index 0000000000..c89ec0968e--- /dev/null+++ b/scripts/migrations/275-pipeline-planning-economy.test.js@@ -0,0 +1,68 @@+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { repoRoot, runPromptMigrationTests } from './_testHelpers.js';+import migration, {+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ applyMigration,+} from './275-pipeline-planning-economy.js';++describe('migration 275 — pipeline planning economy', () => {+ let warningRoot = null;++ afterEach(() => {+ vi.restoreAllMocks();+ if (warningRoot) rmSync(warningRoot, { recursive: true, force: true });+ warningRoot = null;+ });++ runPromptMigrationTests({+ migration,+ applyMigration,+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ prefix: 'migration-275-pipeline-planning-economy-',+ });++ it('publishes the episode budget and dramatic-economy checks', () => {+ const read = (name) => readFileSync(+ `${repoRoot}/data.reference/prompts/stages/${name}`,+ 'utf8',+ );+ const resolver = read('pipeline-arc-resolve.md');+ const arcVerify = read('pipeline-arc-verify.md');+ const volumeVerify = read('pipeline-volume-verify.md');++ expect(resolver).toContain('episode synopsis 4,000');+ expect(resolver).toContain('replace or compact conflicting language');+ for (const prompt of [arcVerify, volumeVerify]) {+ expect(prompt).toContain('Dramatic economy');+ expect(prompt).toContain('Planning altitude and metadata fit');+ expect(prompt).toMatch(/goal, obstacle,[\s\S]*consequential choice/);+ }+ expect(arcVerify).toContain('Premise-engine continuity');+ expect(volumeVerify).toContain('Active story engines');+ });++ it('gives customized resolver owners the resolver-specific manual upgrade', async () => {+ warningRoot = mkdtempSync(join(tmpdir(), 'migration-275-customized-warning-'));+ const stagesDir = join(warningRoot, 'data', 'prompts', 'stages');+ mkdirSync(stagesDir, { recursive: true });+ for (const filename of Object.keys(NEW_SHIPPED_MD5)) {+ writeFileSync(join(stagesDir, filename), `# customized ${filename}\n`);+ }+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ await migration.up({ rootDir: warningRoot });++ const resolverWarning = warn.mock.calls+ .map(([message]) => String(message))+ .find((message) => message.includes('pipeline-arc-resolve.md'));+ expect(resolverWarning).toContain('4,000-character');+ expect(resolverWarning).toContain('replace or compact');+ expect(resolverWarning).toContain('instead of appending');+ });+});diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.jsindex 6fe5af93ff..42a9a34279 100644--- a/scripts/setup-data-drift.test.js+++ b/scripts/setup-data-drift.test.js@@ -31,9 +31,9 @@ const EXPECTED_STAGE_OLD = {'pipeline-teleplay.md': ['1280ef6b1ad68fa44070ca7478ec2a5f', '2568e14beaa574d43f8018a5def51d04', '376f779f4687b598f1c92ca4e770fd5a', '3f6fecc25573ed054b47db392250034a', 'afa4215330bf856429d70d7e2f856605'],'pipeline-season-episodes.md': ['6e349ad26bed8a0ccb042571f03f03eb', 'c4928e2a5f833358116b29d2d669888d', '50c68a29c3ebc275db3095d06bd87100'],'pipeline-arc-overview.md': ['6a3ecab43d1f46b7ef9aab6c69ea0326', 'd34d72b8e49ba303d38607845dd87f1c', '0a1f6ffa6908522e3690c5e9e53a6ee0', '612f8b04950e2ff26dd350dd76a062fe', '74d6c26548660d85fc345b2099c63b6c', '648e11352cd1565aee490de1f662bef0'],- 'pipeline-arc-verify.md': ['52e31abc93e3105176236fcaa5d1575a', 'ff56d8387162017e08d5d0491060ddd6', '36aa70cdfc25d7549573a4d556e7702c', '83347e7d923580a3062033ab39b3c14b', '68f6956d7e09ebdb3870d8726b1b2a7a'],- 'pipeline-volume-verify.md': ['03f3c874cb80e1c98abcf03168fa7a92', 'c6ea28e972ad6e229bafb2d602b4dda3'],- 'pipeline-arc-resolve.md': ['0611db539437083621e19bb88b005e8d', '0787128babf3c4c50e2f2cdb60214030', '5b340885c6e8f8afc63424d6b5bc7eb7', '87bc5c01f1a8a97b681727a38b05edc6', '8bb134554c122d1583c479ab3010e53d', '8e348f3d1894382889f9f0ee7d5c6792', '96f73a7e90526d65ef2bb100fb1cd4bf', 'a8677bbe1eb38f871fb152a5b0fec7c6', 'cc27b4da1d1a13c35e35d1c2d6183815', '31eca76b68f40de1b93734fe9bc9f4bb', '17fbb066d7957dc2e345df1795bb0d9d', 'ebd85d3a0b5949f16877c25ca498cce9', '2349bce80e9df8caafa391a6106327b6'],+ 'pipeline-arc-verify.md': ['52e31abc93e3105176236fcaa5d1575a', 'ff56d8387162017e08d5d0491060ddd6', '36aa70cdfc25d7549573a4d556e7702c', '83347e7d923580a3062033ab39b3c14b', '68f6956d7e09ebdb3870d8726b1b2a7a', '9f32e91bd33b97d30e1cbb2e697f4fc3', '90712f66ec68061ebed2147044e5baee'],+ 'pipeline-volume-verify.md': ['03f3c874cb80e1c98abcf03168fa7a92', 'c6ea28e972ad6e229bafb2d602b4dda3', '49458d36700cb94e34806d536ffe2940', '3e8a8f00d5faaee9d8e08a49d801b812'],+ 'pipeline-arc-resolve.md': ['0611db539437083621e19bb88b005e8d', '0787128babf3c4c50e2f2cdb60214030', '5b340885c6e8f8afc63424d6b5bc7eb7', '87bc5c01f1a8a97b681727a38b05edc6', '8bb134554c122d1583c479ab3010e53d', '8e348f3d1894382889f9f0ee7d5c6792', '96f73a7e90526d65ef2bb100fb1cd4bf', 'a8677bbe1eb38f871fb152a5b0fec7c6', 'cc27b4da1d1a13c35e35d1c2d6183815', '31eca76b68f40de1b93734fe9bc9f4bb', '17fbb066d7957dc2e345df1795bb0d9d', 'ebd85d3a0b5949f16877c25ca498cce9', '2349bce80e9df8caafa391a6106327b6', 'aa2e463ebe0857859d79aa0c6ccb0256'],'pipeline-script-verify.md': ['ed6c8101644cfe56a100eb6bfe3587f3'],'pipeline-extract-scenes.md': ['59fa5ee305ce53d91eb15224d8b546d3', 'c51fb208568d0d903eb43b437478b0ba'],'writers-room-places.md': ['24a33628cc94d80fa5ca60831d973daf', '7f1f80eb63d67a21161994cde115045e'],@@ -63,9 +63,9 @@ const EXPECTED_STAGE_NEW = {'pipeline-teleplay.md': '2ea9974ac3803658b2314db1f5818b77','pipeline-season-episodes.md': 'a88e8e78a949b7aaf500d03314e2ea0b','pipeline-arc-overview.md': '5ed760caaf3cf88916ec28b220e2f590',- 'pipeline-arc-verify.md': '9f32e91bd33b97d30e1cbb2e697f4fc3',- 'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940',- 'pipeline-arc-resolve.md': 'aa2e463ebe0857859d79aa0c6ccb0256',+ 'pipeline-arc-verify.md': 'a397f158fd9c0dca1c8dbe62df253f70',+ 'pipeline-volume-verify.md': '9c0839d7fe1760c0891464afd4a3b8fd',+ 'pipeline-arc-resolve.md': '638b988c84b3e5599f7a2ce09fa149ce','pipeline-script-verify.md': '722c62462d05462603cf67ca0ed1dee8','pipeline-extract-scenes.md': '9f404b0c4721b23932a6d2dcfc1fba43','writers-room-places.md': 'a7f68e51dd6b4421d20f5bd9d855d9b4',diff --git a/server/lib/storyArc.js b/server/lib/storyArc.jsindex e3604ba05c..7bf9a011bc 100644--- a/server/lib/storyArc.js+++ b/server/lib/storyArc.js@@ -41,6 +41,13 @@ export const ARC_LIMITS = Object.freeze({SEASON_NUMBER_MAX: 99,SEASON_EPISODE_COUNT_MAX: 999,SEASONS_PER_SERIES_MAX: 50,+ // One issue/episode planning synopsis. This is deliberately smaller than a+ // whole-volume synopsis: it is a drafting seed, not a place to accumulate+ // every continuity exception the verifier has ever raised. Keep the value in+ // the shared arc limits so initial episode generation and later arc repairs+ // cannot silently disagree about how much text one episode may own.+ EPISODE_LOGLINE_MAX: 500,+ EPISODE_SYNOPSIS_MAX: 4000,});export const ARC_STATUSES = Object.freeze(['draft', 'verified']);diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.jsindex 0c9b34fb5b..11cd223501 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -393,6 +393,34 @@ describe('arcPlanner — generateSeasonEpisodes', () => {expect(out.episodes[1].primaryCharacters).toEqual(['LINA']); // non-string + blank entries filtered});+ it('keeps generated episode synopses within the shared planning budget at a clause boundary', async () => {+ const { series, seasons } = await setupSeriesWithSeasons();+ const overlong = `${'A consequential setup. '.repeat(220)}This tail must be removed`;+ stageRunnerSpy = vi.fn(async () => ({+ content: { episodes: [{ number: 1, title: 'Budgeted', synopsis: overlong, arcRole: 'pilot' }] },+ runId: 'r1', providerId: 'p', model: 'm',+ }));++ const out = await planner.generateSeasonEpisodes(series.id, seasons[0].id);+ expect(out.episodes[0].synopsis.length).toBeLessThanOrEqual(4_000);+ expect(out.episodes[0].synopsis).toMatch(/[.!?]$/);+ expect(out.episodes[0].synopsis).not.toContain('This tail must be removed');+ });++ it('keeps generated episode loglines within their budget at a word boundary', async () => {+ const { series, seasons } = await setupSeriesWithSeasons();+ const overlong = `${'A consequential choice changes the pursuit without ending it. '.repeat(12)}consequence`;+ stageRunnerSpy = vi.fn(async () => ({+ content: { episodes: [{ number: 1, title: 'Budgeted', logline: overlong, arcRole: 'pilot' }] },+ runId: 'r1', providerId: 'p', model: 'm',+ }));++ const out = await planner.generateSeasonEpisodes(series.id, seasons[0].id);+ expect(out.episodes[0].logline.length).toBeLessThanOrEqual(500);+ expect(overlong.split(' ')).toContain(out.episodes[0].logline.split(' ').pop());+ expect(out.episodes[0].logline).not.toMatch(/conseque$/);+ });+it('rejects the `custom` length sentinel and derives a finale-role fallback to `finale`', async () => {const { series, seasons } = await setupSeriesWithSeasons();stageRunnerSpy = vi.fn(async () => ({@@ -2248,6 +2276,16 @@ describe('arcPlanner — shapeEpisodeResolutions', () => {const many = Array.from({ length: 60 }, (_, i) => ({ episodeNumber: i + 1, synopsis: `s${i}` }));expect(planner.shapeEpisodeResolutions(many)).toHaveLength(50);});++ it('cannot inflate a repaired episode beyond the generation synopsis budget', () => {+ const overlong = `${'One complete dramatic sentence. '.repeat(180)}unfinished tail`;+ const [episode] = planner.shapeEpisodeResolutions([+ { seasonNumber: 1, episodeNumber: 4, synopsis: overlong },+ ]);+ expect(episode.synopsis.length).toBeLessThanOrEqual(4_000);+ expect(episode.synopsis).toMatch(/[.!?]$/);+ expect(episode.synopsis).not.toContain('unfinished tail');+ });});describe('arcPlanner — resolvedEpisodeEdits (rollback mutation manifest)', () => {@@ -3312,6 +3350,27 @@ describe('arcPlanner — refineArc', () => {});describe('arcPlanner — manuscript completeness + derive-from-manuscript', () => {+ it('fingerprints manuscript completeness context canonically and includes narrative references', () => {+ const initial = {+ manuscript: 'A short draft.',+ series: { premise: 'An alliance must hold.', name: 'Example' },+ arc: { summary: 'The alliance survives.' },+ existingCharactersJson: '[{"name":"Ari"}]',+ };+ const reordered = {+ existingCharactersJson: '[{"name":"Ari"}]',+ arc: { summary: 'The alliance survives.' },+ series: { name: 'Example', premise: 'An alliance must hold.' },+ manuscript: 'A short draft.',+ };++ expect(planner.completenessSourceHash(reordered)).toBe(planner.completenessSourceHash(initial));+ expect(planner.completenessSourceHash({+ ...initial,+ arc: { summary: 'The alliance shatters.' },+ })).not.toBe(planner.completenessSourceHash(initial));+ });+beforeEach(() => {fileStore.clear();uuidCounter = 0;@@ -3384,6 +3443,7 @@ describe('arcPlanner — manuscript completeness + derive-from-manuscript', () =});const out = await planner.analyzeManuscriptCompleteness(s.id, { withEdits: true });expect(out.issues[0].replace).toBe('She left, but paused.');+ expect(out.issues[0].sourceContentHash).toMatch(/^[a-f0-9]{64}$/);});it('analyzeManuscriptCompleteness defaults withEdits false (ctx.withEdits=false, no replace shaped)', async () => {diff --git a/server/services/pipeline/arcPlanner/completenessPass.js b/server/services/pipeline/arcPlanner/completenessPass.jsindex 8805b274d9..6fcaf72cf5 100644--- a/server/services/pipeline/arcPlanner/completenessPass.js+++ b/server/services/pipeline/arcPlanner/completenessPass.js@@ -3,6 +3,7 @@* (findings + optional edit generation). Built on ./context.js.*/+import { createHash } from 'crypto';import { resolveStageContext, runStagedLLM } from '../../../lib/stageRunner.js';import {estimateTokens, planManuscriptPass, fitContextToManuscriptFloor,@@ -11,6 +12,7 @@ import {import { getSeries } from '../series.js';import { STAGE_OUTPUT_MAX } from '../issues.js';import { getSeriesCanon } from '../seriesCanon.js';+import { canonicalStringify } from '../../../lib/objects.js';import { ERR_VALIDATION, MANUSCRIPT_STAGES, VERIFY_SEVERITIES, buildArcBaseContext, collectManuscriptSections, makeErr, manuscriptSectionHeader, sectionsCorpus } from './context.js';// ── Manuscript completeness ("finish the draft") ──────────────────────────@@ -43,7 +45,7 @@ export const replacementStrategyForCategory = (category) =>// the fix path's per-edit replace ceiling so a long page rewrite isn't clipped.export const COMPLETENESS_REPLACE_MAX = STAGE_OUTPUT_MAX;-export function shapeCompletenessFindings(rawIssues, { withEdits = false } = {}) {+export function shapeCompletenessFindings(rawIssues, { withEdits = false, sourceContentHash = null } = {}) {if (!Array.isArray(rawIssues)) return [];const out = [];for (const raw of rawIssues) {@@ -68,6 +70,7 @@ export function shapeCompletenessFindings(rawIssues, { withEdits = false } = {})// un-anchorable findings still render (just without click-to-jump).issueNumber: Number.isInteger(raw?.issueNumber) ? raw.issueNumber : null,anchorQuote: typeof raw?.anchorQuote === 'string' ? raw.anchorQuote.trim().slice(0, 400) : '',+ ...(sourceContentHash ? { sourceContentHash } : {}),};// With-edits pass: carry the concrete in-place rewrite so the editor can seed// each comment's `fix` from { find: anchorQuote, replace } without a separate@@ -96,6 +99,15 @@ export async function buildCompletenessContext(series, manuscript, preloadedWorl};}+// Completeness advice depends on every reference projection the model sees,+// not just the manuscript. Hash the complete, untrimmed context deterministically+// so an arc, premise, world, or canon edit makes prior advice stale even when the+// drafted pages themselves have not changed. The read path rebuilds this same+// context and calls this one helper, preventing seed/read fingerprint drift.+export const completenessSourceHash = (context) => createHash('sha256')+ .update(canonicalStringify(context ?? {}) || '')+ .digest('hex');+export const COMPLETENESS_STAGE = 'pipeline-manuscript-completeness';// Output room for the findings list; comic-structure suggestions are full page@@ -208,7 +220,6 @@ export async function analyzeManuscriptCompleteness(seriesId, options = {}) {ERR_VALIDATION,);}-const withEdits = !!options.withEdits;const onProgress = typeof options.onProgress === 'function' ? options.onProgress : () => {};const signal = options.signal || null;@@ -220,6 +231,10 @@ export async function analyzeManuscriptCompleteness(seriesId, options = {}) {// 1. hard-cap the canon reference (window-independent), then// 2. window-aware-trim it so the manuscript always keeps a budget floor.const baseCtx = await buildCompletenessContext(series, '', options.preloadedWorld);+ const sourceContentHash = completenessSourceHash({+ ...baseCtx,+ manuscript: sectionsCorpus(sections),+ });const { contextWindow } = await resolveStageContext(COMPLETENESS_STAGE, {providerOverride: options.providerOverride,providerDefault: options.providerDefault,@@ -277,7 +292,7 @@ export async function analyzeManuscriptCompleteness(seriesId, options = {}) {onProgress({ type: 'chunk:start', done: 0, total: 1 });const { content, runId, providerId, model } = await runOne(sectionsCorpus(sections).slice(0, plan.usableChars));onProgress({ type: 'chunk:complete', done: 1, total: 1 });- return { issues: shapeCompletenessFindings(content?.issues, { withEdits }), raw: content, runId, providerId, model, chunked: false, chunkCount: 1 };+ return { issues: shapeCompletenessFindings(content?.issues, { withEdits, sourceContentHash }), raw: content, runId, providerId, model, chunked: false, chunkCount: 1 };}console.log(`📚 completeness: chunked review series=${String(seriesId).slice(0, 12)} chunks=${plan.chunks.length} window=${contextWindow ?? 'floor'}`);@@ -295,7 +310,7 @@ export async function analyzeManuscriptCompleteness(seriesId, options = {}) {const corpus = sectionsCorpus(chunk.sections).slice(0, plan.usableChars);const result = await runOne(`${digest}${corpus}`);if (!first) first = result;- for (const f of shapeCompletenessFindings(result.content?.issues, { withEdits })) {+ for (const f of shapeCompletenessFindings(result.content?.issues, { withEdits, sourceContentHash })) {const k = findingKey(f);if (!merged.has(k)) merged.set(k, f);}diff --git a/server/services/pipeline/arcPlanner/context.js b/server/services/pipeline/arcPlanner/context.jsindex 26f9f4fa52..d40e8e8143 100644--- a/server/services/pipeline/arcPlanner/context.js+++ b/server/services/pipeline/arcPlanner/context.js@@ -10,10 +10,11 @@import { MANUSCRIPT_TYPES } from '../series.js';import { listIssues, STAGE_INPUT_MAX } from '../issues.js';import { ARC_LIMITS, ARC_ROLES as ARC_ROLE_LIST, ARC_SHAPE_IDS, READER_MAP_BEAT_KINDS, buildSeason, renderArcShapeGuidance, renderTickingClock, sanitizeSeasonList } from '../../../lib/storyArc.js';+import { trimToClause } from '../../../lib/storyBible.js';import { composeStyleNotes } from '../../../lib/styleGuide.js';import { CHARACTER_ARC_LIMITS, renderCharacterArcsForPrompt } from '../../../lib/seriesCharacterArc.js';import { describeStructure, recommendStructure } from '../../../lib/seasonStructure.js';-import { DEFAULT_LENGTH_PROFILE, LENGTH_PROFILE_NAMES } from '../../../lib/issueLength.js';+import { computeIssueTargets, DEFAULT_LENGTH_PROFILE, LENGTH_PROFILE_NAMES } from '../../../lib/issueLength.js';import { getUniverse } from '../../universeBuilder.js';import { getSeriesPlanningCanon, scopeCanonForSeries } from '../seriesCanon.js';import { renderCanonForPrompt, renderCategoriesForPrompt, renderCompositesForPrompt, renderEntitiesSummary } from '../../../lib/universePromptRenderers.js';@@ -521,14 +522,20 @@ export function groupIssuesBySeasonTree(seasons, issues, { renderLeaf, seasonFie//// `synopsis` (not `beats`) matches the prompt's existing language; it is sourced// from idea.input, which carries the LLM's logline+synopsis.-export const renderVerifyIssueLeaf = (iss) => ({- number: iss.number,- title: iss.title,- status: iss.status,- arcPosition: iss.arcPosition,- arcRole: iss.arcRole || null,- synopsis: (iss.stages?.idea?.input || '').trim() || null,-});+export const renderVerifyIssueLeaf = (iss) => {+ const targets = computeIssueTargets(iss);+ return {+ number: iss.number,+ title: iss.title,+ status: iss.status,+ arcPosition: iss.arcPosition,+ arcRole: iss.arcRole || null,+ lengthProfile: iss.lengthProfile || null,+ pageTarget: targets.pageTarget,+ minutesTarget: targets.minutesTarget,+ synopsis: (iss.stages?.idea?.input || '').trim() || null,+ };+};// The volume node the arc-verify prompt scores. Exported for the same contract// test as `renderVerifyIssueLeaf` — checks #3/#4/#7 read `endingHook`,@@ -613,7 +620,12 @@ export function shapeEpisodeResolutions(rawEpisodes) {out.push({seasonNumber: Number.isInteger(seasonNumberRaw) ? seasonNumberRaw : null,episodeNumber,- synopsis: synopsis.slice(0, STAGE_INPUT_MAX),+ // A resolver correction must obey the same episode-plan budget as the+ // generator that created the synopsis. The old STAGE_INPUT_MAX ceiling+ // (200k) let a sequence of continuity repairs turn a compact plan into a+ // near-manuscript. Boundary-aware trimming avoids manufacturing the+ // half-sentence that the next verification round would immediately flag.+ synopsis: trimToClause(synopsis, ARC_LIMITS.EPISODE_SYNOPSIS_MAX),});if (out.length >= RESOLVE_EPISODE_MAX) break;}@@ -633,11 +645,16 @@ export function shapeEpisodeResolutions(rawEpisodes) {export function renderVolumeIssue(iss, { synopsisOnly = false } = {}) {const beats = synopsisOnly ? '' : (iss.stages?.idea?.output || '').trim();const synopsis = (iss.stages?.idea?.input || '').trim();+ const targets = computeIssueTargets(iss);const base = {number: iss.number,title: iss.title,status: iss.status,arcPosition: iss.arcPosition,+ arcRole: iss.arcRole || null,+ lengthProfile: iss.lengthProfile || null,+ pageTarget: targets.pageTarget,+ minutesTarget: targets.minutesTarget,};if (beats) return { ...base, beats };return { ...base, synopsis: synopsis || null };diff --git a/server/services/pipeline/arcPlanner/episodeSeedPass.js b/server/services/pipeline/arcPlanner/episodeSeedPass.jsindex b9a535649e..30421d1cdd 100644--- a/server/services/pipeline/arcPlanner/episodeSeedPass.js+++ b/server/services/pipeline/arcPlanner/episodeSeedPass.js@@ -12,6 +12,8 @@ import { extractCanonFromProse } from '../../universeCanon.js';import { resolveSeriesLlmOverride } from '../../../lib/seriesLlmOverride.js';import { getSeriesPlanningCanon } from '../seriesCanon.js';import { ARC_ROLES, ERR_VALIDATION, SEASON_LENGTH_PRESETS, SHAPE_GUIDANCE_NONE, appendCharacterFirstArcGuidance, appendTickingClock, lengthProfileForArcRole, makeErr, renderPriorSeason, resolveWorldContext } from './context.js';+import { ARC_LIMITS } from '../../../lib/storyArc.js';+import { trimToClause } from '../../../lib/storyBible.js';/*** Build the context for one season's episode breakdown. `priorSeasonsContext`@@ -108,8 +110,8 @@ export function shapeEpisodes(rawEpisodes) {out.push({number,title,- logline: typeof raw?.logline === 'string' ? raw.logline.trim().slice(0, 500) : '',- synopsis: typeof raw?.synopsis === 'string' ? raw.synopsis.trim().slice(0, 4000) : '',+ logline: trimToClause(raw?.logline, ARC_LIMITS.EPISODE_LOGLINE_MAX),+ synopsis: trimToClause(raw?.synopsis, ARC_LIMITS.EPISODE_SYNOPSIS_MAX),primaryCharacters,arcRole,lengthProfile,diff --git a/server/services/pipeline/arcPlanner/verifyPromptContract.test.js b/server/services/pipeline/arcPlanner/verifyPromptContract.test.jsindex dcd9c1a847..adf265e397 100644--- a/server/services/pipeline/arcPlanner/verifyPromptContract.test.js+++ b/server/services/pipeline/arcPlanner/verifyPromptContract.test.js@@ -62,6 +62,19 @@ describe('pipeline-arc-verify prompt ↔ buildVerifyContext leaf contract', () =.filter((token) => !NON_FIELD_TOKENS.has(token) && !leafWithoutArcRole.has(token));expect(unrenderable).toEqual(['arcRole']);});++ it('materializes custom numeric targets for metadata-fit checks', () => {+ expect(renderVerifyIssueLeaf({+ lengthProfile: 'custom',+ pageTarget: 4,+ minutesTarget: 120,+ stages: {},+ })).toMatchObject({+ lengthProfile: 'custom',+ pageTarget: 4,+ minutesTarget: 120,+ });+ });});describe('pipeline-arc-verify ↔ pipeline-arc-resolve world parity', () => {diff --git a/server/services/pipeline/arcPlanner/volumeVerifyPromptContract.test.js b/server/services/pipeline/arcPlanner/volumeVerifyPromptContract.test.jsindex cf93be4215..4e0f1e72c1 100644--- a/server/services/pipeline/arcPlanner/volumeVerifyPromptContract.test.js+++ b/server/services/pipeline/arcPlanner/volumeVerifyPromptContract.test.js@@ -72,6 +72,10 @@ const SCOPED_CITATIONS = [['beats', 'issue leaf', issueLeafFields],['synopsis', 'issue leaf', issueLeafFields],['arcPosition', 'issue leaf', issueLeafFields],+ ['arcRole', 'issue leaf', issueLeafFields],+ ['lengthProfile', 'issue leaf', issueLeafFields],+ ['pageTarget', 'issue leaf', issueLeafFields],+ ['minutesTarget', 'issue leaf', issueLeafFields],// Checks #1/#4/#5 read these off the volume node.['logline', 'volume node', volumeNodeFields],['synopsis', 'volume node', volumeNodeFields],@@ -157,17 +161,34 @@ describe('renderVolumeIssue depth selection', () => {it('renders beats (and never synopsis) once the expand pass has run', () => {expect(renderVolumeIssue(issue)).toEqual({- number: 4, title: 'Example Issue', status: 'draft', arcPosition: 4, beats: 'beat sheet',+ number: 4, title: 'Example Issue', status: 'draft', arcPosition: 4,+ arcRole: null, lengthProfile: null, pageTarget: 22, minutesTarget: 24,+ beats: 'beat sheet',});});it('renders synopsis (and never beats) when synopsisOnly is requested', () => {expect(renderVolumeIssue(issue, { synopsisOnly: true })).toEqual({- number: 4, title: 'Example Issue', status: 'draft', arcPosition: 4, synopsis: 'seed synopsis',+ number: 4, title: 'Example Issue', status: 'draft', arcPosition: 4,+ arcRole: null, lengthProfile: null, pageTarget: 22, minutesTarget: 24,+ synopsis: 'seed synopsis',});});it('nulls synopsis rather than emitting an empty string for an unseeded issue', () => {expect(renderVolumeIssue({ ...issue, stages: {} }).synopsis).toBeNull();});++ it('materializes custom numeric targets for metadata-fit checks', () => {+ expect(renderVolumeIssue({+ ...issue,+ lengthProfile: 'custom',+ pageTarget: 4,+ minutesTarget: 120,+ })).toMatchObject({+ lengthProfile: 'custom',+ pageTarget: 4,+ minutesTarget: 120,+ });+ });});diff --git a/server/services/pipeline/canonReadiness.js b/server/services/pipeline/canonReadiness.jsindex fd75c70379..332d6d9700 100644--- a/server/services/pipeline/canonReadiness.js+++ b/server/services/pipeline/canonReadiness.js@@ -194,11 +194,37 @@ export function gradeComicReferencedNouns(comicScript, canon, thinChars = CANON_}, thinChars);}-// Fallback free-text source when there's no parseable comic script: TV draws-// from the teleplay, anything else from teleplay-or-prose. (Comic targets with-// a comic script go through gradeComicReferencedNouns, not this.)-function fallbackSourceText(issue) {- return issue.stages?.teleplay?.output || issue.stages?.prose?.output || '';+const requiredVisualStages = (targetFormat) => {+ if (targetFormat === 'comic') return ['comicScript'];+ if (targetFormat === 'tv') return ['teleplay'];+ return ['comicScript', 'teleplay'];+};++const resolveVisualStages = (targetFormat, sourceStages) => {+ if (!Array.isArray(sourceStages) || sourceStages.length === 0) {+ return requiredVisualStages(targetFormat);+ }+ const scoped = [...new Set(sourceStages.filter((stageId) => stageId === 'comicScript' || stageId === 'teleplay'))];+ return scoped.length > 0 ? scoped : requiredVisualStages(targetFormat);+};++function mergeGrades(grades) {+ const none = new Map();+ const thin = new Map();+ let referenced = 0;+ for (const grade of grades) {+ referenced += grade.referenced;+ for (const entry of grade.none) {+ const key = `${entry.kind}:${entry.id || entry.name}`;+ none.set(key, entry);+ thin.delete(key);+ }+ for (const entry of grade.thin) {+ const key = `${entry.kind}:${entry.id || entry.name}`;+ if (!none.has(key)) thin.set(key, entry);+ }+ }+ return { referenced, none: [...none.values()], thin: [...thin.values()], ready: none.size === 0 };}/**@@ -206,21 +232,52 @@ function fallbackSourceText(issue) {* checking many issues. Returns* `{ issueId, number, title, referenced, none[], thin[], ready }`.*- * Comic targets with a comic script grade against the DRAWABLE text only (panel- * descriptions + dialogue speakers) so an off-page character named only in- * narration/dialogue body isn't a false blocker; everything else grades the- * teleplay/prose.+ * Comic sources grade against the DRAWABLE text only (panel descriptions ++ * dialogue speakers) so an off-page character named only in dialogue body+ * isn't a false blocker. TV sources grade the teleplay. A prose draft or empty+ * outline is not a visual source and therefore cannot produce a vacuous+ * `ready:true`; hybrid series require both parallel-format scripts unless a+ * caller explicitly scopes `sourceStages` to the format it is about to render.*/-export async function checkIssueCanonReadiness(issueId, { canon = null, series = null, thinChars = CANON_THIN_CHARS } = {}) {+export async function checkIssueCanonReadiness(issueId, {+ canon = null,+ series = null,+ thinChars = CANON_THIN_CHARS,+ sourceStages = null,+} = {}) {const issue = await getIssue(issueId);const ser = series || await getSeries(issue.seriesId).catch(() => null);const c = canon || (ser ? await getSeriesCanon(ser).catch(() => null) : null) || { characters: [], places: [], objects: [] };const fmt = ser?.targetFormat || 'comic+tv';- const comic = (issue.stages?.comicScript?.output || '').trim();- const graded = (fmt !== 'tv' && comic)- ? gradeComicReferencedNouns(comic, c, thinChars)- : gradeReferencedNouns(fallbackSourceText(issue), c, thinChars);- return { issueId, number: issue.number, title: issue.title, referenced: graded.referenced, none: graded.none, thin: graded.thin, ready: graded.ready };+ const visualStages = resolveVisualStages(fmt, sourceStages);+ const sourceText = Object.fromEntries(visualStages.map((stageId) => [+ stageId,+ (issue.stages?.[stageId]?.output || '').trim(),+ ]));+ const missingSourceStages = visualStages.filter((stageId) => !sourceText[stageId]);+ const grades = visualStages.flatMap((stageId) => {+ const text = sourceText[stageId];+ if (!text) return [];+ return [stageId === 'comicScript'+ ? gradeComicReferencedNouns(text, c, thinChars)+ : gradeReferencedNouns(text, c, thinChars)];+ });+ const graded = mergeGrades(grades);+ const ready = missingSourceStages.length === 0 && graded.ready;+ return {+ issueId,+ number: issue.number,+ title: issue.title,+ referenced: graded.referenced,+ none: graded.none,+ thin: graded.thin,+ ready,+ sourceStages: visualStages,+ missingSourceStages,+ blockingReason: missingSourceStages.length > 0+ ? 'missing-visual-source'+ : (graded.ready ? null : 'undescribed-canon'),+ };}/**@@ -228,13 +285,15 @@ export async function checkIssueCanonReadiness(issueId, { canon = null, series =* series-level roll-up: `ready` (no issue has an undescribed drawn noun),* `blockingIssues[]`, and the de-duplicated `undescribed[]` noun list.*/-export async function checkSeriesCanonReadiness(seriesId, { thinChars = CANON_THIN_CHARS } = {}) {+export async function checkSeriesCanonReadiness(seriesId, { thinChars = CANON_THIN_CHARS, sourceStages = null } = {}) {const series = await getSeries(seriesId);const canon = await getSeriesCanon(series).catch(() => ({ characters: [], places: [], objects: [] }));const issues = await listIssues({ seriesId });const perIssue = [];for (const issue of issues) {- perIssue.push(await checkIssueCanonReadiness(issue.id, { canon, series, thinChars }));+ perIssue.push(await checkIssueCanonReadiness(issue.id, {+ canon, series, thinChars, sourceStages,+ }));}const blocking = perIssue.filter((r) => !r.ready);const noneById = new Map();@@ -245,7 +304,14 @@ export async function checkSeriesCanonReadiness(seriesId, { thinChars = CANON_THseriesId,ready: blocking.length === 0,issues: perIssue,- blockingIssues: blocking.map((r) => ({ issueId: r.issueId, number: r.number, title: r.title, none: r.none })),+ blockingIssues: blocking.map((r) => ({+ issueId: r.issueId,+ number: r.number,+ title: r.title,+ none: r.none,+ missingSourceStages: r.missingSourceStages,+ blockingReason: r.blockingReason,+ })),undescribed: [...noneById.values()],};}diff --git a/server/services/pipeline/canonReadiness.test.js b/server/services/pipeline/canonReadiness.test.jsindex 3c6910b282..0b1423d4cf 100644--- a/server/services/pipeline/canonReadiness.test.js+++ b/server/services/pipeline/canonReadiness.test.js@@ -104,6 +104,35 @@ describe('checkIssueCanonReadiness (matches the visual source)', () => {expect(report.none.map((n) => n.name)).toContain('Aria');});+ it('does not declare an outline-only comic issue visually ready', async () => {+ const series = await seriesSvc.createSeries({ name: 'S', logline: 'L', premise: 'P', targetFormat: 'comic' });+ const issue = await issuesSvc.createIssue({ seriesId: series.id, title: 'Outline', number: 1 });+ await issuesSvc.updateStage(issue.id, 'idea', { status: 'edited', input: 'Aria finds the door.' });++ const report = await checkIssueCanonReadiness(issue.id);+ expect(report).toMatchObject({+ ready: false,+ referenced: 0,+ blockingReason: 'missing-visual-source',+ missingSourceStages: ['comicScript'],+ });+ });++ it('requires both visual scripts for a hybrid series', async () => {+ const series = await seriesSvc.createSeries({ name: 'S', logline: 'L', premise: 'P', targetFormat: 'comic+tv' });+ const issue = await issuesSvc.createIssue({ seriesId: series.id, title: 'Hybrid', number: 1 });+ await issuesSvc.updateStage(issue.id, 'comicScript', { status: 'ready', output: 'PAGE 1\nPANEL 1\nAn empty room.' });++ const report = await checkIssueCanonReadiness(issue.id);+ expect(report.ready).toBe(false);+ expect(report.missingSourceStages).toEqual(['teleplay']);++ const comicOnly = await checkIssueCanonReadiness(issue.id, { sourceStages: ['comicScript'] });+ expect(comicOnly.ready).toBe(true);+ expect(comicOnly.sourceStages).toEqual(['comicScript']);+ expect(comicOnly.missingSourceStages).toEqual([]);+ });+it('does not flag a character named only in dialogue body (not drawn)', async () => {canon = { characters: [{ id: 'c1', name: 'Maggie', physicalDescription: '' },diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.jsindex 3faf5bc753..80c2e88a4c 100644--- a/server/services/pipeline/editorial/checkRunner.js+++ b/server/services/pipeline/editorial/checkRunner.js@@ -15,11 +15,11 @@* late-connecting clients via lib/sseUtils.js.*/-import { randomUUID, createHash } from 'crypto';+import { randomUUID } from 'crypto';import { createSseRunner } from '../../../lib/sseUtils.js';import { runStagedLLM, runInlineLLM, runStageScopedInlineLLM, resolveStageContext } from '../../../lib/stageRunner.js';import { planManuscriptPass, fitContextToManuscriptFloor, estimateTokens, MANUSCRIPT_FLOOR_TOKENS } from '../../../lib/contextBudget.js';-import { getEnabledChecks, getEnabledCheckRows, getAllChecks, applySeriesCheckConfig, orderChecksByDependencies, buildCustomCheck, CUSTOM_CHECK_ID_PREFIX, EDITORIAL_SOURCES, comicLetteringIssues, proseStageIssues } from '../../../lib/editorial/index.js';+import { getEnabledChecks, getEnabledCheckRows, getAllChecks, applySeriesCheckConfig, orderChecksByDependencies, buildCustomCheck, CUSTOM_CHECK_ID_PREFIX } from '../../../lib/editorial/index.js';import { getSettings } from '../../settings.js';import { getSeries } from '../series.js';import { listIssuesForSeries } from '../issues.js';@@ -28,10 +28,17 @@ import { collectManuscriptSections, sectionsCorpus, manuscriptSectionHeader } frimport { getReverseOutline } from '../reverseOutline.js';import { getFactsLedger } from '../continuityBible.js';import { getSeriesEditorial } from '../editorialAnalysis.js';-import { seedReviewFromFindings, getReview } from '../manuscriptReview.js';+import { seedReviewFromFindings } from '../manuscriptReview.js';import { recordTrendSnapshot } from '../editorialScore.js';import { readReadinessGate, mergeSeverityWeights } from '../../../lib/editorial/index.js';-import { canonicalStringify } from '../../../lib/objects.js';+import {+ buildEditorialSourceProjection,+ checkSources,+ effectiveCheckSources,+ fingerprintForCheck,+} from './reviewStaleness.js';++export { effectiveCheckSources, getReviewWithStaleness } from './reviewStaleness.js';// Per-check severity breakdown for telemetry (#1578). Bucket a check's findings// by severity so the autopilot SSE stream can show a per-check high/medium/low@@ -48,308 +55,6 @@ function severityBreakdown(findings) {return counts;}-// Source-content fingerprinting for finding staleness (#1345, #1387). Each finding-// is stamped with a hash of the exact content its check analyzed; the manuscript-// editor / triage view flags a finding `stale` once that content drifts.-//-// Per-check declared sources (#1387): a check declares the inputs its run() reads-// via `check.sources` (a subset of EDITORIAL_SOURCES), and we fingerprint EXACTLY-// those — so a naming finding (sources: ['canon']) doesn't go stale on a prose or-// style-guide edit, and editing the ticking clock stales only the-// arc.ticking-clock-hygiene finding (sources: ['series.arc.tickingClock']) instead-// of every canon-only finding. This replaces the prior two-segment heuristic-// (manuscript-vs-canon) that over-flagged because it folded the style guide +-// ticking clock into shared segments.-//-// `SOURCE_RESOLVERS` maps each declared token to the exact content hashed.-// `canonicalStringify` (key-sorted) keeps the hash stable across machines so a-// synced finding isn't falsely flagged stale after an import re-orders keys. A-// load-time guard asserts every EDITORIAL_SOURCES token has a resolver here — a-// token with no resolver would silently contribute nothing (false-fresh).-const HASH_SEP = '\u0000';-const sha256 = (text) => createHash('sha256').update(text || '').digest('hex');-const SOURCE_RESOLVERS = {- manuscript: ({ manuscript }) => manuscript || '',- canon: ({ canon }) => canonicalStringify(canon ?? null),- // The continuity-bible facts ledger the timeline / canon-contradiction check- // reconciles the prose against (#1581). Fingerprint the whole facts array so a- // re-extraction or a hand-edit to any established fact stales its findings.- continuityBible: ({ continuityBible }) => canonicalStringify(continuityBible ?? null),- 'series.styleGuide': ({ series }) => canonicalStringify(series?.styleGuide ?? null),- 'series.arc.tickingClock': ({ series }) => canonicalStringify(series?.arc?.tickingClock ?? null),- // The authored reader-map hooks/payoffs the Chekhov check reconciles against (#1299).- 'series.arc.readerMap': ({ series }) => canonicalStringify(series?.arc?.readerMap ?? null),- // The authored foreshadowing ledger the Chekhov check reconciles against (#2172).- // Fingerprint the whole ledger so editing a plant/reinforce/payoff seed stales its findings.- 'series.arc.foreshadowing': ({ series }) => canonicalStringify(series?.arc?.foreshadowing ?? null),- // The authored arc themes the theme.coherence check reconciles the prose against- // (#1317). Lives on the already-loaded series record, so no extra I/O — fingerprint- // the whole themes array so adding/editing a declared theme stales the findings.- 'series.arc.themes': ({ series }) => canonicalStringify(series?.arc?.themes ?? null),- // The author-supplied real-world fact reference the research.fact-accuracy check- // reconciles the prose against (#1588). Lives on the already-loaded series record,- // so no extra I/O — fingerprint the reference text so editing it stales fact findings.- 'series.factReference': ({ series }) => canonicalStringify(series?.factReference ?? null),- // The reverse-outline scenes the check reads (#1296). Fingerprinting the whole- // scenes array is intentionally over-eager (any scene edit stales a finding)- // rather than under: safe vs. false-fresh, and the check reads several scene fields.- reverseOutline: ({ reverseOutline }) => canonicalStringify(reverseOutline ?? null),- // The reverse-outline PLOTLINES the plot-structure check reconciles dropped- // subplots against (#1310). Separate token from `reverseOutline` so a scene- // edit that doesn't touch the plotline list doesn't needlessly stale a- // plotline-only finding (and vice-versa) — same over-eager-but-safe policy.- 'reverseOutline.plotlines': ({ reverseOutlinePlotlines }) =>- canonicalStringify(reverseOutlinePlotlines ?? null),- // The detected per-character arc directions a POV check reads (#1295). The- // injected `editorialArcs` is the stable projection (name/arcDirection/issueCount/- // isProtagonist) — NOT the raw getSeriesEditorial output, which carries a- // per-call `generatedAt` timestamp that would re-stale every finding each run.- // The `complete` flag is folded in too: a prose edit that stales the analysis- // (without re-running it) leaves the projection byte-identical but flips- // completeness, and pov.justified's "absent from arcs" finding depends on that- // flag — so a finding must go stale when it changes, not only when the arcs do.- editorialArcs: ({ editorialArcs, editorialArcsComplete }) =>- canonicalStringify({ arcs: editorialArcs ?? null, complete: editorialArcsComplete === true }),- // The AUTHORED per-character story arcs the arc.transitions check reconciles- // against (#1293). Lives on the already-loaded series record, so no extra I/O- // — fingerprint the whole array so any arc/transition edit stales the findings.- 'series.characterArcs': ({ series }) => canonicalStringify(series?.characterArcs ?? null),- // The per-issue storyboard shot lists the visual.shot-continuity check reads- // (#1315). Fingerprint ONLY the fields the check actually reads (scene- // heading/slugline + each shot's grammar fields) via `projectStoryboardContinuity`- // — NOT the whole scene object, so an unrelated render/status edit- // (`imageJobId`, `sceneVideoJobId`, wardrobe metadata) doesn't falsely stale a- // continuity finding. Mirrors `projectComicLetteringContent` for the comic check.- 'storyboard.shots': ({ storyboardScenes }) =>- canonicalStringify(projectStoryboardContinuity(storyboardScenes) ?? null),- // Every issue's AUTHORITATIVE comic lettering content, keyed by issue number- // (#1313). The lettering-density check reads the edited comic-pages split (or the- // generated script when unsplit) — NOT the prose manuscript — so it gets its own- // source token: editing a comic script/page stales lettering findings without- // staling prose findings, and vice-versa. `projectComicLetteringContent` builds- // the stable [{ number, panels: [{ caption, dialogue, sfx }] }] off the SAME- // `comicLetteringIssues` the check analyzes, so a finding stales exactly when the- // text it read changes (and an unrelated image render — `panel.imageJobId` — does- // NOT stale it, since only the lettering fields are projected).- comicScript: ({ comicScripts }) => canonicalStringify(comicScripts ?? null),- // The page-turn check's content (#1314) — its own token because it reads each- // panel's visual `description` (+ caption/dialogue/SFX text) for the LLM digest.- // A description edit stales a page-turn finding without staling a lettering one- // (which doesn't read `description`), and vice-versa.- 'comicScript.pacing': ({ comicPacingContent }) => canonicalStringify(comicPacingContent ?? null),- // The panel-rhythm check's content (#1314) — LAYOUT ONLY: it reads nothing but- // the per-page panel COUNT (splash/crowding/grid-monotony verdicts), so its- // fingerprint is just the counts. A text-only edit (rewording a caption or- // description without adding/removing a panel) must NOT stale a rhythm finding —- // the verdict cannot have changed. Distinct from `comicScript.pacing` (which- // hashes the text the page-turn LLM reads).- 'comicScript.layout': ({ comicLayoutContent }) => canonicalStringify(comicLayoutContent ?? null),- // Each issue's PROSE-stage text the comic↔prose-sync check compares against the- // comic (#1589). Its own token (NOT `manuscript`): the stitched manuscript picks- // comicScript over prose for a hybrid issue, so a `manuscript` fingerprint would- // track comic edits, not prose. `proseContent` is built off the SAME- // `proseStageIssues` projection the check reads (per-issue prose keyed by number),- // so a finding stales exactly when the prose it compared changes — and a comic-only- // edit doesn't stale it.- prose: ({ proseContent }) => canonicalStringify(proseContent ?? null),-};--// Flatten the storyboard scenes across every issue into the `{ issueNumber, scene }`-// list the visual.shot-continuity check reads (#1315). Built off the already-loaded-// issues — no extra I/O. Only issues that actually have storyboard scenes contribute,-// so a series with no visual stage yields an empty list (the check's gate then skips).-function collectStoryboardScenes(issues) {- const out = [];- for (const issue of (Array.isArray(issues) ? issues : [])) {- const scenes = issue?.stages?.storyboards?.scenes;- if (!Array.isArray(scenes) || !scenes.length) continue;- const issueNumber = Number.isInteger(issue.number) ? issue.number : null;- for (const scene of scenes) {- if (scene && typeof scene === 'object') out.push({ issueNumber, scene });- }- }- return out;-}--// Project the collected storyboard scenes down to ONLY the fields the-// visual.shot-continuity check reads (#1315), for the staleness fingerprint —-// the scene's heading/slugline (its finding location) and each shot's grammar-// fields (`id`, `continuityFromShotId`, `screenDirection`, `shotType`,-// `description` — the anchorQuote source). Excludes render/status fields-// (`imageJobId`, `sceneVideoJobId`, wardrobe, …) so a finding stales only when-// the shot grammar it analyzed changes, not on an unrelated render. Mirrors-// `projectComicLetteringContent`. Type-guarded throughout (scenes ride peer sync).-function projectStoryboardContinuity(storyboardScenes) {- return (Array.isArray(storyboardScenes) ? storyboardScenes : []).map(({ issueNumber, scene }) => ({- issueNumber: Number.isInteger(issueNumber) ? issueNumber : null,- heading: typeof scene?.heading === 'string' ? scene.heading : '',- slugline: typeof scene?.slugline === 'string' ? scene.slugline : '',- shots: (Array.isArray(scene?.shots) ? scene.shots : []).map((s) => ({- id: typeof s?.id === 'string' ? s.id : '',- continuityFromShotId: typeof s?.continuityFromShotId === 'string' ? s.continuityFromShotId : null,- screenDirection: typeof s?.screenDirection === 'string' ? s.screenDirection : null,- shotType: typeof s?.shotType === 'string' ? s.shotType : null,- description: typeof s?.description === 'string' ? s.description : '',- })),- }));-}--// The three comic projections below all derive from the SAME parsed page list-// (`comicLetteringIssues(issues)` → `[{ number, pages }]`), so the caller parses-// the comic scripts ONCE (`comicIssuesFor(issues)`) and passes the rows in —-// rather than each projection re-parsing every issue's script. They take the-// already-parsed `comicIssues` rows, not raw `issues`.--// Lettering token (`comicScript`, #1313): keeps ONLY caption/dialogue/SFX — the-// fields `panelLetteringMetrics` consumes — so the hash is stable across image-// renders and description edits that don't change lettering. PAGE GROUPING is-// preserved: the check reports per-page totals/locations, so moving panels between-// pages must change the hash even when the lettering text is identical.-function projectComicLetteringContent(comicIssues) {- return comicIssues.map(({ number, pages }) => ({- number,- pages: pages.map((p) => ({- panels: (Array.isArray(p?.panels) ? p.panels : []).map((panel) => ({- caption: typeof panel?.caption === 'string' ? panel.caption : '',- dialogue: Array.isArray(panel?.dialogue) ? panel.dialogue : [],- sfx: typeof panel?.sfx === 'string' ? panel.sfx : '',- })),- })),- }));-}--// Page-turn token (`comicScript.pacing`, #1314): distinct from the lettering token-// so the two checks' fingerprints don't bleed — editing a panel's visual-// `description` must stale a page-turn finding (the LLM digest reads it) WITHOUT-// staling a lettering finding (which never reads it), and vice-versa. So this adds-// `description` on top of caption/dialogue/SFX. PAGE GROUPING preserved; render/-// status fields (`panel.imageJobId`) are never projected.-function projectComicPacingContent(comicIssues) {- return comicIssues.map(({ number, pages }) => ({- number,- pages: pages.map((p) => ({- panels: (Array.isArray(p?.panels) ? p.panels : []).map((panel) => ({- description: typeof panel?.description === 'string' ? panel.description : '',- caption: typeof panel?.caption === 'string' ? panel.caption : '',- dialogue: Array.isArray(panel?.dialogue) ? panel.dialogue : [],- sfx: typeof panel?.sfx === 'string' ? panel.sfx : '',- })),- })),- }));-}--// Layout token (`comicScript.layout`, #1314): LAYOUT ONLY — the per-page panel-// COUNT — for the panel-rhythm check, which reads nothing but counts-// (`analyzePanelRhythm`). Fingerprinting only the count means a text-only edit-// (reword a caption/description without changing how many panels a page has) does-// NOT stale a rhythm finding, while adding/removing/moving a panel does. Per-page-// array order is preserved so a reordering that changes the run structure (splash-// runs, monotony) re-hashes.-function projectComicLayoutContent(comicIssues) {- return comicIssues.map(({ number, pages }) => ({- number,- panelCounts: pages.map((p) => (Array.isArray(p?.panels) ? p.panels.length : 0)),- }));-}--// Stable projection of the series editorial aggregate down to the arc fields a-// POV/arc check reads — drops the volatile `generatedAt` (and the rest) so the-// staleness fingerprint only moves when a character's detected arc actually does.-function projectEditorialArcs(editorial) {- const chars = Array.isArray(editorial?.characters) ? editorial.characters : [];- return chars.map((c) => ({- name: c?.name || '',- arcDirection: c?.arcDirection || 'flat',- issueCount: Number.isFinite(c?.issueCount) ? c.issueCount : 0,- isProtagonist: c?.isProtagonist === true,- }));-}--// True only when every analyzable issue has a fresh, complete analysis — the-// signal pov.justified uses to tell "absent because arc-less" from "absent-// because not-yet-analyzed" (#1295). Injected into ctx for the check AND folded-// into the editorialArcs fingerprint above so a prose edit that stales coverage-// (without changing the arc projection) still stales the POV findings.-function editorialCoverageComplete(editorial) {- const cov = editorial?.coverage;- return !!cov && cov.withContent > 0 && cov.analyzed >= cov.withContent && (cov.stale || 0) === 0;-}-for (const token of EDITORIAL_SOURCES) {- if (typeof SOURCE_RESOLVERS[token] !== 'function') {- throw new Error(`checkRunner: editorial source "${token}" has no fingerprint resolver — keep SOURCE_RESOLVERS in sync with EDITORIAL_SOURCES`);- }-}--// A check's declared sources, falling back to the legacy needsManuscript heuristic-// for any check synthesized before the declaration existed (e.g. an older custom-// check). Unknown tokens are dropped so a typo can't corrupt the hash.-function checkSources(check) {- const declared = Array.isArray(check?.sources) && check.sources.length- ? check.sources- : (check?.needsManuscript ? ['manuscript', 'canon'] : ['canon']);- return declared.filter((token) => SOURCE_RESOLVERS[token]);-}--// The source tokens a check's findings EFFECTIVELY depend on for staleness: its-// OWN declared sources PLUS, transitively, the sources of every check it lists in-// `dependsOn` (#1627). A dependency-consuming check reads its dependency's findings-// via ctx.priorFindings, so its compound finding can change when the DEPENDENCY's-// source content drifts even though the dependent's own sources didn't. Folding the-// dependencies' sources in keeps getReviewWithStaleness from marking such a finding-// falsely fresh — and the matching I/O gates fetch that content so it isn't falsely-// stale either. Resolved against the full registry (`checkById`) and cycle-guarded-// so it's identical at seed-time and read-time. With no checkById (or no dependsOn)-// it returns the check's own sources unchanged, so a check that opts out is untouched.-export function effectiveCheckSources(check, checkById) {- const own = checkSources(check);- const deps = Array.isArray(check?.dependsOn) ? check.dependsOn : [];- if (!deps.length || !(checkById instanceof Map)) return own;- const tokens = new Set(own);- const seen = new Set([check?.id]);- const stack = [...deps];- while (stack.length) {- const id = stack.pop();- if (seen.has(id)) continue;- seen.add(id);- const dep = checkById.get(id);- if (!dep) continue;- for (const token of checkSources(dep)) tokens.add(token);- for (const next of (Array.isArray(dep.dependsOn) ? dep.dependsOn : [])) {- if (!seen.has(next)) stack.push(next);- }- }- return [...tokens];-}--// Resolve every source token's content ONCE for a given inputs object-// (`{ manuscript, canon, series }`), so fingerprinting many checks/comments doesn't-// re-stringify the canon per call. Returns a token→string map the fingerprint reads.-function resolveSources(inputs) {- const resolved = {};- for (const token of EDITORIAL_SOURCES) resolved[token] = SOURCE_RESOLVERS[token](inputs);- return resolved;-}--// Fingerprint exactly the inputs a check reads, from a pre-resolved token→content-// map (see `resolveSources`). Tokens are de-duped and sorted so the hash is-// independent of declaration order; each segment is prefixed with its token so two-// source sets can't collide on equal content. NUL joins segments (it can't appear-// in the JSON the resolvers emit) so they can't run together ambiguously.-function fingerprintForCheck(check, resolved, checkById = null) {- const segments = [...new Set(effectiveCheckSources(check, checkById))]- .sort()- .map((token) => `${token}=${resolved[token]}`);- // A custom check's run logic IS its authored prompt (user data, not code), so a- // prompt edit must stale its prior findings even when the manuscript is unchanged- // — fold it into the fingerprint. Built-in checks' logic lives in code (a code- // change isn't user content and isn't fingerprinted), so only their declared- // content sources matter. (#1346, #1387)- if (check?.isCustom && typeof check.prompt === 'string') {- segments.push(`definition=${check.prompt}`);- }- return sha256(segments.join(HASH_SEP));-}-// Inter-check context sharing (#1627). Build the read-only `ctx.priorFindings` a// check sees: the stamped findings produced EARLIER this pass by the checks it// named in `dependsOn`. Scoped to declared deps so a non-declaring check always@@ -442,40 +147,23 @@ export async function buildEditorialContext(seriesId, enabled, { providerOverridneedsContinuityBible ? getFactsLedger(seriesId).catch(() => null) : Promise.resolve(null),]);const manuscript = sectionsCorpus(sections);- // The continuity-bible facts ledger (#1581) — the facts array, injected for the- // timeline / canon-contradiction check and fingerprinted for its staleness.- const continuityBible = Array.isArray(bible?.facts) ? bible.facts : [];- // Storyboard shots for the visual.shot-continuity check (#1315) — projected off- // the gated `issues` fetch (empty unless a storyboard.shots/comicScript check is on).- const storyboardScenes = collectStoryboardScenes(issues);- const reverseOutline = Array.isArray(outline?.scenes) ? outline.scenes : [];- // The outline's plotline list (#1310) — injected separately from the scenes so a- // plotline-reading check (plot.structure-momentum) can reconcile dropped subplots- // against the author's tagged threads.- const reverseOutlinePlotlines = Array.isArray(outline?.plotlines) ? outline.plotlines : [];- const editorialArcs = projectEditorialArcs(editorial);- // Whether every analyzable issue has been analyzed and is fresh — gates the- // pov.justified "absent from detected arcs" finding so a partially-analyzed- // series (canceled/early-stopped batch) doesn't flag a not-yet-analyzed POV- // holder as arc-less (#1295). Folded into the editorialArcs fingerprint below.- const editorialArcsComplete = editorialCoverageComplete(editorial);- // The comic content the comic checks read — derived from the already-loaded- // issues (no extra I/O). Parse each issue's comic script ONCE, then build all- // three per-token projections from the shared rows: lettering (#1313,- // caption/dialogue/SFX), pacing (#1314, + visual `description`), and layout- // (#1314, panel counts only) — so a description edit stales a pacing finding- // without staling a lettering one, and a text-only edit never stales a rhythm one.- const comicIssues = comicLetteringIssues(issues);- const comicScripts = projectComicLetteringContent(comicIssues);- const comicPacingContent = projectComicPacingContent(comicIssues);- const comicLayoutContent = projectComicLayoutContent(comicIssues);- // The per-issue PROSE-stage content the comic↔prose-sync check compares against the- // comic (#1589) — built off the same already-loaded issues, keyed by issue number.- const proseContent = proseStageIssues(issues);- // Resolve every source token once — each finding's fingerprint reads from this- // so the editor flags it `stale` when the content that check actually read (its- // declared `sources`) drifts (#1345, #1387).- const resolvedSources = resolveSources({ manuscript, canon, continuityBible, series, reverseOutline, reverseOutlinePlotlines, editorialArcs, editorialArcsComplete, storyboardScenes, comicScripts, comicPacingContent, comicLayoutContent, proseContent });+ const {+ continuityBible,+ storyboardScenes,+ reverseOutline,+ reverseOutlinePlotlines,+ editorialArcs,+ editorialArcsComplete,+ resolvedSources,+ } = buildEditorialSourceProjection({+ manuscript,+ canon,+ series,+ issues,+ outline,+ editorial,+ bible,+ });const baseCtx = {seriesId,series,@@ -932,94 +620,6 @@ export async function buildReverseOutlineGateContext(seriesId, { outline } = {})};}-/**- * Read the manuscript review and annotate each editorial-check finding with a- * `stale` flag (#1345): true when the content the check analyzed has changed- * since the finding was seeded. Mirrors `editorialAnalysis.isSnapshotStale` —- * recompute the current source hash and compare against the one stamped on the- * finding. Findings without a `sourceContentHash` (completeness-pass comments,- * older peers, legacy records) or whose check is no longer registered are left- * unannotated → the UI treats absent `stale` as not-stale.- *- * Staleness is derived per-read (never stored), so it stays local to each- * install's current content and never rides the synced review document.- */-export async function getReviewWithStaleness(seriesId) {- const review = await getReview(seriesId);- // Resolve checks against built-ins + the user's custom checks (#1346) so a- // custom-check finding still gets staleness annotation. Build the id→check map- // once (custom-check synthesis is not free) and look up per comment.- const settings = await getSettings();- const byId = new Map(getAllChecks(settings).map((c) => [c.id, c]));- const checkFor = (id) => byId.get(id) || null;- // Only recompute hashes when there's at least one hash-stamped finding from a- // still-registered check — a pure completeness review pays no extra I/O.- const evaluable = review.comments.filter((c) => c.checkId && c.sourceContentHash && checkFor(c.checkId));- if (!evaluable.length) return review;- // Re-fingerprint each finding against its check's EFFECTIVE sources — own plus- // declared-dependency sources (#1627) — exactly as the seed path stamped it, so a- // dependency-consuming finding's hash is computed against the same content on read- // as on seed. With no deps this is the check's own sources, unchanged.- const sourcesFor = (id) => effectiveCheckSources(checkFor(id), byId);- // Only pay the manuscript-collection I/O when an evaluable check declares it as- // a source (mirrors the run path's gate, now source-derived rather than the bare- // needsManuscript flag so it stays correct as the source vocabulary grows).- const needsManuscript = evaluable.some((c) => sourcesFor(c.checkId).includes('manuscript'));- const needsReverseOutline = evaluable.some((c) => {- const sources = sourcesFor(c.checkId);- return sources.includes('reverseOutline') || sources.includes('reverseOutline.plotlines');- });- const needsEditorialArcs = evaluable.some((c) => sourcesFor(c.checkId).includes('editorialArcs'));- // Continuity-bible ledger re-fingerprint, gated like the others (#1581) — must- // mirror the run path's fetch so a timeline/canon finding's hash is computed- // against the SAME ledger content on read as on seed (else it always reads stale).- const needsContinuityBible = evaluable.some((c) => sourcesFor(c.checkId).includes('continuityBible'));- // Issues are fetched here only when a storyboard-shots (#1315) OR comic-script- // (#1313 lettering / #1314 pacing) finding needs re-fingerprinting — all derive- // from the issue records, so a single gated fetch serves them. Mirrors the other- // per-source I/O gates.- const needsStoryboards = evaluable.some((c) => sourcesFor(c.checkId).includes('storyboard.shots'));- const needsComicScript = evaluable.some((c) => {- const s = sourcesFor(c.checkId);- return s.includes('comicScript') || s.includes('comicScript.pacing') || s.includes('comicScript.layout');- });- // The prose source (#1589) reads the per-issue prose stage off the same `issues`- // fetch, so it gates the issues load too — a prose-only check still loads issues.- const needsProse = evaluable.some((c) => sourcesFor(c.checkId).includes('prose'));- const needsIssues = needsStoryboards || needsComicScript || needsProse;- const series = await getSeries(seriesId);- const [sections, canon, outline, editorial, issues, bible] = await Promise.all([- needsManuscript ? collectManuscriptSections(seriesId) : Promise.resolve([]),- getSeriesCanon(series),- needsReverseOutline ? getReverseOutline(seriesId).catch(() => null) : Promise.resolve(null),- // Reuse the already-loaded series.- needsEditorialArcs ? getSeriesEditorial(seriesId, { series }).catch(() => null) : Promise.resolve(null),- needsIssues ? listIssuesForSeries(seriesId).catch(() => []) : Promise.resolve([]),- needsContinuityBible ? getFactsLedger(seriesId).catch(() => null) : Promise.resolve(null),- ]);- const continuityBible = Array.isArray(bible?.facts) ? bible.facts : [];- const reverseOutline = Array.isArray(outline?.scenes) ? outline.scenes : [];- const reverseOutlinePlotlines = Array.isArray(outline?.plotlines) ? outline.plotlines : [];- const editorialArcs = projectEditorialArcs(editorial);- const editorialArcsComplete = editorialCoverageComplete(editorial);- const storyboardScenes = collectStoryboardScenes(issues);- const comicIssues = comicLetteringIssues(issues);- const comicScripts = projectComicLetteringContent(comicIssues);- const comicPacingContent = projectComicPacingContent(comicIssues);- const comicLayoutContent = projectComicLayoutContent(comicIssues);- const proseContent = proseStageIssues(issues);- const resolvedSources = resolveSources({ manuscript: sectionsCorpus(sections), canon, continuityBible, series, reverseOutline, reverseOutlinePlotlines, editorialArcs, editorialArcsComplete, storyboardScenes, comicScripts, comicPacingContent, comicLayoutContent, proseContent });- return {- ...review,- comments: review.comments.map((c) => {- const check = c.checkId && c.sourceContentHash ? checkFor(c.checkId) : null;- if (!check) return c;- const current = fingerprintForCheck(check, resolvedSources, byId);- return { ...c, stale: c.sourceContentHash !== current };- }),- };-}-// ---------------------------------------------------------------------------// SSE run-tracking — shared lifecycle via createSseRunner (server/lib/sseUtils.js),// the same factory backing manuscriptCompletenessRunner + editorialAnalysisRunner.diff --git a/server/services/pipeline/editorial/checkRunner.test.js b/server/services/pipeline/editorial/checkRunner.test.jsindex 800fe91ee1..038006573c 100644--- a/server/services/pipeline/editorial/checkRunner.test.js+++ b/server/services/pipeline/editorial/checkRunner.test.js@@ -3,7 +3,11 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';// Mock the data sources + LLM + seed, but use the REAL registry so the runner// exercises the actual reference checks (deterministic naming + LLM info-dump).vi.mock('../../settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));-vi.mock('../series.js', () => ({ getSeries: vi.fn(async () => ({ id: 's1', universeId: 'u1' })) }));+let seriesState = { id: 's1', universeId: 'u1', premise: 'A fragile alliance.', arc: { summary: 'The alliance holds.' } };+vi.mock('../series.js', () => ({+ getSeries: vi.fn(async () => seriesState),+ MANUSCRIPT_TYPES: ['comicScript', 'teleplay', 'prose'],+}));// Issues source — backed by a mutable fixture so the storyboard.shots continuity// check (#1315) can be exercised; default empty so the check is gated off unless a// test populates issues carrying storyboard scenes. The runner reads the UNCAPPED@@ -11,21 +15,37 @@ vi.mock('../series.js', () => ({ getSeries: vi.fn(async () => ({ id: 's1', univelet issuesState = [];vi.mock('../issues.js', () => ({listIssuesForSeries: vi.fn(async (seriesId) => issuesState.filter((i) => i.seriesId === seriesId)),+ listIssues: vi.fn(async () => []),+ STAGE_INPUT_MAX: 200_000,+ STAGE_OUTPUT_MAX: 200_000,}));-vi.mock('../seriesCanon.js', () => ({- getSeriesCanon: vi.fn(async () => ({+let canonState = {characters: [{ name: 'Alina' }, { name: 'Alana' }, { name: 'Zog' }],places: [],objects: [],- })),-}));-vi.mock('../arcPlanner.js', () => ({- collectManuscriptSections: vi.fn(async () => [- { number: 1, title: 'Pilot', stageId: 'prose', content: 'As you know, Bob, the kingdom fell.' },- ]),- sectionsCorpus: vi.fn((sections) => sections.map((s) => s.content).join('\n')),- manuscriptSectionHeader: vi.fn((s) => `# Issue ${s.number}`),+};+vi.mock('../seriesCanon.js', () => ({+ getSeriesCanon: vi.fn(async () => canonState),+ getSeriesPlanningCanon: vi.fn(async () => canonState),+ scopeCanonForSeries: vi.fn((world) => world),}));+vi.mock('../../universeBuilder.js', () => ({ getUniverse: vi.fn(async () => null) }));+const defaultSections = [+ { number: 1, title: 'Pilot', stageId: 'prose', content: 'As you know, Bob, the kingdom fell.' },+];+vi.mock('../arcPlanner.js', async () => {+ const [context, completeness] = await Promise.all([+ vi.importActual('../arcPlanner/context.js'),+ vi.importActual('../arcPlanner/completenessPass.js'),+ ]);+ return {+ collectManuscriptSections: vi.fn(async () => defaultSections),+ sectionsCorpus: context.sectionsCorpus,+ manuscriptSectionHeader: context.manuscriptSectionHeader,+ buildCompletenessContext: completeness.buildCompletenessContext,+ completenessSourceHash: completeness.completenessSourceHash,+ };+});vi.mock('../../../lib/stageRunner.js', () => ({runStagedLLM: vi.fn(async () => ({runId: 'llm-run',@@ -78,7 +98,7 @@ vi.mock('../editorialAnalysis.js', () => ({ getSeriesEditorial: vi.fn(async () =const { runEditorialChecks, buildEditorialCheckPlan, getReviewWithStaleness, enabledChecksConsumeReverseOutline, buildReverseOutlineGateContext, summarizeCheckErrors, previewCustomCheck, buildScopedPriorFindings, effectiveCheckSources, __testing: checkRunnerTesting } = await import('./checkRunner.js');const { runStagedLLM, resolveStageContext } = await import('../../../lib/stageRunner.js');-const { collectManuscriptSections } = await import('../arcPlanner.js');+const { buildCompletenessContext, collectManuscriptSections, completenessSourceHash, sectionsCorpus } = await import('../arcPlanner.js');const { getSeriesCanon } = await import('../seriesCanon.js');const { getSeries } = await import('../series.js');const { getSettings } = await import('../../settings.js');@@ -95,6 +115,12 @@ const disableWhere = (predicate) => ({});beforeEach(() => {+ seriesState = { id: 's1', universeId: 'u1', premise: 'A fragile alliance.', arc: { summary: 'The alliance holds.' } };+ canonState = {+ characters: [{ name: 'Alina' }, { name: 'Alana' }, { name: 'Zog' }],+ places: [],+ objects: [],+ };seedStore.length = 0;reviewState = { comments: [] };outlineState = { scenes: [] };@@ -105,6 +131,7 @@ beforeEach(() => {resolveStageContext.mockClear();collectManuscriptSections.mockClear();getSeriesCanon.mockClear();+ getSeries.mockClear();listIssuesForSeries.mockClear();});@@ -957,19 +984,91 @@ describe('getReviewWithStaleness (#1345)', () => {expect(stale.comments.find((c) => c.checkId === 'custom.anachronism').stale).toBe(true);});- it('leaves legacy findings (no hash), completeness comments (no checkId), and unknown checks unannotated', async () => {+ it('evaluates hash-stamped completeness comments while leaving legacy and unknown checks unannotated', async () => {+ const sourceContentHash = completenessSourceHash(await buildCompletenessContext(+ seriesState,+ sectionsCorpus(defaultSections),+ ));reviewState = {comments: [{ id: 'a', checkId: 'naming.dissimilar-names', anchorQuote: 'x', problem: 'legacy', status: 'open' }, // no hash- { id: 'b', checkId: null, anchorQuote: 'y', problem: 'completeness', status: 'open', sourceContentHash: 'abc' },+ { id: 'b', checkId: null, anchorQuote: 'y', problem: 'completeness', status: 'open', sourceContentHash },{ id: 'c', checkId: 'does.not-exist', anchorQuote: 'z', problem: 'unknown check', status: 'open', sourceContentHash: 'abc' },],};const review = await getReviewWithStaleness('s1');- // No evaluable comment → passthrough, no recompute, no `stale` key added.- for (const c of review.comments) expect(c).not.toHaveProperty('stale');- expect(collectManuscriptSections).not.toHaveBeenCalled();- expect(getSeriesCanon).not.toHaveBeenCalled();+ expect(review.comments.find((c) => c.id === 'b').stale).toBe(false);+ expect(review.comments.find((c) => c.id === 'a')).not.toHaveProperty('stale');+ expect(review.comments.find((c) => c.id === 'c')).not.toHaveProperty('stale');+ expect(collectManuscriptSections).toHaveBeenCalledWith('s1');++ collectManuscriptSections.mockResolvedValueOnce([+ { number: 1, title: 'Pilot', stageId: 'prose', content: 'The manuscript has changed.' },+ ]);+ const stale = await getReviewWithStaleness('s1');+ expect(stale.comments.find((c) => c.id === 'b').stale).toBe(true);+ expect(getSeriesCanon).toHaveBeenCalled();+ });++ it('stales completeness advice when the intended arc or canon changes without a manuscript edit', async () => {+ const manuscript = sectionsCorpus(defaultSections);+ const sourceContentHash = completenessSourceHash(await buildCompletenessContext(seriesState, manuscript));+ reviewState = {+ comments: [{+ id: 'b', checkId: null, anchorQuote: 'y', problem: 'completeness',+ status: 'open', sourceContentHash,+ }],+ };++ const fresh = await getReviewWithStaleness('s1');+ expect(fresh.comments[0].stale).toBe(false);++ seriesState = { ...seriesState, arc: { summary: 'The alliance shatters.' } };+ const arcStale = await getReviewWithStaleness('s1');+ expect(arcStale.comments[0].stale).toBe(true);++ seriesState = { ...seriesState, arc: { summary: 'The alliance holds.' } };+ canonState = { ...canonState, places: [{ name: 'The New Citadel' }] };+ const canonStale = await getReviewWithStaleness('s1');+ expect(canonStale.comments[0].stale).toBe(true);+ });++ it('recomputes named-check and completeness fingerprints together in a mixed review', async () => {+ const run = await runEditorialChecks('s1');+ const naming = run.findings.find((finding) => finding.checkId === 'naming.dissimilar-names');+ const completenessHash = completenessSourceHash(await buildCompletenessContext(+ seriesState,+ sectionsCorpus(defaultSections),+ ));+ reviewState = {+ comments: [+ {+ id: 'named', checkId: naming.checkId, anchorQuote: naming.anchorQuote,+ problem: naming.problem, status: 'open', sourceContentHash: naming.sourceContentHash,+ },+ {+ id: 'completeness', checkId: null, anchorQuote: 'kingdom fell',+ problem: 'arc gap', status: 'open', sourceContentHash: completenessHash,+ },+ ],+ };++ const fresh = await getReviewWithStaleness('s1');+ expect(fresh.comments.find((comment) => comment.id === 'named').stale).toBe(false);+ expect(fresh.comments.find((comment) => comment.id === 'completeness').stale).toBe(false);++ collectManuscriptSections.mockResolvedValueOnce([{+ ...defaultSections[0],+ content: 'The manuscript changed while the canon names stayed fixed.',+ }]);+ const manuscriptStale = await getReviewWithStaleness('s1');+ expect(manuscriptStale.comments.find((comment) => comment.id === 'completeness').stale).toBe(true);+ expect(manuscriptStale.comments.find((comment) => comment.id === 'named').stale).toBe(false);++ seriesState = { ...seriesState, arc: { summary: 'The alliance shatters.' } };+ const arcStale = await getReviewWithStaleness('s1');+ expect(arcStale.comments.find((comment) => comment.id === 'completeness').stale).toBe(true);+ expect(arcStale.comments.find((comment) => comment.id === 'named').stale).toBe(false);});});diff --git a/server/services/pipeline/editorial/reviewStaleness.js b/server/services/pipeline/editorial/reviewStaleness.jsnew file mode 100644index 0000000000..faf5c99d75--- /dev/null+++ b/server/services/pipeline/editorial/reviewStaleness.js@@ -0,0 +1,337 @@+/**+ * Pipeline editorial review staleness.+ *+ * Owns the source projections and deterministic fingerprints shared by the+ * editorial-check seed path and the read-time review annotation path. Keeping+ * both consumers on this boundary prevents their source contracts from+ * drifting while leaving checkRunner focused on conducting checks.+ */++import { createHash } from 'crypto';+import {+ EDITORIAL_SOURCES,+ comicLetteringIssues,+ getAllChecks,+ proseStageIssues,+} from '../../../lib/editorial/index.js';+import { canonicalStringify } from '../../../lib/objects.js';+import { getSettings } from '../../settings.js';+import {+ buildCompletenessContext,+ collectManuscriptSections,+ completenessSourceHash,+ sectionsCorpus,+} from '../arcPlanner.js';+import { getFactsLedger } from '../continuityBible.js';+import { getSeriesEditorial } from '../editorialAnalysis.js';+import { listIssuesForSeries } from '../issues.js';+import { getReview } from '../manuscriptReview.js';+import { getReverseOutline } from '../reverseOutline.js';+import { getSeries } from '../series.js';+import { getSeriesCanon } from '../seriesCanon.js';++// Source-content fingerprinting for finding staleness (#1345, #1387). Each+// finding is stamped with a hash of the exact content its check analyzed; the+// manuscript editor / triage view flags a finding `stale` once that content+// drifts.+//+// Per-check declared sources (#1387): a check declares the inputs its run()+// reads via `check.sources` (a subset of EDITORIAL_SOURCES), and we fingerprint+// EXACTLY those. `canonicalStringify` keeps hashes stable across machines. The+// load-time guard below ensures a newly declared source cannot silently hash as+// empty.+const HASH_SEP = '\u0000';+const sha256 = (text) => createHash('sha256').update(text || '').digest('hex');+const SOURCE_RESOLVERS = {+ manuscript: ({ manuscript }) => manuscript || '',+ canon: ({ canon }) => canonicalStringify(canon ?? null),+ continuityBible: ({ continuityBible }) => canonicalStringify(continuityBible ?? null),+ 'series.styleGuide': ({ series }) => canonicalStringify(series?.styleGuide ?? null),+ 'series.arc.tickingClock': ({ series }) => canonicalStringify(series?.arc?.tickingClock ?? null),+ 'series.arc.readerMap': ({ series }) => canonicalStringify(series?.arc?.readerMap ?? null),+ 'series.arc.foreshadowing': ({ series }) => canonicalStringify(series?.arc?.foreshadowing ?? null),+ 'series.arc.themes': ({ series }) => canonicalStringify(series?.arc?.themes ?? null),+ 'series.factReference': ({ series }) => canonicalStringify(series?.factReference ?? null),+ reverseOutline: ({ reverseOutline }) => canonicalStringify(reverseOutline ?? null),+ 'reverseOutline.plotlines': ({ reverseOutlinePlotlines }) =>+ canonicalStringify(reverseOutlinePlotlines ?? null),+ editorialArcs: ({ editorialArcs, editorialArcsComplete }) =>+ canonicalStringify({ arcs: editorialArcs ?? null, complete: editorialArcsComplete === true }),+ 'series.characterArcs': ({ series }) => canonicalStringify(series?.characterArcs ?? null),+ 'storyboard.shots': ({ storyboardScenes }) =>+ canonicalStringify(projectStoryboardContinuity(storyboardScenes) ?? null),+ comicScript: ({ comicScripts }) => canonicalStringify(comicScripts ?? null),+ 'comicScript.pacing': ({ comicPacingContent }) => canonicalStringify(comicPacingContent ?? null),+ 'comicScript.layout': ({ comicLayoutContent }) => canonicalStringify(comicLayoutContent ?? null),+ prose: ({ proseContent }) => canonicalStringify(proseContent ?? null),+};++function collectStoryboardScenes(issues) {+ const out = [];+ for (const issue of (Array.isArray(issues) ? issues : [])) {+ const scenes = issue?.stages?.storyboards?.scenes;+ if (!Array.isArray(scenes) || !scenes.length) continue;+ const issueNumber = Number.isInteger(issue.number) ? issue.number : null;+ for (const scene of scenes) {+ if (scene && typeof scene === 'object') out.push({ issueNumber, scene });+ }+ }+ return out;+}++function projectStoryboardContinuity(storyboardScenes) {+ return (Array.isArray(storyboardScenes) ? storyboardScenes : []).map(({ issueNumber, scene }) => ({+ issueNumber: Number.isInteger(issueNumber) ? issueNumber : null,+ heading: typeof scene?.heading === 'string' ? scene.heading : '',+ slugline: typeof scene?.slugline === 'string' ? scene.slugline : '',+ shots: (Array.isArray(scene?.shots) ? scene.shots : []).map((shot) => ({+ id: typeof shot?.id === 'string' ? shot.id : '',+ continuityFromShotId: typeof shot?.continuityFromShotId === 'string' ? shot.continuityFromShotId : null,+ screenDirection: typeof shot?.screenDirection === 'string' ? shot.screenDirection : null,+ shotType: typeof shot?.shotType === 'string' ? shot.shotType : null,+ description: typeof shot?.description === 'string' ? shot.description : '',+ })),+ }));+}++function projectComicLetteringContent(comicIssues) {+ return comicIssues.map(({ number, pages }) => ({+ number,+ pages: pages.map((page) => ({+ panels: (Array.isArray(page?.panels) ? page.panels : []).map((panel) => ({+ caption: typeof panel?.caption === 'string' ? panel.caption : '',+ dialogue: Array.isArray(panel?.dialogue) ? panel.dialogue : [],+ sfx: typeof panel?.sfx === 'string' ? panel.sfx : '',+ })),+ })),+ }));+}++function projectComicPacingContent(comicIssues) {+ return comicIssues.map(({ number, pages }) => ({+ number,+ pages: pages.map((page) => ({+ panels: (Array.isArray(page?.panels) ? page.panels : []).map((panel) => ({+ description: typeof panel?.description === 'string' ? panel.description : '',+ caption: typeof panel?.caption === 'string' ? panel.caption : '',+ dialogue: Array.isArray(panel?.dialogue) ? panel.dialogue : [],+ sfx: typeof panel?.sfx === 'string' ? panel.sfx : '',+ })),+ })),+ }));+}++function projectComicLayoutContent(comicIssues) {+ return comicIssues.map(({ number, pages }) => ({+ number,+ panelCounts: pages.map((page) => (Array.isArray(page?.panels) ? page.panels.length : 0)),+ }));+}++function projectEditorialArcs(editorial) {+ const chars = Array.isArray(editorial?.characters) ? editorial.characters : [];+ return chars.map((character) => ({+ name: character?.name || '',+ arcDirection: character?.arcDirection || 'flat',+ issueCount: Number.isFinite(character?.issueCount) ? character.issueCount : 0,+ isProtagonist: character?.isProtagonist === true,+ }));+}++function editorialCoverageComplete(editorial) {+ const coverage = editorial?.coverage;+ return !!coverage+ && coverage.withContent > 0+ && coverage.analyzed >= coverage.withContent+ && (coverage.stale || 0) === 0;+}++for (const token of EDITORIAL_SOURCES) {+ if (typeof SOURCE_RESOLVERS[token] !== 'function') {+ throw new Error(`checkRunner: editorial source "${token}" has no fingerprint resolver — keep SOURCE_RESOLVERS in sync with EDITORIAL_SOURCES`);+ }+}++export function checkSources(check) {+ const declared = Array.isArray(check?.sources) && check.sources.length+ ? check.sources+ : (check?.needsManuscript ? ['manuscript', 'canon'] : ['canon']);+ return declared.filter((token) => SOURCE_RESOLVERS[token]);+}++export function effectiveCheckSources(check, checkById) {+ const own = checkSources(check);+ const deps = Array.isArray(check?.dependsOn) ? check.dependsOn : [];+ if (!deps.length || !(checkById instanceof Map)) return own;+ const tokens = new Set(own);+ const seen = new Set([check?.id]);+ const stack = [...deps];+ while (stack.length) {+ const id = stack.pop();+ if (seen.has(id)) continue;+ seen.add(id);+ const dep = checkById.get(id);+ if (!dep) continue;+ for (const token of checkSources(dep)) tokens.add(token);+ for (const next of (Array.isArray(dep.dependsOn) ? dep.dependsOn : [])) {+ if (!seen.has(next)) stack.push(next);+ }+ }+ return [...tokens];+}++function resolveSources(inputs) {+ const resolved = {};+ for (const token of EDITORIAL_SOURCES) resolved[token] = SOURCE_RESOLVERS[token](inputs);+ return resolved;+}++export function fingerprintForCheck(check, resolved, checkById = null) {+ const segments = [...new Set(effectiveCheckSources(check, checkById))]+ .sort()+ .map((token) => `${token}=${resolved[token]}`);+ if (check?.isCustom && typeof check.prompt === 'string') {+ segments.push(`definition=${check.prompt}`);+ }+ return sha256(segments.join(HASH_SEP));+}++/**+ * Project the raw editorial data sources once for both the check-run context and+ * read-time fingerprinting. The returned context fields are the exact values+ * checks consume; `resolvedSources` is their stable token-to-string projection.+ */+export function buildEditorialSourceProjection({+ manuscript,+ canon,+ series,+ issues,+ outline,+ editorial,+ bible,+}) {+ const continuityBible = Array.isArray(bible?.facts) ? bible.facts : [];+ const storyboardScenes = collectStoryboardScenes(issues);+ const reverseOutline = Array.isArray(outline?.scenes) ? outline.scenes : [];+ const reverseOutlinePlotlines = Array.isArray(outline?.plotlines) ? outline.plotlines : [];+ const editorialArcs = projectEditorialArcs(editorial);+ const editorialArcsComplete = editorialCoverageComplete(editorial);+ const comicIssues = comicLetteringIssues(issues);+ const comicScripts = projectComicLetteringContent(comicIssues);+ const comicPacingContent = projectComicPacingContent(comicIssues);+ const comicLayoutContent = projectComicLayoutContent(comicIssues);+ const proseContent = proseStageIssues(issues);+ const resolvedSources = resolveSources({+ manuscript,+ canon,+ continuityBible,+ series,+ reverseOutline,+ reverseOutlinePlotlines,+ editorialArcs,+ editorialArcsComplete,+ storyboardScenes,+ comicScripts,+ comicPacingContent,+ comicLayoutContent,+ proseContent,+ });+ return {+ continuityBible,+ storyboardScenes,+ reverseOutline,+ reverseOutlinePlotlines,+ editorialArcs,+ editorialArcsComplete,+ resolvedSources,+ };+}++/**+ * Read the manuscript review and derive `stale` against the exact content each+ * editorial check or completeness pass analyzed. The annotation is never+ * persisted and therefore never rides the synced review document.+ */+export async function getReviewWithStaleness(seriesId) {+ const review = await getReview(seriesId);+ const settings = await getSettings();+ const byId = new Map(getAllChecks(settings).map((check) => [check.id, check]));+ const checkFor = (id) => byId.get(id) || null;+ const evaluable = review.comments.filter((comment) =>+ comment.checkId && comment.sourceContentHash && checkFor(comment.checkId));+ const completeness = review.comments.filter((comment) =>+ !comment.checkId && comment.sourceContentHash);+ if (!evaluable.length && !completeness.length) return review;++ if (!evaluable.length) {+ const [series, sections] = await Promise.all([+ getSeries(seriesId),+ collectManuscriptSections(seriesId),+ ]);+ const context = await buildCompletenessContext(series, sectionsCorpus(sections));+ const current = completenessSourceHash(context);+ return {+ ...review,+ comments: review.comments.map((comment) => (!comment.checkId && comment.sourceContentHash+ ? { ...comment, stale: comment.sourceContentHash !== current }+ : comment)),+ };+ }++ const sourcesFor = (id) => effectiveCheckSources(checkFor(id), byId);+ const needsManuscript = completeness.length > 0+ || evaluable.some((comment) => sourcesFor(comment.checkId).includes('manuscript'));+ const needsReverseOutline = evaluable.some((comment) => {+ const sources = sourcesFor(comment.checkId);+ return sources.includes('reverseOutline') || sources.includes('reverseOutline.plotlines');+ });+ const needsEditorialArcs = evaluable.some((comment) =>+ sourcesFor(comment.checkId).includes('editorialArcs'));+ const needsContinuityBible = evaluable.some((comment) =>+ sourcesFor(comment.checkId).includes('continuityBible'));+ const needsStoryboards = evaluable.some((comment) =>+ sourcesFor(comment.checkId).includes('storyboard.shots'));+ const needsComicScript = evaluable.some((comment) => {+ const sources = sourcesFor(comment.checkId);+ return sources.includes('comicScript')+ || sources.includes('comicScript.pacing')+ || sources.includes('comicScript.layout');+ });+ const needsProse = evaluable.some((comment) => sourcesFor(comment.checkId).includes('prose'));+ const needsIssues = needsStoryboards || needsComicScript || needsProse;+ const series = await getSeries(seriesId);+ const [sections, canon, outline, editorial, issues, bible] = await Promise.all([+ needsManuscript ? collectManuscriptSections(seriesId) : Promise.resolve([]),+ getSeriesCanon(series),+ needsReverseOutline ? getReverseOutline(seriesId).catch(() => null) : Promise.resolve(null),+ needsEditorialArcs ? getSeriesEditorial(seriesId, { series }).catch(() => null) : Promise.resolve(null),+ needsIssues ? listIssuesForSeries(seriesId).catch(() => []) : Promise.resolve([]),+ needsContinuityBible ? getFactsLedger(seriesId).catch(() => null) : Promise.resolve(null),+ ]);+ const { resolvedSources } = buildEditorialSourceProjection({+ manuscript: sectionsCorpus(sections),+ canon,+ series,+ issues,+ outline,+ editorial,+ bible,+ });+ const currentCompletenessHash = completeness.length > 0+ ? completenessSourceHash(await buildCompletenessContext(series, resolvedSources.manuscript))+ : null;+ return {+ ...review,+ comments: review.comments.map((comment) => {+ if (!comment.checkId && comment.sourceContentHash) {+ return { ...comment, stale: comment.sourceContentHash !== currentCompletenessHash };+ }+ const check = comment.checkId && comment.sourceContentHash+ ? checkFor(comment.checkId)+ : null;+ if (!check) return comment;+ const current = fingerprintForCheck(check, resolvedSources, byId);+ return { ...comment, stale: comment.sourceContentHash !== current };+ }),+ };+}diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.jsindex c2ad2727ed..eea436283b 100644--- a/server/services/pipeline/foundationJudge.js+++ b/server/services/pipeline/foundationJudge.js@@ -36,15 +36,13 @@*/import { join } from 'path';-import { createHash } from 'crypto';import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';import { runStagedLLM, resolveStageContext, resolveJudgeForStage } from '../../lib/stageRunner.js';import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextBudget.js';import { getStage } from '../promptService.js';import { composeStyleNotes, sanitizeStyleGuide, STYLE_GUIDE_LIMITS } from '../../lib/styleGuide.js';-import { renderCharacterArcsForPrompt, sanitizeCharacterArcList } from '../../lib/seriesCharacterArc.js';+import { sanitizeCharacterArcList } from '../../lib/seriesCharacterArc.js';import { BIBLE_KEYS, BIBLE_SOURCE, sanitizeCharacter } from '../../lib/storyBible.js';-import { renderEntitiesSummary } from '../../lib/universePromptRenderers.js';import { getUniverse, updateUniverse } from '../universeBuilder.js';import { isBlankString, isBlankArray } from '../universeCharacterExpand.js';import { expandWorldTemplate, narrativeRepairTargets } from '../universeBuilderExpand.js';@@ -59,6 +57,35 @@ import {verifyArc,} from './arcPlanner.js';import { createArcMutationLedger } from './arcMutationLedger.js';+import {+ FRAMEWORK_STRING_FIELDS,+ PROFILE_STRING_FIELDS,+ VISUAL_FOUNDATION_LIST_FIELDS,+ VISUAL_FOUNDATION_STRING_FIELDS,+ buildFoundationContext,+ contentHash,+ countFoundationCharacterBlanks,+ foundationInputs,+ foundationInputsHash,+ pickFrameworkFields,+ pickVisualFoundationFields,+ rankFoundationCharacters,+ renderArc,+ renderCharacterLine,+ renderWorldFoundation,+ repairableSeriesFoundationCharacters,+ seriesFoundationCharacters,+} from './foundationJudgeContext.js';++// Compatibility surface: callers keep importing these projection helpers from+// foundationJudge.js while their implementation lives with the context builder.+export {+ countFoundationCharacterBlanks,+ foundationInputs,+ foundationInputsHash,+ rankFoundationCharacters,+ seriesFoundationCharacters,+};const STAGE = 'pipeline-judge-foundation';const REPAIR_STAGE = 'pipeline-foundation-repair';@@ -145,120 +172,6 @@ function assertValidSeriesId(id) {const foundationDir = () => join(PATHS.data, 'pipeline-foundation-judge');const snapshotPath = (seriesId) => join(foundationDir(), `${seriesId}.json`);-// ---------- input hashing (fast-pass / staleness) ------------// The judged foundation as a stable, hashable projection: universe canon,-// character records, the full synopsis plan, authored character arcs, and the-// series voice. A change-// to ANY of these flips the pinned hash so a re-judge re-runs; an unchanged-// foundation short-circuits to the cached verdict. Kept deliberately narrow —-// only the fields the judge actually reads — so an unrelated series edit (e.g. a-// render slot) doesn't needlessly invalidate the score.-export function foundationInputs(series, universe, issues = []) {- const characters = Array.isArray(universe?.characters) ? universe.characters : [];- const seriesCharacters = seriesFoundationCharacters(characters, series, issues);- const episodeInputs = [...(Array.isArray(issues) ? issues : [])]- .sort((a, b) => String(a?.seasonId || '').localeCompare(String(b?.seasonId || ''))- || (a?.number ?? 9999) - (b?.number ?? 9999)- || String(a?.id || '').localeCompare(String(b?.id || '')))- .map((issue) => ({- id: issue?.id || '',- seasonId: issue?.seasonId || '',- number: issue?.number ?? null,- title: issue?.title || '',- synopsis: issue?.stages?.idea?.input || '',- }));- return {- world: universe- ? {- // The starter prompt is the author's protected originating intent, not- // just another generated bible paragraph. A change here must invalidate- // a cached verdict, and the judge must compare every derived field to it- // so a polished-but-off-premise foundation cannot fast-pass forever.- starterPrompt: universe.starterPrompt || '',- logline: universe.logline || '',- premise: universe.premise || '',- styleNotes: universe.styleNotes || '',- influences: universe.influences || null,- // Places/objects are rendered into the world summary the judge scores,- // so a user edit to either must flip the pinned hash (otherwise a clean- // verdict would wrongly fast-pass a changed world).- places: Array.isArray(universe.places) ? universe.places : [],- objects: Array.isArray(universe.objects) ? universe.objects : [],- }- : null,- // A linked universe can contain characters belonging to other stories. Only- // the cast referenced by THIS series is judged and hashed; otherwise an- // unrelated blank universe asset can keep an otherwise-ready series trapped- // in the character repair loop forever.- characters: seriesCharacters.map((c) => ({- id: c.id,- name: c.name,- role: c.role || '',- ...pickFrameworkFields(c),- ...pickProfileFields(c),- ...pickVisualFoundationFields(c),- })),- arc: series?.arc || null,- seasons: Array.isArray(series?.seasons)- ? series.seasons.map((s) => ({- id: s.id,- number: s.number,- title: s.title || '',- logline: s.logline || '',- synopsis: s.synopsis || '',- endingHook: s.endingHook || '',- }))- : [],- episodes: episodeInputs,- characterArcs: Array.isArray(series?.characterArcs) ? series.characterArcs : [],- voice: {- styleNotes: series?.styleNotes || '',- styleGuide: series?.styleGuide || null,- },- };-}--// The character-framework subset the character dimension scores (Ghost → Wound →-// Lie → Want → Need chain + secrets + arc fields). Shared by the hash projection-// and the "thinnest character" fix target so both read the SAME field set.-const FRAMEWORK_STRING_FIELDS = Object.freeze(['ghost', 'wound', 'lie', 'want', 'need', 'coreTheme', 'motivations', 'speechPattern']);-// A dramatic engine alone does not make a complete bible card. These fields-// prevent a later drafter or renderer from having to invent a supporting-// character's identity, behavior, and capabilities after the plot is settled.-const PROFILE_STRING_FIELDS = Object.freeze([- 'pronouns', 'age', 'speechAccent', 'personality', 'background',- 'likes', 'dislikes', 'mannerisms', 'relationships', 'skills',-]);-// Identity-bearing visual axes a graphic-novel lead needs before the plot is-// allowed to grow around them. This intentionally stops short of requiring a-// human facial-expression or wardrobe sheet from non-human characters.-const VISUAL_FOUNDATION_STRING_FIELDS = Object.freeze([- 'physicalDescription', 'visualNotes', 'silhouetteNotes', 'visualIdentity',-]);-const VISUAL_FOUNDATION_LIST_FIELDS = Object.freeze(['colorPalette']);-function pickFrameworkFields(c) {- const out = {};- for (const f of FRAMEWORK_STRING_FIELDS) out[f] = c?.[f] || '';- out.arcType = c?.arcType || '';- out.secrets = Array.isArray(c?.secrets) ? c.secrets : [];- return out;-}--function pickProfileFields(c) {- return Object.fromEntries(PROFILE_STRING_FIELDS.map((field) => [field, c?.[field] || '']));-}--function pickVisualFoundationFields(c) {- const out = {};- for (const field of VISUAL_FOUNDATION_STRING_FIELDS) out[field] = c?.[field] || '';- for (const field of VISUAL_FOUNDATION_LIST_FIELDS) out[field] = Array.isArray(c?.[field]) ? c[field] : [];- return out;-}--const contentHash = (value) => createHash('sha256').update(JSON.stringify(value ?? null)).digest('hex');-export const foundationInputsHash = (series, universe, issues = []) => contentHash(foundationInputs(series, universe, issues));-// ---------- weighted composite math ----------const clampScore = (v, fallback = 0) => {@@ -427,140 +340,7 @@ export function isFoundationStale(snap, currentHash) {return snap.sourceInputsHash !== currentHash;}-// ---------- context assembly ------------// Render one character's framework completeness so the judge can see which of-// the Wound/Lie/Want/Need chain is present vs. blank (the character dimension's-// core signal) without dumping the whole record.-function renderCharacterLine(c, { core = false } = {}) {- const role = c?.role ? ` (${c.role})` : '';- const concise = (value, maxChars = 100) => {- if (typeof value !== 'string' || !value.trim()) return '—';- const compact = value.trim().replace(/\s+/g, ' ');- return compact.length <= maxChars ? compact : `${compact.slice(0, maxChars - 1).trimEnd()}…`;- };- const framework = FRAMEWORK_STRING_FIELDS- .map((field) => `${field}: ${concise(c?.[field])}`)- .join(' | ');- const profile = PROFILE_STRING_FIELDS- .map((field) => `${field}: ${concise(c?.[field])}`)- .join(' | ');- const secrets = (Array.isArray(c?.secrets) ? c.secrets : [])- .map(concise)- .slice(0, 3)- .join('; ');- // The harsh judge needs the actual render identity, not a presence marker.- // `ready` proved actively misleading: five complete character sheets were- // scored as absent because the prompt hid every distinguishing detail. Keep- // the lines bounded, but show enough anatomy, silhouette, palette, and visual- // grammar to compare the cast and identify generic or contradictory designs.- const visualString = (field) => (isBlankString(c?.[field]) ? 'BLANK' : concise(c[field], 320));- const visualList = (field) => {- if (isBlankArray(c?.[field])) return 'BLANK';- const compact = JSON.stringify(c[field]).replace(/\s+/g, ' ');- return compact.length <= 420 ? compact : `${compact.slice(0, 419).trimEnd()}…`;- };- const visual = [- ...VISUAL_FOUNDATION_STRING_FIELDS.map((field) => `${field}: ${visualString(field)}`),- ...VISUAL_FOUNDATION_LIST_FIELDS.map((field) => `${field}: ${visualList(field)}`),- ].join(' | ');- return `- ${core ? '[CORE] ' : ''}**${c?.name || 'Unnamed'}**${role} — dramatic framework: ${framework} | profile: ${profile} | arcType: ${c?.arcType || '—'} | secrets: ${secrets || '—'} | visual foundation: ${visual}`;-}--function countOccurrences(text, value) {- const haystack = String(text || '').toLocaleLowerCase();- const needle = String(value || '').trim().toLocaleLowerCase();- if (!needle) return 0;- let count = 0;- let cursor = 0;- while ((cursor = haystack.indexOf(needle, cursor)) !== -1) {- count += 1;- cursor += needle.length;- }- return count;-}--export function rankFoundationCharacters(characters, series, issues = [], { includeLocked = false } = {}) {- const list = Array.isArray(characters) ? characters : [];- const storyText = JSON.stringify({- logline: series?.logline || '',- premise: series?.premise || '',- arc: series?.arc || null,- seasons: series?.seasons || [],- characterArcs: series?.characterArcs || [],- episodes: (Array.isArray(issues) ? issues : []).map((issue) => ({- title: issue?.title || '',- synopsis: issue?.stages?.idea?.input || '',- })),- });- const authoredArcKeys = new Set((Array.isArray(series?.characterArcs) ? series.characterArcs : [])- .flatMap((arc) => [- arc?.characterId || '',- arc?.characterName ? `name:${arc.characterName.trim().toLowerCase()}` : '',- ])- .filter(Boolean));- return list- .filter((character) => character && (includeLocked || character.locked !== true))- .map((character, index) => {- const blanks = FRAMEWORK_STRING_FIELDS.filter((field) => isBlankString(character[field])).length- + PROFILE_STRING_FIELDS.filter((field) => isBlankString(character[field])).length- + (isBlankArray(character.secrets) ? 1 : 0)- + VISUAL_FOUNDATION_STRING_FIELDS.filter((field) => isBlankString(character[field])).length- + VISUAL_FOUNDATION_LIST_FIELDS.filter((field) => isBlankArray(character[field])).length;- const mentions = countOccurrences(storyText, character.name);- const authoredArc = authoredArcKeys.has(character.id)- || authoredArcKeys.has(`name:${String(character.name || '').trim().toLowerCase()}`);- const coreRole = /protagonist|lead|hero|antagonist|villain|deuteragonist|mentor/i.test(character.role || '');- const seriesOwned = !!series?.id && character.sourceSeriesId === series.id;- return { character, index, mentions, authoredArc, coreRole, seriesOwned, blanks };- })- .sort((a, b) => Number(b.authoredArc) - Number(a.authoredArc)- || Number(b.seriesOwned) - Number(a.seriesOwned)- || Number(b.coreRole) - Number(a.coreRole)- || b.mentions - a.mentions- || b.blanks - a.blanks- || a.index - b.index);-}--/**- * Resolve the cast that belongs to this series from actual story references.- * Once a plot exists, every named/arc-linked character is retained: there is no- * arbitrary top-N cap. Before a plot exists, a small ranked fallback gives the- * character architect enough principals to start from without drafting every- * unrelated person in a shared universe.- *- * Locked referenced characters remain in this returned roster because the- * judge still has to see constraints it cannot repair. Repair callers filter- * them separately.- */-export function seriesFoundationCharacters(characters, series, issues = []) {- const ranked = rankFoundationCharacters(characters, series, issues, { includeLocked: true });- const referenced = ranked.filter(({ authoredArc, mentions, seriesOwned }) => authoredArc || mentions > 0 || seriesOwned);- const selected = referenced.length > 0 ? referenced : ranked.slice(0, 6);- return selected.map(({ character }) => character);-}--function repairableSeriesFoundationCharacters(characters, series, issues = []) {- return seriesFoundationCharacters(characters, series, issues)- .filter((character) => character?.locked !== true);-}--/**- * Blank foundation fields across the cast a `character` repair is allowed to- * write — the series roster minus locked members, over the SAME framework,- * profile, and visual field sets the character dimension is scored on.- *- * This is the gate's objective, LLM-free second opinion on a repair the judge- * scored as a tie. A judge can misread the cast — a presence-marker render once- * showed every authored design as the bare word `ready`, so a complete five-sheet- * character foundation was scored as absent and thrown away — but "25 named- * fields went from empty to authored" is a fact on disk, not an opinion.- */-export function countFoundationCharacterBlanks(characters, series, issues = []) {- const targets = repairableSeriesFoundationCharacters(characters, series, issues);- return rankFoundationCharacters(targets, series, issues)- .reduce((total, { blanks }) => total + blanks, 0);-}+// ---------- context record reads ----------/*** `countFoundationCharacterBlanks` against live records. Pass `charactersOverride`@@ -578,191 +358,6 @@ export async function readFoundationCharacterBlanks(seriesId, charactersOverridereturn countFoundationCharacterBlanks(characters, series, issues);}-const joinedLength = (lines) => lines.reduce((total, line) => total + line.length + 1, 0);--const pluralLines = (count) => (count === 1 ? 'line' : 'lines');--// Last-resort clamp for `renderArc`. Every tier above it drops WHOLE lines so the-// render stays coherent, but a budget smaller than the arc header itself (or a-// series with more volume loglines than the budget has room for) can still-// overrun — and `maxChars` is a hard contract, not a target. Slice, and keep the-// marker only when there is room for it.-const ARC_TRUNCATION_NOTE = '\n[series plan truncated to fit the prompt budget]';-function clampArcToBudget(text, maxChars) {- if (!Number.isFinite(maxChars) || text.length <= maxChars) return text;- if (maxChars <= ARC_TRUNCATION_NOTE.length) return text.slice(0, Math.max(0, maxChars));- return `${text.slice(0, maxChars - ARC_TRUNCATION_NOTE.length)}${ARC_TRUNCATION_NOTE}`;-}--/**- * Render the synopsis-level series plan: arc header, per-volume loglines and- * synopses, the episode list under each volume, and the authored character arcs.- *- * `maxChars` is a HARD bound on the result, spent in tiers so the render always- * degrades to something coherent rather than being sliced mid-sentence:- *- * 1. Drop WHOLE episode synopsis lines from the end. Earliest episodes survive- * a tight budget because that's where a character arc's opening transitions- * hang.- * 2. If the spine alone (arc header + every volume's logline/synopsis/hook +- * the authored character arcs) still overruns, drop the per-volume synopsis- * and ending-hook lines, keeping `V# title: logline` so the volume order and- * shape survive. Every episode goes with them.- * 3. Slice, as a floor, when even the loglines cannot fit — a caller that set a- * budget gets a smaller string, never a longer one.- *- * Each tier names what it left out, so the model can tell a short plan from a- * budgeted one.- *- * Unbudgeted (the default) the output is byte-identical to the pre-budget- * render, so the foundation judge's own section-level truncation is unchanged.- */-function renderArc(series, issues = [], { maxChars = Infinity, includeArcTransitions = false } = {}) {- const arc = series?.arc || {};- const seasons = Array.isArray(series?.seasons) ? [...series.seasons].sort((a, b) => (a.number || 0) - (b.number || 0)) : [];- const orderedIssues = [...(Array.isArray(issues) ? issues : [])]- .sort((a, b) => (a?.number ?? 9999) - (b?.number ?? 9999));- const themes = Array.isArray(arc.themes) ? arc.themes.join(', ') : (arc.themes || '');- const head = [- `Logline: ${arc.logline || '(none)'}`,- `Summary: ${arc.summary || '(none)'}`,- `Themes: ${themes || '(none)'}`,- `Protagonist arc: ${arc.protagonistArc || '(none)'}`,- `Shape: ${arc.shape || '(unset)'}`,- '',- `Volumes (${seasons.length}):`,- ];- const volumes = seasons.map((season) => {- const logline = ` V${season.number ?? '?'} ${season.title || ''}: ${season.logline || '(no logline)'}`;- const detail = [` Synopsis: ${season.synopsis || '(none)'}`];- if (season.endingHook) detail.push(` Ending hook: ${season.endingHook}`);- const episodes = orderedIssues- .filter((issue) => issue?.seasonId === season.id)- .map((issue) => ` #${issue.number ?? '?'} ${issue.title || 'Untitled'}: ${issue?.stages?.idea?.input || '(no synopsis)'}`);- return { logline, detail, episodes };- });- const characterArcs = Array.isArray(series?.characterArcs) ? series.characterArcs : [];- const tail = ['', `Authored character arcs (${characterArcs.length}):`];- if (includeArcTransitions) {- tail.push(renderCharacterArcsForPrompt(characterArcs) || '(none)');- } else {- for (const characterArc of characterArcs) {- tail.push(` - ${characterArc.characterName || characterArc.characterId || 'Unnamed'}: ${characterArc.startState || '(no start)'} → ${characterArc.endState || '(no end)'}; want=${characterArc.want || '—'}; need=${characterArc.need || '—'}`);- }- }-- // Tier 1: the full spine is unconditional; episodes fill whatever is left.- const fullSpine = [...head, ...volumes.flatMap((volume) => [volume.logline, ...volume.detail]), ...tail];- let remaining = maxChars - joinedLength(fullSpine);- const notes = [];- // Tier 2: the spine alone overruns, so the per-volume synopsis/hook lines go- // and every episode goes with them — dropping craft detail to make room for- // episode lines would invert the priority the tiers exist to express.- const withDetail = remaining >= 0;- if (!withDetail) {- const droppedDetail = volumes.reduce((total, volume) => total + volume.detail.length, 0);- if (droppedDetail > 0) {- notes.push(` [${droppedDetail} volume synopsis ${pluralLines(droppedDetail)} omitted to fit the prompt budget]`);- }- remaining = -1;- }- let omitted = 0;- const lines = [...head];- for (const volume of volumes) {- lines.push(volume.logline);- if (withDetail) lines.push(...volume.detail);- for (const episode of volume.episodes) {- if (episode.length + 1 <= remaining) {- lines.push(episode);- remaining -= episode.length + 1;- } else {- omitted += 1;- }- }- }- if (omitted > 0) lines.push(` [${omitted} later episode synopsis ${pluralLines(omitted)} omitted to fit the prompt budget]`);- lines.push(...notes, ...tail);- return clampArcToBudget(lines.join('\n'), maxChars);-}--// Below this the named-canon line carries no usable signal — render the-// omission marker instead of a handful of dangling entity names.-const NAMED_CANON_MIN_CHARS = 200;--/**- * Render the world as the worldbuilding dimension is scored on it, bounded by- * `maxChars`.- *- * The budget is spent by dropping the NAMED-CANON inventory, never the narrative- * spine. Causal rules, costs, hard limits, and failure modes live in the premise- * and style notes; the entity list is the noun inventory whose over-supply the- * judge already penalizes, and it is the part that grows without bound. Slicing- * the joined block instead (what this did before) cut the TAIL of the premise —- * exactly where a freshly authored ruleset lands — so a world repair the judge- * had just demanded became invisible to the next judge, the score never moved,- * and the foundation gate burned its rounds against a repair it could not see.- */-function renderWorldFoundation(universe, { maxChars = Infinity } = {}) {- if (!universe) return '(no linked universe — worldbuilding cannot be judged from canon)';- const influences = universe.influences && typeof universe.influences === 'object'- ? `Embrace: ${(universe.influences.embrace || []).join(', ') || '—'}; Avoid: ${(universe.influences.avoid || []).join(', ') || '—'}`- : '(none)';- const spine = [- `Protected author intent (starter idea): ${universe.starterPrompt || '(none)'}`,- `Universe logline: ${universe.logline || '(none)'}`,- `Universe premise: ${universe.premise || '(none)'}`,- `Universe style: ${universe.styleNotes || '(none)'}`,- `Influences: ${influences}`,- ].join('\n');- const entities = renderEntitiesSummary(universe, { maxPerKind: { characters: 0 } }) || '(no named places or objects)';- const canonLine = `Named canon: ${entities}`;- const remaining = maxChars - spine.length - 1;- if (canonLine.length <= remaining) return `${spine}\n${canonLine}`;- if (remaining >= NAMED_CANON_MIN_CHARS) return `${spine}\n${canonLine.slice(0, remaining - 1).trimEnd()}…`;- if (spine.length <= maxChars) return `${spine}\nNamed canon: [omitted to fit the judging budget]`;- // The spine alone overruns: the premise is larger than this judge model's- // world budget. Slicing is unavoidable here, but say so rather than letting- // the judge score a silently amputated world.- return `${spine.slice(0, maxChars)}\n\n[world summary truncated for judging]`;-}--// Build the judge's variable bag from the whole foundation. Content is budgeted-// to the judge model's window (a small/local judge trims to fit rather than-// overflowing; a big-context judge gets the whole foundation).-function buildFoundationContext({ series, universe, canon, issues = [], contentMax }) {- const characters = Array.isArray(canon?.characters) ? canon.characters : [];- const seriesCharacters = seriesFoundationCharacters(characters, series, issues);- const characterRoster = seriesCharacters.length- ? seriesCharacters.map((character) => renderCharacterLine(character, { core: true })).join('\n')- : '(no canon characters)';- const sectionMax = Math.max(1_000, Math.floor(contentMax / 3));- const world = renderWorldFoundation(universe, { maxChars: sectionMax });- // Character quality lives in the choices between start and end, not merely- // the endpoints. Reuse the canonical authored-arc renderer here so the judge- // sees decisions, relapses, sacrifices, and their issue placement. The- // repair prompt keeps the legacy compact summary because it already receives- // the full `series.characterArcs` JSON separately.- const arcText = renderArc(series, issues, { includeArcTransitions: true });- const roster = characterRoster.length > sectionMax- ? `${characterRoster.slice(0, sectionMax)}\n\n[character roster truncated for judging]`- : characterRoster;- const arcContext = arcText.length > sectionMax- ? `${arcText.slice(0, sectionMax)}\n\n[series plan truncated for judging]`- : arcText;- return {- series: {- name: series?.name || 'Untitled series',- logline: series?.logline || '',- premise: series?.premise || '',- styleNotes: composeStyleNotes(series, { proseCraft: true }),- },- worldEntitiesSummary: world,- characterRoster: roster,- characterCount: seriesCharacters.length,- arc: arcContext,- };-}-// One deliberate malformed-JSON retry (see module doc). Mirrors pipelineJudge.js.async function runFoundationJudgeStage(ctx, runOptions) {let lastError;diff --git a/server/services/pipeline/foundationJudge.test.js b/server/services/pipeline/foundationJudge.test.jsindex 4e27962198..ac73d768fe 100644--- a/server/services/pipeline/foundationJudge.test.js+++ b/server/services/pipeline/foundationJudge.test.js@@ -332,6 +332,8 @@ describe('foundationInputsHash + staleness — fast-pass pinning', () => {const issue = { id: 'iss-1', seasonId: 'sea-1', number: 1, stages: { idea: { input: 'Opening promise' } } };const base = foundationInputsHash(series, null, [issue]);expect(foundationInputsHash(series, null, [{ ...issue, stages: { idea: { input: 'Different promise' } } }])).not.toBe(base);+ expect(foundationInputsHash(series, null, [{ ...issue, arcRole: 'midpoint' }])).not.toBe(base);+ expect(foundationInputsHash(series, null, [{ ...issue, lengthProfile: 'extended' }])).not.toBe(base);expect(foundationInputsHash({ ...series, characterArcs: [{ characterId: 'chr-1', want: 'belong' }] }, null, [issue])).not.toBe(base);expect(foundationInputsHash({ ...series, styleNotes: 'lyrical' }, null, [issue])).not.toBe(base);});@@ -475,11 +477,36 @@ describe('renderArc — episode-list budget', () => {it('renders every episode when unbudgeted', () => {const out = __testing.renderArc(bigSeries, manyIssues);- expect(out).toContain('#1 Ep 1:');- expect(out).toContain('#40 Ep 40:');+ expect(out).toContain('#1 Ep 1 [role=unset, length=unset, 1 synopsis words]:');+ expect(out).toContain('#40 Ep 40 [role=unset, length=unset, 1 synopsis words]:');expect(out).not.toContain('omitted to fit the prompt budget');});+ it('renders authored episode metadata and exact synopsis word counts', () => {+ const issues = [+ {+ number: 1,+ seasonId: 'sea-1',+ title: 'Opening',+ arcRole: 'pilot',+ lengthProfile: 'teaser',+ stages: { idea: { input: 'Three deliberate words' } },+ },+ {+ number: 2,+ seasonId: 'sea-1',+ title: 'Finale',+ arcRole: 'finale',+ lengthProfile: 'custom',+ stages: { idea: { input: '' } },+ },+ ];++ const out = __testing.renderArc(bigSeries, issues);+ expect(out).toContain('#1 Opening [role=pilot, length=teaser, 3 synopsis words]: Three deliberate words');+ expect(out).toContain('#2 Finale [role=finale, length=custom, 0 synopsis words]: (no synopsis)');+ });+it('drops whole trailing episode lines to fit, keeping the plan spine intact', () => {const out = __testing.renderArc(bigSeries, manyIssues, { maxChars: 4_000 });// Spine survives: arc header, volume logline/synopsis/hook, authored arcs.@@ -490,8 +517,8 @@ describe('renderArc — episode-list budget', () => {expect(out).toContain('Authored character arcs (1):');// Earliest episodes are the ones kept; the tail is dropped by whole lines// (never sliced mid-sentence) and the omitted count is named.- expect(out).toContain('#1 Ep 1:');- expect(out).not.toContain('#40 Ep 40:');+ expect(out).toContain('#1 Ep 1 [');+ expect(out).not.toContain('#40 Ep 40 [');expect(out).toMatch(/\[\d+ later episode synopsis lines omitted to fit the prompt budget\]/);for (const line of out.split('\n')) {if (line.startsWith(' #')) expect(line.endsWith('x'.repeat(20))).toBe(true);@@ -512,7 +539,7 @@ describe('renderArc — episode-list budget', () => {expect(out).toContain('Logline: AL');expect(out).toContain(' V1 V1: VL');expect(out).not.toContain(' Synopsis: ');- expect(out).not.toContain('#1 Ep 1:');+ expect(out).not.toContain('#1 Ep 1 [');expect(out).toContain('[60 volume synopsis lines omitted to fit the prompt budget]');});diff --git a/server/services/pipeline/foundationJudgeContext.js b/server/services/pipeline/foundationJudgeContext.jsnew file mode 100644index 0000000000..ebfc019c04--- /dev/null+++ b/server/services/pipeline/foundationJudgeContext.js@@ -0,0 +1,458 @@+/**+ * Pure foundation-judge input projection, hashing, and prompt context assembly.+ *+ * The orchestration, persistence, and repair paths remain in foundationJudge.js;+ * this module owns the deterministic view of the foundation those paths judge.+ */++import { createHash } from 'crypto';+import { composeStyleNotes } from '../../lib/styleGuide.js';+import { renderCharacterArcsForPrompt } from '../../lib/seriesCharacterArc.js';+import { renderEntitiesSummary } from '../../lib/universePromptRenderers.js';+import { isBlankString, isBlankArray } from '../universeCharacterExpand.js';++// The character-framework subset the character dimension scores (Ghost → Wound →+// Lie → Want → Need chain + secrets + arc fields). Shared by the hash projection+// and the "thinnest character" fix target so both read the SAME field set.+export const FRAMEWORK_STRING_FIELDS = Object.freeze(['ghost', 'wound', 'lie', 'want', 'need', 'coreTheme', 'motivations', 'speechPattern']);+// A dramatic engine alone does not make a complete bible card. These fields+// prevent a later drafter or renderer from having to invent a supporting+// character's identity, behavior, and capabilities after the plot is settled.+export const PROFILE_STRING_FIELDS = Object.freeze([+ 'pronouns', 'age', 'speechAccent', 'personality', 'background',+ 'likes', 'dislikes', 'mannerisms', 'relationships', 'skills',+]);+// Identity-bearing visual axes a graphic-novel lead needs before the plot is+// allowed to grow around them. This intentionally stops short of requiring a+// human facial-expression or wardrobe sheet from non-human characters.+export const VISUAL_FOUNDATION_STRING_FIELDS = Object.freeze([+ 'physicalDescription', 'visualNotes', 'silhouetteNotes', 'visualIdentity',+]);+export const VISUAL_FOUNDATION_LIST_FIELDS = Object.freeze(['colorPalette']);++export function pickFrameworkFields(c) {+ const out = {};+ for (const f of FRAMEWORK_STRING_FIELDS) out[f] = c?.[f] || '';+ out.arcType = c?.arcType || '';+ out.secrets = Array.isArray(c?.secrets) ? c.secrets : [];+ return out;+}++function pickProfileFields(c) {+ return Object.fromEntries(PROFILE_STRING_FIELDS.map((field) => [field, c?.[field] || '']));+}++export function pickVisualFoundationFields(c) {+ const out = {};+ for (const field of VISUAL_FOUNDATION_STRING_FIELDS) out[field] = c?.[field] || '';+ for (const field of VISUAL_FOUNDATION_LIST_FIELDS) out[field] = Array.isArray(c?.[field]) ? c[field] : [];+ return out;+}++function countOccurrences(text, value) {+ const haystack = String(text || '').toLocaleLowerCase();+ const needle = String(value || '').trim().toLocaleLowerCase();+ if (!needle) return 0;+ let count = 0;+ let cursor = 0;+ while ((cursor = haystack.indexOf(needle, cursor)) !== -1) {+ count += 1;+ cursor += needle.length;+ }+ return count;+}++export function rankFoundationCharacters(characters, series, issues = [], { includeLocked = false } = {}) {+ const list = Array.isArray(characters) ? characters : [];+ const storyText = JSON.stringify({+ logline: series?.logline || '',+ premise: series?.premise || '',+ arc: series?.arc || null,+ seasons: series?.seasons || [],+ characterArcs: series?.characterArcs || [],+ episodes: (Array.isArray(issues) ? issues : []).map((issue) => ({+ title: issue?.title || '',+ synopsis: issue?.stages?.idea?.input || '',+ })),+ });+ const authoredArcKeys = new Set((Array.isArray(series?.characterArcs) ? series.characterArcs : [])+ .flatMap((arc) => [+ arc?.characterId || '',+ arc?.characterName ? `name:${arc.characterName.trim().toLowerCase()}` : '',+ ])+ .filter(Boolean));+ return list+ .filter((character) => character && (includeLocked || character.locked !== true))+ .map((character, index) => {+ const blanks = FRAMEWORK_STRING_FIELDS.filter((field) => isBlankString(character[field])).length+ + PROFILE_STRING_FIELDS.filter((field) => isBlankString(character[field])).length+ + (isBlankArray(character.secrets) ? 1 : 0)+ + VISUAL_FOUNDATION_STRING_FIELDS.filter((field) => isBlankString(character[field])).length+ + VISUAL_FOUNDATION_LIST_FIELDS.filter((field) => isBlankArray(character[field])).length;+ const mentions = countOccurrences(storyText, character.name);+ const authoredArc = authoredArcKeys.has(character.id)+ || authoredArcKeys.has(`name:${String(character.name || '').trim().toLowerCase()}`);+ const coreRole = /protagonist|lead|hero|antagonist|villain|deuteragonist|mentor/i.test(character.role || '');+ const seriesOwned = !!series?.id && character.sourceSeriesId === series.id;+ return { character, index, mentions, authoredArc, coreRole, seriesOwned, blanks };+ })+ .sort((a, b) => Number(b.authoredArc) - Number(a.authoredArc)+ || Number(b.seriesOwned) - Number(a.seriesOwned)+ || Number(b.coreRole) - Number(a.coreRole)+ || b.mentions - a.mentions+ || b.blanks - a.blanks+ || a.index - b.index);+}++/**+ * Resolve the cast that belongs to this series from actual story references.+ * Once a plot exists, every named/arc-linked character is retained: there is no+ * arbitrary top-N cap. Before a plot exists, a small ranked fallback gives the+ * character architect enough principals to start from without drafting every+ * unrelated person in a shared universe.+ *+ * Locked referenced characters remain in this returned roster because the+ * judge still has to see constraints it cannot repair. Repair callers filter+ * them separately.+ */+export function seriesFoundationCharacters(characters, series, issues = []) {+ const ranked = rankFoundationCharacters(characters, series, issues, { includeLocked: true });+ const referenced = ranked.filter(({ authoredArc, mentions, seriesOwned }) => authoredArc || mentions > 0 || seriesOwned);+ const selected = referenced.length > 0 ? referenced : ranked.slice(0, 6);+ return selected.map(({ character }) => character);+}++export function repairableSeriesFoundationCharacters(characters, series, issues = []) {+ return seriesFoundationCharacters(characters, series, issues)+ .filter((character) => character?.locked !== true);+}++/**+ * Blank foundation fields across the cast a `character` repair is allowed to+ * write — the series roster minus locked members, over the SAME framework,+ * profile, and visual field sets the character dimension is scored on.+ *+ * This is the gate's objective, LLM-free second opinion on a repair the judge+ * scored as a tie. A judge can misread the cast — a presence-marker render once+ * showed every authored design as the bare word `ready`, so a complete five-sheet+ * character foundation was scored as absent and thrown away — but "25 named+ * fields went from empty to authored" is a fact on disk, not an opinion.+ */+export function countFoundationCharacterBlanks(characters, series, issues = []) {+ const targets = repairableSeriesFoundationCharacters(characters, series, issues);+ return rankFoundationCharacters(targets, series, issues)+ .reduce((total, { blanks }) => total + blanks, 0);+}++// ---------- input hashing (fast-pass / staleness) ----------++// The judged foundation as a stable, hashable projection: universe canon,+// character records, the full synopsis plan, authored character arcs, and the+// series voice. A change+// to ANY of these flips the pinned hash so a re-judge re-runs; an unchanged+// foundation short-circuits to the cached verdict. Kept deliberately narrow —+// only the fields the judge actually reads — so an unrelated series edit (e.g. a+// render slot) doesn't needlessly invalidate the score.+export function foundationInputs(series, universe, issues = []) {+ const characters = Array.isArray(universe?.characters) ? universe.characters : [];+ const seriesCharacters = seriesFoundationCharacters(characters, series, issues);+ const episodeInputs = [...(Array.isArray(issues) ? issues : [])]+ .sort((a, b) => String(a?.seasonId || '').localeCompare(String(b?.seasonId || ''))+ || (a?.number ?? 9999) - (b?.number ?? 9999)+ || String(a?.id || '').localeCompare(String(b?.id || '')))+ .map((issue) => ({+ id: issue?.id || '',+ seasonId: issue?.seasonId || '',+ number: issue?.number ?? null,+ title: issue?.title || '',+ arcRole: issue?.arcRole || null,+ lengthProfile: issue?.lengthProfile || null,+ synopsis: issue?.stages?.idea?.input || '',+ }));+ return {+ world: universe+ ? {+ // The starter prompt is the author's protected originating intent, not+ // just another generated bible paragraph. A change here must invalidate+ // a cached verdict, and the judge must compare every derived field to it+ // so a polished-but-off-premise foundation cannot fast-pass forever.+ starterPrompt: universe.starterPrompt || '',+ logline: universe.logline || '',+ premise: universe.premise || '',+ styleNotes: universe.styleNotes || '',+ influences: universe.influences || null,+ // Places/objects are rendered into the world summary the judge scores,+ // so a user edit to either must flip the pinned hash (otherwise a clean+ // verdict would wrongly fast-pass a changed world).+ places: Array.isArray(universe.places) ? universe.places : [],+ objects: Array.isArray(universe.objects) ? universe.objects : [],+ }+ : null,+ // A linked universe can contain characters belonging to other stories. Only+ // the cast referenced by THIS series is judged and hashed; otherwise an+ // unrelated blank universe asset can keep an otherwise-ready series trapped+ // in the character repair loop forever.+ characters: seriesCharacters.map((c) => ({+ id: c.id,+ name: c.name,+ role: c.role || '',+ ...pickFrameworkFields(c),+ ...pickProfileFields(c),+ ...pickVisualFoundationFields(c),+ })),+ arc: series?.arc || null,+ seasons: Array.isArray(series?.seasons)+ ? series.seasons.map((s) => ({+ id: s.id,+ number: s.number,+ title: s.title || '',+ logline: s.logline || '',+ synopsis: s.synopsis || '',+ endingHook: s.endingHook || '',+ }))+ : [],+ episodes: episodeInputs,+ characterArcs: Array.isArray(series?.characterArcs) ? series.characterArcs : [],+ voice: {+ styleNotes: series?.styleNotes || '',+ styleGuide: series?.styleGuide || null,+ },+ };+}++export const contentHash = (value) => createHash('sha256').update(JSON.stringify(value ?? null)).digest('hex');+export const foundationInputsHash = (series, universe, issues = []) => contentHash(foundationInputs(series, universe, issues));++// ---------- context assembly ----------++// Render one character's framework completeness so the judge can see which of+// the Wound/Lie/Want/Need chain is present vs. blank (the character dimension's+// core signal) without dumping the whole record.+export function renderCharacterLine(c, { core = false } = {}) {+ const role = c?.role ? ` (${c.role})` : '';+ const concise = (value, maxChars = 100) => {+ if (typeof value !== 'string' || !value.trim()) return '—';+ const compact = value.trim().replace(/\s+/g, ' ');+ return compact.length <= maxChars ? compact : `${compact.slice(0, maxChars - 1).trimEnd()}…`;+ };+ const framework = FRAMEWORK_STRING_FIELDS+ .map((field) => `${field}: ${concise(c?.[field])}`)+ .join(' | ');+ const profile = PROFILE_STRING_FIELDS+ .map((field) => `${field}: ${concise(c?.[field])}`)+ .join(' | ');+ const secrets = (Array.isArray(c?.secrets) ? c.secrets : [])+ .map(concise)+ .slice(0, 3)+ .join('; ');+ // The harsh judge needs the actual render identity, not a presence marker.+ // `ready` proved actively misleading: five complete character sheets were+ // scored as absent because the prompt hid every distinguishing detail. Keep+ // the lines bounded, but show enough anatomy, silhouette, palette, and visual+ // grammar to compare the cast and identify generic or contradictory designs.+ const visualString = (field) => (isBlankString(c?.[field]) ? 'BLANK' : concise(c[field], 320));+ const visualList = (field) => {+ if (isBlankArray(c?.[field])) return 'BLANK';+ const compact = JSON.stringify(c[field]).replace(/\s+/g, ' ');+ return compact.length <= 420 ? compact : `${compact.slice(0, 419).trimEnd()}…`;+ };+ const visual = [+ ...VISUAL_FOUNDATION_STRING_FIELDS.map((field) => `${field}: ${visualString(field)}`),+ ...VISUAL_FOUNDATION_LIST_FIELDS.map((field) => `${field}: ${visualList(field)}`),+ ].join(' | ');+ return `- ${core ? '[CORE] ' : ''}**${c?.name || 'Unnamed'}**${role} — dramatic framework: ${framework} | profile: ${profile} | arcType: ${c?.arcType || '—'} | secrets: ${secrets || '—'} | visual foundation: ${visual}`;+}++const joinedLength = (lines) => lines.reduce((total, line) => total + line.length + 1, 0);++const pluralLines = (count) => (count === 1 ? 'line' : 'lines');++// Last-resort clamp for `renderArc`. Every tier above it drops WHOLE lines so the+// render stays coherent, but a budget smaller than the arc header itself (or a+// series with more volume loglines than the budget has room for) can still+// overrun — and `maxChars` is a hard contract, not a target. Slice, and keep the+// marker only when there is room for it.+const ARC_TRUNCATION_NOTE = '\n[series plan truncated to fit the prompt budget]';+function clampArcToBudget(text, maxChars) {+ if (!Number.isFinite(maxChars) || text.length <= maxChars) return text;+ if (maxChars <= ARC_TRUNCATION_NOTE.length) return text.slice(0, Math.max(0, maxChars));+ return `${text.slice(0, maxChars - ARC_TRUNCATION_NOTE.length)}${ARC_TRUNCATION_NOTE}`;+}++/**+ * Render the synopsis-level series plan: arc header, per-volume loglines and+ * synopses, the episode list under each volume, and the authored character arcs.+ *+ * `maxChars` is a HARD bound on the result, spent in tiers so the render always+ * degrades to something coherent rather than being sliced mid-sentence:+ *+ * 1. Drop WHOLE episode synopsis lines from the end. Earliest episodes survive+ * a tight budget because that's where a character arc's opening transitions+ * hang.+ * 2. If the spine alone (arc header + every volume's logline/synopsis/hook ++ * the authored character arcs) still overruns, drop the per-volume synopsis+ * and ending-hook lines, keeping `V# title: logline` so the volume order and+ * shape survive. Every episode goes with them.+ * 3. Slice, as a floor, when even the loglines cannot fit — a caller that set a+ * budget gets a smaller string, never a longer one.+ *+ * Each tier names what it left out, so the model can tell a short plan from a+ * budgeted one.+ *+ * Unbudgeted (the default) the output is byte-identical to the pre-budget+ * render, so the foundation judge's own section-level truncation is unchanged.+ */+export function renderArc(series, issues = [], { maxChars = Infinity, includeArcTransitions = false } = {}) {+ const arc = series?.arc || {};+ const seasons = Array.isArray(series?.seasons) ? [...series.seasons].sort((a, b) => (a.number || 0) - (b.number || 0)) : [];+ const orderedIssues = [...(Array.isArray(issues) ? issues : [])]+ .sort((a, b) => (a?.number ?? 9999) - (b?.number ?? 9999));+ const themes = Array.isArray(arc.themes) ? arc.themes.join(', ') : (arc.themes || '');+ const head = [+ `Logline: ${arc.logline || '(none)'}`,+ `Summary: ${arc.summary || '(none)'}`,+ `Themes: ${themes || '(none)'}`,+ `Protagonist arc: ${arc.protagonistArc || '(none)'}`,+ `Shape: ${arc.shape || '(unset)'}`,+ '',+ `Volumes (${seasons.length}):`,+ ];+ const volumes = seasons.map((season) => {+ const logline = ` V${season.number ?? '?'} ${season.title || ''}: ${season.logline || '(no logline)'}`;+ const detail = [` Synopsis: ${season.synopsis || '(none)'}`];+ if (season.endingHook) detail.push(` Ending hook: ${season.endingHook}`);+ const episodes = orderedIssues+ .filter((issue) => issue?.seasonId === season.id)+ .map((issue) => {+ const synopsis = issue?.stages?.idea?.input || '(no synopsis)';+ const words = synopsis === '(no synopsis)' ? 0 : synopsis.trim().split(/\s+/).filter(Boolean).length;+ const metadata = [+ issue.arcRole ? `role=${issue.arcRole}` : 'role=unset',+ issue.lengthProfile ? `length=${issue.lengthProfile}` : 'length=unset',+ `${words} synopsis words`,+ ].join(', ');+ return ` #${issue.number ?? '?'} ${issue.title || 'Untitled'} [${metadata}]: ${synopsis}`;+ });+ return { logline, detail, episodes };+ });+ const characterArcs = Array.isArray(series?.characterArcs) ? series.characterArcs : [];+ const tail = ['', `Authored character arcs (${characterArcs.length}):`];+ if (includeArcTransitions) {+ tail.push(renderCharacterArcsForPrompt(characterArcs) || '(none)');+ } else {+ for (const characterArc of characterArcs) {+ tail.push(` - ${characterArc.characterName || characterArc.characterId || 'Unnamed'}: ${characterArc.startState || '(no start)'} → ${characterArc.endState || '(no end)'}; want=${characterArc.want || '—'}; need=${characterArc.need || '—'}`);+ }+ }++ // Tier 1: the full spine is unconditional; episodes fill whatever is left.+ const fullSpine = [...head, ...volumes.flatMap((volume) => [volume.logline, ...volume.detail]), ...tail];+ let remaining = maxChars - joinedLength(fullSpine);+ const notes = [];+ // Tier 2: the spine alone overruns, so the per-volume synopsis/hook lines go+ // and every episode goes with them — dropping craft detail to make room for+ // episode lines would invert the priority the tiers exist to express.+ const withDetail = remaining >= 0;+ if (!withDetail) {+ const droppedDetail = volumes.reduce((total, volume) => total + volume.detail.length, 0);+ if (droppedDetail > 0) {+ notes.push(` [${droppedDetail} volume synopsis ${pluralLines(droppedDetail)} omitted to fit the prompt budget]`);+ }+ remaining = -1;+ }+ let omitted = 0;+ const lines = [...head];+ for (const volume of volumes) {+ lines.push(volume.logline);+ if (withDetail) lines.push(...volume.detail);+ for (const episode of volume.episodes) {+ if (episode.length + 1 <= remaining) {+ lines.push(episode);+ remaining -= episode.length + 1;+ } else {+ omitted += 1;+ }+ }+ }+ if (omitted > 0) lines.push(` [${omitted} later episode synopsis ${pluralLines(omitted)} omitted to fit the prompt budget]`);+ lines.push(...notes, ...tail);+ return clampArcToBudget(lines.join('\n'), maxChars);+}++// Below this the named-canon line carries no usable signal — render the+// omission marker instead of a handful of dangling entity names.+const NAMED_CANON_MIN_CHARS = 200;++/**+ * Render the world as the worldbuilding dimension is scored on it, bounded by+ * `maxChars`.+ *+ * The budget is spent by dropping the NAMED-CANON inventory, never the narrative+ * spine. Causal rules, costs, hard limits, and failure modes live in the premise+ * and style notes; the entity list is the noun inventory whose over-supply the+ * judge already penalizes, and it is the part that grows without bound. Slicing+ * the joined block instead (what this did before) cut the TAIL of the premise —+ * exactly where a freshly authored ruleset lands — so a world repair the judge+ * had just demanded became invisible to the next judge, the score never moved,+ * and the foundation gate burned its rounds against a repair it could not see.+ */+export function renderWorldFoundation(universe, { maxChars = Infinity } = {}) {+ if (!universe) return '(no linked universe — worldbuilding cannot be judged from canon)';+ const influences = universe.influences && typeof universe.influences === 'object'+ ? `Embrace: ${(universe.influences.embrace || []).join(', ') || '—'}; Avoid: ${(universe.influences.avoid || []).join(', ') || '—'}`+ : '(none)';+ const spine = [+ `Protected author intent (starter idea): ${universe.starterPrompt || '(none)'}`,+ `Universe logline: ${universe.logline || '(none)'}`,+ `Universe premise: ${universe.premise || '(none)'}`,+ `Universe style: ${universe.styleNotes || '(none)'}`,+ `Influences: ${influences}`,+ ].join('\n');+ const entities = renderEntitiesSummary(universe, { maxPerKind: { characters: 0 } }) || '(no named places or objects)';+ const canonLine = `Named canon: ${entities}`;+ const remaining = maxChars - spine.length - 1;+ if (canonLine.length <= remaining) return `${spine}\n${canonLine}`;+ if (remaining >= NAMED_CANON_MIN_CHARS) return `${spine}\n${canonLine.slice(0, remaining - 1).trimEnd()}…`;+ if (spine.length <= maxChars) return `${spine}\nNamed canon: [omitted to fit the judging budget]`;+ // The spine alone overruns: the premise is larger than this judge model's+ // world budget. Slicing is unavoidable here, but say so rather than letting+ // the judge score a silently amputated world.+ return `${spine.slice(0, maxChars)}\n\n[world summary truncated for judging]`;+}++// Build the judge's variable bag from the whole foundation. Content is budgeted+// to the judge model's window (a small/local judge trims to fit rather than+// overflowing; a big-context judge gets the whole foundation).+export function buildFoundationContext({ series, universe, canon, issues = [], contentMax }) {+ const characters = Array.isArray(canon?.characters) ? canon.characters : [];+ const seriesCharacters = seriesFoundationCharacters(characters, series, issues);+ const characterRoster = seriesCharacters.length+ ? seriesCharacters.map((character) => renderCharacterLine(character, { core: true })).join('\n')+ : '(no canon characters)';+ const sectionMax = Math.max(1_000, Math.floor(contentMax / 3));+ const world = renderWorldFoundation(universe, { maxChars: sectionMax });+ // Character quality lives in the choices between start and end, not merely+ // the endpoints. Reuse the canonical authored-arc renderer here so the judge+ // sees decisions, relapses, sacrifices, and their issue placement. The+ // repair prompt keeps the legacy compact summary because it already receives+ // the full `series.characterArcs` JSON separately.+ const arcText = renderArc(series, issues, { includeArcTransitions: true });+ const roster = characterRoster.length > sectionMax+ ? `${characterRoster.slice(0, sectionMax)}\n\n[character roster truncated for judging]`+ : characterRoster;+ const arcContext = arcText.length > sectionMax+ ? `${arcText.slice(0, sectionMax)}\n\n[series plan truncated for judging]`+ : arcText;+ return {+ series: {+ name: series?.name || 'Untitled series',+ logline: series?.logline || '',+ premise: series?.premise || '',+ styleNotes: composeStyleNotes(series, { proseCraft: true }),+ },+ worldEntitiesSummary: world,+ characterRoster: roster,+ characterCount: seriesCharacters.length,+ arc: arcContext,+ };+}diff --git a/server/services/pipeline/issueCrud.js b/server/services/pipeline/issueCrud.jsindex b8fb2c2889..750131bfee 100644--- a/server/services/pipeline/issueCrud.js+++ b/server/services/pipeline/issueCrud.js@@ -10,6 +10,7 @@*/import { randomUUID } from 'crypto';+import { pickRenderedFilename } from '../../lib/renderSlot.js';import { isStr, trimTo } from '../../lib/storyBible.js';import { UNSCOPED_ANCHOR } from '../../lib/pipelineIssueOrder.js';import { emitRecordUpdated } from '../sharing/recordEvents.js';@@ -423,6 +424,19 @@ function mergeIssuePatch(cur, patch = {}) {return merged;}+const frontCoverFilename = (issue) => pickRenderedFilename(issue?.stages?.comicPages?.cover);++async function returnIssueAfterCoverRefresh({ issue, frontCoverChanged }) {+ if (frontCoverChanged) {+ // General issue PATCHes can clear or replace comicPages.cover without+ // passing through the stage helpers. Refresh after the serialized write so+ // series.coverImage always derives from the freshly persisted issue set.+ const { refreshSeriesCoverImage } = await import('./seriesCoverImage.js');+ await refreshSeriesCoverImage(issue.seriesId).catch(() => {});+ }+ return issue;+}+export function updateIssue(id, patch = {}, { skipRenumber = false } = {}) {const needsRenumber = !skipRenumber && ('seasonId' in patch || 'arcPosition' in patch);if (!needsRenumber) {@@ -438,9 +452,12 @@ export function updateIssue(id, patch = {}, { skipRenumber = false } = {}) {const merged = mergeIssuePatch(cur, patch);await saveIssueNow(merged);emitRecordUpdated('series', merged.seriesId);- return merged;+ return {+ issue: merged,+ frontCoverChanged: frontCoverFilename(cur) !== frontCoverFilename(merged),+ };}),- );+ ).then(returnIssueAfterCoverRefresh);}return getIssue(id, { includeDeleted: true }).then((existing) =>@@ -463,9 +480,12 @@ export function updateIssue(id, patch = {}, { skipRenumber = false } = {}) {// Issues are exported as part of their parent series — re-export the// series so any active subscription picks up the issue change.emitRecordUpdated('series', merged.seriesId);- return merged;+ return {+ issue: merged,+ frontCoverChanged: frontCoverFilename(cur) !== frontCoverFilename(merged),+ };})- );+ ).then(returnIssueAfterCoverRefresh);}export function deleteIssue(id) {diff --git a/server/services/pipeline/issueStages.js b/server/services/pipeline/issueStages.jsindex 82413aa5be..93becb1737 100644--- a/server/services/pipeline/issueStages.js+++ b/server/services/pipeline/issueStages.js@@ -10,6 +10,7 @@import { isPlainObject } from '../../lib/objects.js';import { isStr } from '../../lib/storyBible.js';+import { pickRenderedFilename } from '../../lib/renderSlot.js';import { emitRecordUpdated } from '../sharing/recordEvents.js';import { getIssue } from './issueCrud.js';import {@@ -66,6 +67,7 @@ export function updateStagesWithLatest(seriesId, updates = [], { snapshotPrior =const state = await readState();const results = [];let changed = false;+ let frontCoverChanged = false;// Index once: `state.issues` is the INSTALL-wide list, and a bulk caller can// pass one update per (issue, stage) — a per-update findIndex would make the// write O(updates × issues in the install). Rebuilt in step with the@@ -83,6 +85,10 @@ export function updateStagesWithLatest(seriesId, updates = [], { snapshotPrior =continue;}const nextStage = mergeStagePatch(currentStage, update.stageId, patch, { snapshotPrior });+ if (update.stageId === 'comicPages'+ && pickRenderedFilename(currentStage?.cover) !== pickRenderedFilename(nextStage?.cover)) {+ frontCoverChanged = true;+ }const mergedIssue = sanitizeIssue({...cur,stages: { ...cur.stages, [update.stageId]: nextStage },@@ -97,6 +103,15 @@ export function updateStagesWithLatest(seriesId, updates = [], { snapshotPrior =await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));emitRecordUpdated('series', seriesId);}+ return { results, frontCoverChanged };+ }).then(async ({ results, frontCoverChanged }) => {+ if (frontCoverChanged) {+ // A manual clear/replacement does not pass through the media filename+ // hook, so it previously left series.coverImage pointing at stale art.+ // Recompute after the serialized issue write and outside its queue.+ const { refreshSeriesCoverImage } = await import('./seriesCoverImage.js');+ await refreshSeriesCoverImage(seriesId).catch(() => {});+ }return results;});}@@ -168,12 +183,17 @@ export function updateStageWithLatest(issueId, stageId, computeFn, { snapshotPri// page). Skip the disk write + emitRecordUpdated so it doesn't trigger// a re-export storm in share subscriptions for late no-op events.if (isPlainObject(patch) && Object.keys(patch).length === 0) {- return { issue: cur, stage: currentStage };+ return {+ result: { issue: cur, stage: currentStage },+ frontCoverChanged: false,+ };}// Snapshot the prior `{ runId, input, output }` into runHistory when this// patch carries a fresh lastRunId (i.e. a generate just replaced prior// content). Computed BEFORE the spread so it reads pre-merge state.const next = mergeStagePatch(currentStage, stageId, patch, { snapshotPrior });+ const frontCoverChanged = stageId === 'comicPages'+ && pickRenderedFilename(currentStage?.cover) !== pickRenderedFilename(next?.cover);const mergedIssue = sanitizeIssue({...cur,stages: { ...cur.stages, [stageId]: next },@@ -181,9 +201,18 @@ export function updateStageWithLatest(issueId, stageId, computeFn, { snapshotPri});await saveIssueNow(mergedIssue);emitRecordUpdated('series', mergedIssue.seriesId);- return { issue: mergedIssue, stage: mergedIssue.stages[stageId] };+ return {+ result: { issue: mergedIssue, stage: mergedIssue.stages[stageId] },+ frontCoverChanged,+ };};return getIssue(issueId, { includeDeleted: true }).then((existing) =>- queueSeriesIssuesWrite(existing.seriesId, work),+ queueSeriesIssuesWrite(existing.seriesId, work).then(async ({ result, frontCoverChanged }) => {+ if (frontCoverChanged) {+ const { refreshSeriesCoverImage } = await import('./seriesCoverImage.js');+ await refreshSeriesCoverImage(result.issue.seriesId).catch(() => {});+ }+ return result;+ }),);}diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.jsindex bc8a66a44b..b7c2335e73 100644--- a/server/services/pipeline/issues.test.js+++ b/server/services/pipeline/issues.test.js@@ -6,6 +6,7 @@ const fileStore = new Map();// first atomicWrite whose (path, data) matches is held for `ms` before landing,// letting a test force a specific read→write interleaving deterministically.let pendingWriteDelay = null;+const coverRefresh = vi.hoisted(() => ({ refreshSeriesCoverImage: vi.fn(async () => {}) }));vi.mock('../../lib/fileUtils.js', () => ({tryReadFile: vi.fn().mockResolvedValue(null),@@ -30,6 +31,7 @@ vi.mock('crypto', async () => {vi.mock('../instances.js', () => mockNoPeers());vi.mock('../sharing/peerSync.js', () => mockNoPeerSync());+vi.mock('./seriesCoverImage.js', () => coverRefresh);const svc = await import('./issues.js');const seriesSvc = await import('./series.js');@@ -42,6 +44,7 @@ describe('pipeline issues service', () => {fileStore.clear();uuidCounter = 0;pendingWriteDelay = null;+ coverRefresh.refreshSeriesCoverImage.mockClear();});it('createIssue assigns iss- id and auto-numbers within a series', async () => {@@ -246,6 +249,83 @@ describe('pipeline issues service', () => {expect(stage.pages[0].panels[0].imageJobId).toBe('j1');});+ it('refreshes the series thumbnail when a rendered issue cover is cleared', async () => {+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'First' });+ await svc.updateStage(i.id, 'comicPages', {+ status: 'ready',+ cover: { finalImage: { filename: 'old-cover.png', fromProof: false } },+ });+ coverRefresh.refreshSeriesCoverImage.mockClear();++ await svc.updateStage(i.id, 'comicPages', { status: 'empty', cover: null });++ expect(coverRefresh.refreshSeriesCoverImage).toHaveBeenCalledOnce();+ expect(coverRefresh.refreshSeriesCoverImage).toHaveBeenCalledWith('ser-1');+ });++ it('refreshes once when a batch replaces a rendered issue cover', async () => {+ const issue = await svc.createIssue({ seriesId: 'ser-1', title: 'First' });+ await svc.updateStage(issue.id, 'comicPages', {+ status: 'ready',+ cover: { finalImage: { filename: 'old-cover.png', fromProof: false } },+ });+ coverRefresh.refreshSeriesCoverImage.mockClear();++ await svc.updateStagesWithLatest('ser-1', [+ {+ issueId: issue.id,+ stageId: 'comicPages',+ computeFn: (stage) => ({+ cover: {+ ...stage.cover,+ finalImage: { filename: 'new-cover.png', fromProof: false },+ },+ }),+ },+ ]);++ expect(coverRefresh.refreshSeriesCoverImage).toHaveBeenCalledOnce();+ expect(coverRefresh.refreshSeriesCoverImage).toHaveBeenCalledWith('ser-1');+ });++ it('refreshes once when a batch clears a rendered issue cover', async () => {+ const issue = await svc.createIssue({ seriesId: 'ser-1', title: 'First' });+ await svc.updateStage(issue.id, 'comicPages', {+ status: 'ready',+ cover: { finalImage: { filename: 'old-cover.png', fromProof: false } },+ });+ coverRefresh.refreshSeriesCoverImage.mockClear();++ await svc.updateStagesWithLatest('ser-1', [{+ issueId: issue.id,+ stageId: 'comicPages',+ computeFn: () => ({ cover: null }),+ }]);++ expect(coverRefresh.refreshSeriesCoverImage).toHaveBeenCalledOnce();+ expect(coverRefresh.refreshSeriesCoverImage).toHaveBeenCalledWith('ser-1');+ });++ it('does not refresh after a batch patch that preserves the rendered cover filename', async () => {+ const issue = await svc.createIssue({ seriesId: 'ser-1', title: 'First' });+ await svc.updateStage(issue.id, 'comicPages', {+ status: 'ready',+ cover: {+ script: 'old concept',+ finalImage: { filename: 'same-cover.png', fromProof: false },+ },+ });+ coverRefresh.refreshSeriesCoverImage.mockClear();++ await svc.updateStagesWithLatest('ser-1', [{+ issueId: issue.id,+ stageId: 'comicPages',+ computeFn: (stage) => ({ cover: { ...stage.cover, script: 'new concept' } }),+ }]);++ expect(coverRefresh.refreshSeriesCoverImage).not.toHaveBeenCalled();+ });+describe('runHistory snapshots', () => {const seedFirstRun = async () => {const i = await svc.createIssue({ seriesId: 'ser-1', title: 'Pilot' });@@ -669,12 +749,41 @@ describe('pipeline issues service', () => {const i = await svc.createIssue({ seriesId: 'ser-1', title: 'Clear cover' });await svc.updateStage(i.id, 'comicPages', {status: 'edited',- cover: { script: 'concept', imageJobId: null, prompt: null },+ cover: {+ script: 'concept',+ imageJobId: null,+ prompt: null,+ finalImage: { filename: 'rendered-cover.png', fromProof: false },+ },});+ coverRefresh.refreshSeriesCoverImage.mockClear();const updated = await svc.updateIssue(i.id, {stages: { comicPages: { cover: null } },});expect(updated.stages.comicPages.cover).toBeNull();+ expect(coverRefresh.refreshSeriesCoverImage).toHaveBeenCalledOnce();+ expect(coverRefresh.refreshSeriesCoverImage).toHaveBeenCalledWith('ser-1');+ });++ it('refreshes after a rendered cover replacement in the renumbering update path', async () => {+ const i = await svc.createIssue({ seriesId: 'ser-1', title: 'Move and replace' });+ await svc.updateStage(i.id, 'comicPages', {+ status: 'edited',+ cover: { finalImage: { filename: 'before.png', fromProof: false } },+ });+ coverRefresh.refreshSeriesCoverImage.mockClear();++ await svc.updateIssue(i.id, {+ arcPosition: 2,+ stages: {+ comicPages: {+ cover: { finalImage: { filename: 'after.png', fromProof: false } },+ },+ },+ });++ expect(coverRefresh.refreshSeriesCoverImage).toHaveBeenCalledOnce();+ expect(coverRefresh.refreshSeriesCoverImage).toHaveBeenCalledWith('ser-1');});it('clears errorMessage when a stage patch transitions out of error state', async () => {diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex 98f893af62..40e03974f4 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -4238,7 +4238,7 @@ describe('autopilot conductor', () => {const { seriesId } = await seedComplete();await autopilot.startSeriesAutopilot(seriesId, { includeVisual: true });await waitFor(runFinished(seriesId));- expect(checkSeriesCanonReadiness).toHaveBeenCalled();+ expect(checkSeriesCanonReadiness).toHaveBeenCalledWith(seriesId, { sourceStages: ['comicScript'] });expect(visualSpies.enqueueComicCover).toHaveBeenCalled();expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');});diff --git a/server/services/pipeline/seriesAutopilot/visualSteps.js b/server/services/pipeline/seriesAutopilot/visualSteps.jsindex ed1b8cd27a..63db0be266 100644--- a/server/services/pipeline/seriesAutopilot/visualSteps.js+++ b/server/services/pipeline/seriesAutopilot/visualSteps.js@@ -175,7 +175,11 @@ export async function runVisualDraft(sId, issueId, record) {// has no description (it can't be drawn). Marks canonVerified when clean so the// run proceeds to visual drafting.export async function runCanonVerify(sId, record) {- let report = await checkSeriesCanonReadiness(sId);+ // This gate only precedes comic-page rendering. A hybrid run may be scoped to+ // comics and intentionally omit teleplays, so judge the source this step will+ // actually render; the general series review still requires both formats.+ const readinessOptions = { sourceStages: ['comicScript'] };+ let report = await checkSeriesCanonReadiness(sId, readinessOptions);if (!report.ready) {const series = await getSeries(sId);const providerOpts = providerOverrideOpts(record);@@ -232,7 +236,7 @@ export async function runCanonVerify(sId, record) {}// Re-read after every issue-local repair. Shared canon means one fill can// clear the same noun across many later issues without another LLM call.- report = await checkSeriesCanonReadiness(sId);+ report = await checkSeriesCanonReadiness(sId, readinessOptions);}broadcast(sId, {type: 'verify:round', scope: 'canon', round: 1,