Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-1315]): storyboard shot grammar + deterministic visual-continuity editorial check
Adam Eivy87c5560046de
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 787d916b0f..dd0b667d4a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## Added+- **[issue-1315] Storyboard shots now record camera framing + screen direction, and a new editorial check catches film-grammar continuity errors before render.** Each storyboard shot gains two film-grammar fields — **shot type** (extreme-wide / wide / medium / close / extreme-close / over-the-shoulder / two-shot / POV) and **screen direction** (the side the subject faces or moves: left / right / neutral) — captured by the scene extractor (the teleplay→scenes prompt now asks the model to tag them) and carried on the shot record. A new deterministic **Storyboard shot continuity** check (Create → Editorial Checks) reads those fields and flags two classic film-grammar mistakes *before* you spend render time on a clip: a **180-degree-rule axis reversal** — a shot that continues from an earlier one but flips the subject to the opposite side of the screen, so they appear to jump sides across the cut — and **shot-type monotony**, a scene whose shots all share one framing and read as flat, slideshow coverage with no establishing wide or punch-in. Findings render as `Continuity` notes anchored to the offending issue + scene, and (being deterministic) need no LLM. Both fields are backward-compatible and default to "not captured," so older storyboards simply aren't flagged until re-extracted; the extraction-prompt change migrates for existing installs (114). Eyeline-match and appearance/prop continuity (which need a vision/LLM pass) and a hard pre-render render-gate are tracked as follow-ups. (`server/lib/shotGrammar.js`, `server/lib/sceneExtractor.js`, `server/lib/editorial/shotContinuity.js`, `server/lib/editorial/checkRegistry.js`, `server/services/pipeline/editorial/checkRunner.js`, `scripts/migrations/114-extract-scenes-shot-grammar.js`, #1315)- **[issue-1310] Editorial check flags plot-structure & momentum problems — passive protagonist, deus ex machina, idiot plot, flat stakes, sagging middle, dropped subplots.** A new **Plot structure & momentum** check (Create → Editorial Checks) reads your drafted manuscript and surfaces the macro pathologies a developmental editor flags at the arc level: a **passive protagonist** (events happen *to* them instead of being driven by their choices), a **deus ex machina / convenient coincidence** that resolves a problem by luck rather than setup, an **idiot plot** that only holds together because someone won't say the obvious, **flat or unclear stakes** that never escalate, a **sagging middle** with no try-fail rhythm, and **dropped subplots** — threads that open and then fizzle. It reconciles dropped threads against your reverse-outline plotline tags and your authored reader-map hooks/payoffs, and defers whole-arc judgments (a sagging middle, a never-resolved thread) until it has seen the whole manuscript so a long book reviewed in chunks isn't false-flagged. Findings render as `Plot structure` notes in the manuscript editor, anchored to the issue and (where one exists) a verbatim quote. Ships a new stage prompt (`pipeline-editorial-plot-structure`) that migrates for existing installs (111). (#1310)- **[issue-1311] Editorial check flags head-hopping / POV-discipline breaks within a scene.** A new **Head-hopping / POV discipline** LLM check (Create → Editorial Checks) polices viewpoint discipline in limited-POV prose — distinct from the existing **POV justification** check (#1295, which asks whether each viewpoint *character* earns an arc). For each limited-POV scene it flags narration that enters another character's head (reports interior thoughts/feelings the POV character can't know), reports knowledge or perception the POV character couldn't have (offstage events, things behind them), or switches POV mid-scene with no break — and suggests re-anchoring to the POV character's perception or inserting a proper scene break. It reads your reverse-outline scene segmentation as context (each scene's anchored POV character + the other characters on-stage, the candidate heads a hop slips into) and **degrades gracefully** to a whole-issue manuscript scan when no outline exists yet. It **no-ops when the series style guide sets third-person omniscient** — there the roaming viewpoint is intentional — and surfaces the configured POV person (first / third-limited / second) to the model so it judges against the discipline actually in force. Each finding anchors a verbatim quote + issue number and names whose head was entered. Ships a new stage prompt (`pipeline-editorial-head-hopping`) that migrates for existing installs (112). (`server/lib/editorial/checkRegistry.js`, `scripts/migrations/112-editorial-head-hopping-stage.js`, #1311)diff --git a/data.reference/prompts/stages/pipeline-extract-scenes.md b/data.reference/prompts/stages/pipeline-extract-scenes.mdindex 0a5c4331b0..ef12b2687e 100644--- a/data.reference/prompts/stages/pipeline-extract-scenes.md+++ b/data.reference/prompts/stages/pipeline-extract-scenes.md@@ -42,6 +42,8 @@ Within each scene, produce **3–8 shots** — distinct camera setups that cover- **`description`** — one camera setup (~20–50 words): subject + framing + motion + mood. Be specific about lens choice cues if implied (wide / medium / close, low angle, handheld, slow push-in). Do not name characters — describe them physically.- **`durationSeconds`** — integer 2–10. Default 4 for standard coverage, 2–3 for reaction inserts, 6–10 for held establishing or emotionally weighted shots. The shot durations across a scene should roughly match the dramatic time the scene occupies on the page.- **`continuityFromShotId`** — id of an earlier shot in the SAME scene whose final frame should bridge into this shot's first frame (visual continuity for i2v video chaining). Use `null` for the first shot of a scene, or any shot that intentionally breaks continuity (new angle from scratch, hard cut, time jump within scene). When a shot is a natural progression — a push-in on the same subject, a reaction shot of the same set, a continuation of motion — reference the prior shot's id. This is what makes the rendered video feel like a scene instead of a slideshow.+ - **`shotType`** — the camera framing, one of: `extreme-wide`, `wide`, `medium`, `close`, `extreme-close`, `over-the-shoulder`, `two-shot`, `pov`. Pick the size that matches the shot's dramatic job (a master/establishing beat is `wide`; a reaction or emotional beat is `close`; an exchange between two characters is `over-the-shoulder` or `two-shot`). Use `null` only if the framing is genuinely ambiguous.+ - **`screenDirection`** — the dominant on-screen direction the shot's subject faces or moves, from the viewer's perspective: `left`, `right`, or `neutral` (head-on, or no clear left/right). This is what lets the pipeline catch 180-degree-rule violations: within a continuous run of shots, keep a character on a consistent side of the action axis — if they faced screen-`left` in one shot they should not suddenly face screen-`right` in a shot that continues from it. Use `neutral` for head-on framing or when there is no meaningful axis.- **`sourceSegmentIds`** — keep empty.## Output contract@@ -69,7 +71,9 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c"id": "shot-01","description": "string","durationSeconds": 4,- "continuityFromShotId": null+ "continuityFromShotId": null,+ "shotType": "wide",+ "screenDirection": "neutral"}],"sourceSegmentIds": []diff --git a/scripts/migrations/006-extract-scenes-shots.js b/scripts/migrations/006-extract-scenes-shots.jsindex 37089ea6ab..f65c276ca9 100644--- a/scripts/migrations/006-extract-scenes-shots.js+++ b/scripts/migrations/006-extract-scenes-shots.js@@ -10,11 +10,18 @@import { makePromptReplaceMigration } from './_lib.js';export const ACCEPTED_OLD_MD5 = {- 'pipeline-extract-scenes.md': ['59fa5ee305ce53d91eb15224d8b546d3'],+ 'pipeline-extract-scenes.md': [+ '59fa5ee305ce53d91eb15224d8b546d3', // pre-006 (original, no shots[])+ 'c51fb208568d0d903eb43b437478b0ba', // post-006 / pre-114 — the hash this migration originally produced+ ],};+// Tracks the LATEST shipped body. Bumped to the post-114 hash (shot-grammar+// fields) so this migration still upgrades a post-006/pre-114 install straight+// to current rather than classifying it "customized". The intermediate hash+// moved to ACCEPTED_OLD_MD5 above. See migration 114.export const NEW_SHIPPED_MD5 = {- 'pipeline-extract-scenes.md': 'c51fb208568d0d903eb43b437478b0ba',+ 'pipeline-extract-scenes.md': '9f404b0c4721b23932a6d2dcfc1fba43', // post-114 (shotType + screenDirection)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/114-extract-scenes-shot-grammar.js b/scripts/migrations/114-extract-scenes-shot-grammar.jsnew file mode 100644index 0000000000..0067310eec--- /dev/null+++ b/scripts/migrations/114-extract-scenes-shot-grammar.js@@ -0,0 +1,54 @@+/**+ * Update the `pipeline-extract-scenes` stage prompt to emit shot-grammar fields+ * (#1315): each shot now carries `shotType` (camera framing) and `screenDirection`+ * (on-screen left/right/neutral), the two signals the deterministic+ * `visual.shot-continuity` editorial check reasons over (180°-rule axis reversals,+ * shot-type monotony).+ *+ * `scripts/setup-data.js` only COPIES missing prompt files — an existing install+ * already has `data/prompts/stages/pipeline-extract-scenes.md`, so it would keep+ * the old template (no `shotType`/`screenDirection` instruction) and the extractor+ * would never populate the new fields. This migration hash-replaces the installed+ * prompt with the new shipped version when it still matches the pre-change shipped+ * hash; a customized copy is left alone with a merge hint.+ *+ * Hash-driven prompt-replace via `./_lib.js` (newline-normalized MD5, so the+ * comparison is correct on Windows checkouts). Idempotent. Exporting+ * ACCEPTED_OLD_MD5 / NEW_SHIPPED_MD5 keeps the drift table in setup-data.js in+ * sync automatically (buildPromptDriftTables reads them).+ *+ * No stage-config change: `pipeline-extract-scenes` is already a shipped stage,+ * so only its prompt body moved.+ */++import { makePromptReplaceMigration } from './_lib.js';++export const ACCEPTED_OLD_MD5 = {+ 'pipeline-extract-scenes.md': [+ 'c51fb208568d0d903eb43b437478b0ba', // pre-114 (pre shot-grammar fields)+ ],+};++export const NEW_SHIPPED_MD5 = {+ 'pipeline-extract-scenes.md': '9f404b0c4721b23932a6d2dcfc1fba43', // post-114 (shotType + screenDirection)+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'pipeline scene-extract prompt',+ customizedHint: (filename) =>+ ` To add the shot-grammar fields manually, diff:\n` ++ ` data.reference/prompts/stages/${filename}\n` ++ ` against your current:\n` ++ ` data/prompts/stages/${filename}\n` ++ ` and add the shotType + screenDirection shot fields (the field spec + the output-contract example).`,+ skipFooter: (count) =>+ `⚠️ ${count} scene-extract prompt(s) could not be auto-updated because they were customized.\n` ++ ` Scene extraction still works, but extracted shots won't carry shotType / screenDirection\n` ++ ` (and the visual.shot-continuity editorial check has nothing to read) until you merge the\n` ++ ` new shot fields. See data.reference/prompts/stages/pipeline-extract-scenes.md.`,+});++export { applyMigration };+export default { up };diff --git a/scripts/migrations/114-extract-scenes-shot-grammar.test.js b/scripts/migrations/114-extract-scenes-shot-grammar.test.jsnew file mode 100644index 0000000000..236de4f47f--- /dev/null+++ b/scripts/migrations/114-extract-scenes-shot-grammar.test.js@@ -0,0 +1,21 @@+/**+ * Test for migration 114 — pipeline-extract-scenes.md gains per-shot+ * shotType + screenDirection (#1315).+ *+ * Picked up via the vitest include glob in server/vitest.config.js+ * (`../scripts/migrations/**\/*.test.js`).+ */+import { describe } from 'vitest';++import { runPromptMigrationTests } from './_testHelpers.js';+import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './114-extract-scenes-shot-grammar.js';++describe('migration 114 — extract-scenes shot grammar (shotType + screenDirection)', () => {+ runPromptMigrationTests({+ migration,+ applyMigration,+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ prefix: 'migration-114-',+ });+});diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.jsindex 78d402222b..75c5a53534 100644--- a/scripts/setup-data-drift.test.js+++ b/scripts/setup-data-drift.test.js@@ -33,7 +33,7 @@ const EXPECTED_STAGE_OLD = {'pipeline-arc-verify.md': ['52e31abc93e3105176236fcaa5d1575a', 'ff56d8387162017e08d5d0491060ddd6'],'pipeline-volume-verify.md': ['03f3c874cb80e1c98abcf03168fa7a92', 'c6ea28e972ad6e229bafb2d602b4dda3'],'pipeline-arc-resolve.md': ['87bc5c01f1a8a97b681727a38b05edc6', '8e348f3d1894382889f9f0ee7d5c6792', 'a8677bbe1eb38f871fb152a5b0fec7c6'],- 'pipeline-extract-scenes.md': ['59fa5ee305ce53d91eb15224d8b546d3'],+ 'pipeline-extract-scenes.md': ['59fa5ee305ce53d91eb15224d8b546d3', 'c51fb208568d0d903eb43b437478b0ba'],'writers-room-places.md': ['24a33628cc94d80fa5ca60831d973daf', '7f1f80eb63d67a21161994cde115045e'],'universe-character-expand.md': ['ef109eb8e12ddb664c11c790271b5139'],'story-builder-idea-expand.md': ['778c86e2caa120856c36e4d5a4da3355', 'a23939626a226f7420cebfb45d47950c'],@@ -53,7 +53,7 @@ const EXPECTED_STAGE_NEW = {'pipeline-arc-verify.md': '36aa70cdfc25d7549573a4d556e7702c','pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940','pipeline-arc-resolve.md': '5b340885c6e8f8afc63424d6b5bc7eb7',- 'pipeline-extract-scenes.md': 'c51fb208568d0d903eb43b437478b0ba',+ 'pipeline-extract-scenes.md': '9f404b0c4721b23932a6d2dcfc1fba43','writers-room-places.md': 'a7f68e51dd6b4421d20f5bd9d855d9b4','cos-agent-briefing.md': 'dccb392a43cbd3dac900fee12c31619a','universe-character-expand.md': '67b6e73ed47f318451a730088b4cff14',diff --git a/server/lib/README.md b/server/lib/README.mdindex 9612e43f0a..f1db758596 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -54,6 +54,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `canonPrompt.js` | Per-kind field-precedence rules; SHORT/RICH/PREVIEW spec tables; `flattenCanonDescriptorFragments` / `mapCanonDescriptorFragments` / `descriptorForCanonEntry`. || `scenePrompt.js` | Scene-prompt composer + bible matchers (chars/places/objects in text). || `sceneExtractor.js` | Split prose or teleplay into scene list via LLM. |+| `shotGrammar.js` | Pure shot-grammar vocabularies (`SHOT_TYPES`, `SCREEN_DIRECTIONS`) + normalizers (`normalizeShotType`, `normalizeScreenDirection`) for a storyboard shot's camera framing + on-screen direction. Shared by the scene extractor's sanitizer, the storyboards Zod schema, and the `visual.shot-continuity` editorial check (#1315). || `seasonStructure.js` | Season/episode structure recommendation. || `seriesCharacterArc.js` | Per-character story-arc shapes (`series.characterArcs[]`): want/need, start → end state, transition beats. Sanitizers + `renderCharacterArcsForPrompt` for the `arc.transitions` editorial check. || `seriesLlmOverride.js` | Pure `resolveSeriesLlmOverride(series, { overrideProvider, overrideModel })` → `{ provider, model, providerMatchesSeries }` — shared fallback so Pipeline LLM actions honor the series' configured provider/model, only inheriting the series model when the effective provider still matches. |diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.mdindex a18c11ee75..641d8317cc 100644--- a/server/lib/editorial/README.md+++ b/server/lib/editorial/README.md@@ -58,7 +58,7 @@ Declare every input the check's `run(ctx)` reads in its `sources` array (anon-empty subset of `EDITORIAL_SOURCES`: `manuscript`, `canon`,`series.styleGuide`, `series.arc.tickingClock`, `series.arc.readerMap`,`reverseOutline`, `reverseOutline.plotlines`, `editorialArcs`,-`series.characterArcs`). The staleness+`series.characterArcs`, `storyboard.shots`). The stalenessrunner fingerprints exactly those sources, so a finding goes stale only whencontent the check actually analyzed drifts — declare too few and a finding staysfalsely fresh; a `manuscript` source must pair with `needsManuscript: true`, and@@ -76,7 +76,11 @@ because not-yet-analyzed" under a partial coverage batch. `series.characterArcs`(#1293) reads the AUTHORED per-character arcs off the already-loaded seriesrecord (`series.characterArcs[]` — want/need, start → end state, transitionbeats), which the `arc.transitions` check reconciles detected change moments-against. When a new check reads a+against. `storyboard.shots` (#1315) is built off the already-loaded issues (no+extra I/O) and injects `ctx.storyboardScenes` (a flat `{ issueNumber, scene }`+list for every issue with storyboard scenes), which the deterministic+`visual.shot-continuity` check reads for 180°-rule axis reversals + shot-type+monotony. When a new check reads a`ctx.series` field (or another artifact) that isn't yet a token, add the token to`EDITORIAL_SOURCES` and a matching resolver in the runner's `SOURCE_RESOLVERS`.@@ -103,5 +107,6 @@ runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of| `italicThoughts.js` | Pure, dependency-free italic-thought primitive for `prose.italic-thoughts` (#1300): `findItalicThoughts` (multi-word markdown `*…*` / `_…_` italic runs, dedup + word-count threshold so single-word emphasis, bold, and `snake_case` are skipped). The LLM siblings (`opening.wrong-start`, `prose.mirror-description`, `dialogue.pleasantries`, `prose.kill-your-darlings`) handle the judgment cases in the #1300 anti-pattern bundle. || `proseTics.js` | Pure, dependency-free copy-edit prose-tic primitives for the #1306 line-edit group: `tokenizeWords` / `splitSentences` (shared tokenization), `findFilterWords` (`prose.filter-words`), `findCrutchWords` (`prose.crutch-words`), `findAdverbs` (`prose.adverbs` — `-ly` adverbs + dialogue-tag adverbs), `findPassiveVoice` (`prose.passive-voice` — be-verb + past-participle heuristic), `findGestures` (`prose.repeated-gestures` — gesture tally + body-part autonomy), plus the seed `FILTER_WORDS` / `CRUTCH_WORDS` / `GESTURE_WORDS` lists. The LLM sibling `prose.telling-emotion` handles the named-emotion judgment case. || `repetition.js` | Pure, dependency-free word-echo & rhythm primitives for #1306: `findWordEchoes` (`prose.word-echoes` — distinctive word repeated within a window), `findRepeatedOpeners` (runs of sentences sharing an opener, "He… He… He…"), and `measureSentenceRhythm` (`prose.sentence-rhythm` — sentence-length variation). Reuses `tokenizeWords` / `splitSentences` from `proseTics.js`. |+| `shotContinuity.js` | Pure, dependency-free storyboard shot-continuity primitives for the deterministic `visual.shot-continuity` check (#1315): `findAxisReversals` (180°-rule axis flips across a continuity-linked shot pair using `screenDirection`) and `findShotTypeMonotony` (a scene whose classified shots all share one `shotType`). Reads the shot-grammar fields from `server/lib/shotGrammar.js`. The judgment cases (eyeline match, appearance/prop continuity) are LLM-sibling follow-ups. || `dialogue.js` | Pure, dependency-free dialogue-tag primitives for the #1307 dialogue-craft group: `findSaidBookisms` (`dialogue.said-bookisms` — ornate speech tags like *expostulated*/*opined* and non-speech tags like "she smiled", matched only when adjacent to a double-quote span) and `findUnattributedDialogueRuns` (`dialogue.attribution-clarity` — runs of consecutive untagged/unbeated dialogue lines where the speaker can't be tracked), plus the seed `SAID_BOOKISMS` / `NON_SPEECH_TAGS` lists. The LLM siblings `dialogue.on-the-nose` (subtext-free / "as you know, Bob" dialogue) and `dialogue.voice-distinctiveness` (per-character voice against canon `speechPattern`/`speechAccent`) handle the judgment cases. || `index.js` | Barrel re-export of the above. |diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.jsindex 7fe547f60e..551a6bf094 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -43,6 +43,7 @@ import {findRepeatedOpeners,measureSentenceRhythm,} from './repetition.js';+import { findAxisReversals, findShotTypeMonotony } from './shotContinuity.js';export const CHECK_SCOPES = Object.freeze(['series', 'issue', 'scene', 'noun']);export const CHECK_KINDS = Object.freeze(['deterministic', 'llm']);@@ -86,6 +87,15 @@ const SEVERITIES = CHECK_SEVERITIES;// want, need, startState, endState, transitions[] }`). The// arc.transitions check reconciles detected change moments// against these authored transitions + flat-arc warnings.+// - 'storyboard.shots' — the per-issue storyboard shot lists+// (`stages.storyboards.scenes[].shots[]`) the+// visual-continuity check (#1315) reasons over:+// each shot carries `shotType` / `screenDirection`+// / `continuityFromShotId` (server/lib/shotGrammar.js).+// Served off the already-loaded `ctx.issues` (no+// extra I/O); the runner injects `ctx.storyboardScenes`+// (a flat list of `{ issueNumber, scene }` for every+// issue that has storyboard scenes).export const EDITORIAL_SOURCES = Object.freeze(['manuscript','canon',@@ -96,6 +106,7 @@ export const EDITORIAL_SOURCES = Object.freeze(['reverseOutline.plotlines','editorialArcs','series.characterArcs',+ 'storyboard.shots',]);// Default per-run finding cap for user-defined checks (#1346) — mirrors the@@ -1587,6 +1598,94 @@ export const EDITORIAL_CHECKS = [return findings;},},+ {+ id: 'visual.shot-continuity',+ sources: ['storyboard.shots'],+ label: 'Storyboard shot continuity (180° rule, shot-type variety)',+ description:+ 'Flags film-grammar errors in a storyboard scene\'s shot list BEFORE render — a 180-degree-rule axis reversal across a continuity-linked shot pair (the subject appears to flip sides across a cut declared continuous), and shot-type monotony (a scene whose shots all share one framing reads as flat, slideshow coverage). Reads the per-issue storyboard shots; deterministic, so it needs no LLM.',+ scope: 'scene',+ kind: 'deterministic',+ category: 'continuity',+ severityDefault: 'medium',+ defaultEnabled: true,+ configSchema: z.object({+ // Flag a 180° axis reversal across a continuity-linked shot pair.+ flagAxisReversal: z.boolean().default(true),+ // Flag a scene where every classified shot shares one framing. 0 disables+ // the monotony check; otherwise it's the minimum classified-shot count+ // before a single-framing scene is flagged (a sparse 2-shot tag is noise).+ minShotsForMonotony: z.number().int().min(0).max(16).default(3),+ }),+ configFields: [+ {+ key: 'flagAxisReversal',+ label: 'Flag 180° axis reversals',+ type: 'boolean',+ help: 'Flag a continuity-linked shot pair whose screen directions are opposite (left↔right) — the subject appears to jump sides across a cut the author declared continuous.',+ },+ {+ key: 'minShotsForMonotony',+ label: 'Min classified shots for monotony',+ type: 'number',+ min: 0,+ max: 16,+ step: 1,+ help: 'Flag a scene where every classified shot shares one framing (all medium, say) once at least this many shots are classified. 0 disables the monotony check.',+ },+ ],+ // Needs at least one storyboard scene with shots to read.+ gate: (ctx) => Array.isArray(ctx.storyboardScenes) && ctx.storyboardScenes.length > 0,+ run: (ctx) => {+ const cfg = ctx.config || {};+ const flagAxis = cfg.flagAxisReversal !== false;+ const minMonotony = cfg.minShotsForMonotony ?? 3;+ const entries = Array.isArray(ctx.storyboardScenes) ? ctx.storyboardScenes : [];+ const findings = [];+ const DIRECTION_LABEL = { left: 'screen-left', right: 'screen-right', neutral: 'head-on' };+ for (const entry of entries) {+ const scene = entry?.scene;+ if (!scene || typeof scene !== 'object') continue;+ const issueNumber = Number.isInteger(entry.issueNumber) ? entry.issueNumber : null;+ const sceneName = typeof scene.heading === 'string' && scene.heading.trim()+ ? scene.heading.trim()+ : (typeof scene.slugline === 'string' && scene.slugline.trim() ? scene.slugline.trim() : 'scene');+ const location = issueNumber != null ? `Issue ${issueNumber}: ${sceneName}` : `Scene: ${sceneName}`;++ if (flagAxis) {+ for (const r of findAxisReversals(scene)) {+ const fromLabel = DIRECTION_LABEL[r.fromDirection] || r.fromDirection;+ const toLabel = DIRECTION_LABEL[r.toDirection] || r.toDirection;+ findings.push({+ severity: ctx.severityDefault,+ category: 'continuity',+ location,+ problem: `Shot "${r.toId}" continues from "${r.fromId}" but faces ${toLabel} where "${r.fromId}" faced ${fromLabel} — a 180°-rule axis reversal makes the subject appear to jump sides across the cut.`,+ suggestion: `Keep both shots on the same side of the action axis (both ${fromLabel} or both ${toLabel}), insert a neutral/head-on cutaway between them, or break the continuity link if the angle change is intentional.`,+ anchorQuote: (r.toDescription || r.fromDescription || '').slice(0, 200),+ issueNumber,+ });+ }+ }++ if (minMonotony > 0) {+ const mono = findShotTypeMonotony(scene, { minClassified: minMonotony });+ if (mono) {+ findings.push({+ severity: ctx.severityDefault,+ category: 'continuity',+ location,+ problem: `All ${mono.classifiedCount} classified shots in "${sceneName}" are ${mono.shotType} — a scene shot in a single framing reads as flat, slideshow coverage with no establishing wide or punch-in for emphasis.`,+ suggestion: `Vary the coverage: open on a wider establishing framing, punch in to a close for an emotional or key beat, or add an over-the-shoulder for a two-character exchange.`,+ anchorQuote: '',+ issueNumber,+ });+ }+ }+ }+ return findings;+ },+ },{id: 'sensory.balance',sources: ['manuscript', 'reverseOutline'],diff --git a/server/lib/editorial/index.js b/server/lib/editorial/index.jsindex 85466f6f37..dcbe3c3481 100644--- a/server/lib/editorial/index.js+++ b/server/lib/editorial/index.js@@ -7,3 +7,4 @@ export * from './italicThoughts.js';export * from './nameSimilarity.js';export * from './proseTics.js';export * from './repetition.js';+export * from './shotContinuity.js';diff --git a/server/lib/editorial/shotContinuity.js b/server/lib/editorial/shotContinuity.jsnew file mode 100644index 0000000000..0a13adb474--- /dev/null+++ b/server/lib/editorial/shotContinuity.js@@ -0,0 +1,111 @@+/**+ * Storyboard / video shot-continuity deterministic primitives (#1315) for the+ * editorial check registry. Pure and dependency-free (no side-effecting imports)+ * so it stays unit-testable in isolation — mirrors ./nameSimilarity.js and the+ * other deterministic scanners.+ *+ * Backs the deterministic `visual.shot-continuity` check in checkRegistry.js,+ * which reasons over a storyboard scene's `shots[]` (each carrying the+ * film-grammar fields `shotType` + `screenDirection` + `continuityFromShotId`+ * from server/lib/shotGrammar.js). Two classic film-grammar errors are computable+ * from those signals without an LLM:+ *+ * 1. **180-degree rule (axis reversal).** When shot B chains from an earlier+ * shot A (`B.continuityFromShotId === A.id`) — i.e. the author declared the+ * two shots a continuous bridge — and the two shots face OPPOSITE screen+ * directions (one `left`, one `right`), the subject appears to flip sides+ * across the cut. That's an axis jump that disorients the viewer. A+ * continuity-linked pair is the high-precision trigger: the link is the+ * author's explicit "these are continuous" signal, so a direction flip+ * across it is a real error, not a legitimate reverse-angle.+ *+ * 2. **Shot-type monotony.** A scene whose shots ALL share one framing (every+ * shot `medium`, say) reads as flat, slideshow coverage — no establishing+ * wide, no punch-in for emphasis. Flagged only when enough shots are+ * classified to be confident it's monotony, not a sparse outline.+ *+ * High-precision by design (favors under-flagging, like the other deterministic+ * scanners). Unclassified shots (null `shotType` / `screenDirection`) are treated+ * as ABSENT — skipped, never guessed — per the absent-vs-empty rule. The judgment+ * cases this can't compute (eyeline match, appearance/prop continuity) are LLM+ * siblings tracked as follow-ups.+ */++// Two directions are an axis reversal only when both are decided AND opposite.+// `neutral` (head-on / ambiguous) has no axis to cross, so it never reverses.+function isAxisReversal(a, b) {+ if (a == null || b == null) return false;+ if (a === 'neutral' || b === 'neutral') return false;+ return a !== b; // one 'left', one 'right'+}++// Shots of a scene as a safe array (an older/peer-synced scene may carry a+// non-array `shots`). Each element is passed through untouched — the caller+// type-guards the fields it reads.+function sceneShots(scene) {+ return Array.isArray(scene?.shots) ? scene.shots : [];+}++/**+ * Detect 180-degree-rule axis reversals across continuity-linked shot pairs in+ * one scene. For every shot that chains from an earlier shot in the same scene,+ * compare their `screenDirection`; a decided-and-opposite pair is flagged.+ *+ * @param {object} scene a storyboard scene with `shots[]`+ * @returns {Array<{ fromId, toId, fromDirection, toDirection, fromDescription, toDescription }>}+ */+export function findAxisReversals(scene) {+ const shots = sceneShots(scene);+ if (shots.length < 2) return [];+ const byId = new Map();+ for (const s of shots) {+ if (s && typeof s === 'object' && typeof s.id === 'string' && s.id) byId.set(s.id, s);+ }+ const out = [];+ for (const shot of shots) {+ if (!shot || typeof shot !== 'object') continue;+ const fromId = typeof shot.continuityFromShotId === 'string' ? shot.continuityFromShotId : null;+ if (!fromId) continue;+ const prior = byId.get(fromId);+ if (!prior || prior === shot) continue;+ const fromDir = typeof prior.screenDirection === 'string' ? prior.screenDirection : null;+ const toDir = typeof shot.screenDirection === 'string' ? shot.screenDirection : null;+ if (!isAxisReversal(fromDir, toDir)) continue;+ out.push({+ fromId,+ toId: typeof shot.id === 'string' ? shot.id : '',+ fromDirection: fromDir,+ toDirection: toDir,+ fromDescription: typeof prior.description === 'string' ? prior.description : '',+ toDescription: typeof shot.description === 'string' ? shot.description : '',+ });+ }+ return out;+}++/**+ * Detect shot-type monotony in one scene: enough classified shots that they ALL+ * share a single `shotType`. Returns the monotony descriptor or null.+ *+ * Only CLASSIFIED shots (non-null `shotType`) count toward the verdict — an+ * outline where the extractor tagged framing on some shots but not others isn't+ * penalized for the untagged ones. The scene is flagged only when at least+ * `minClassified` shots are classified AND every classified one is the same type+ * (so a 2-of-5 partial tag never trips it).+ *+ * @param {object} scene+ * @param {{ minClassified?: number }} [opts] minClassified default 3+ * @returns {{ shotType: string, classifiedCount: number, totalShots: number } | null}+ */+export function findShotTypeMonotony(scene, opts = {}) {+ const minClassified = Math.max(2, Number.isInteger(opts.minClassified) ? opts.minClassified : 3);+ const shots = sceneShots(scene);+ const types = [];+ for (const s of shots) {+ if (s && typeof s === 'object' && typeof s.shotType === 'string' && s.shotType) types.push(s.shotType);+ }+ if (types.length < minClassified) return null;+ const first = types[0];+ if (!types.every((t) => t === first)) return null;+ return { shotType: first, classifiedCount: types.length, totalShots: shots.length };+}diff --git a/server/lib/editorial/shotContinuity.test.js b/server/lib/editorial/shotContinuity.test.jsnew file mode 100644index 0000000000..fe17963152--- /dev/null+++ b/server/lib/editorial/shotContinuity.test.js@@ -0,0 +1,128 @@+import { describe, it, expect } from 'vitest';+import { findAxisReversals, findShotTypeMonotony } from './shotContinuity.js';++describe('findAxisReversals', () => {+ it('flags an axis reversal across a continuity-linked left↔right pair', () => {+ const scene = {+ shots: [+ { id: 'a', description: 'hero faces left', screenDirection: 'left' },+ { id: 'b', description: 'reverse — hero faces right', screenDirection: 'right', continuityFromShotId: 'a' },+ ],+ };+ const out = findAxisReversals(scene);+ expect(out).toHaveLength(1);+ expect(out[0]).toMatchObject({ fromId: 'a', toId: 'b', fromDirection: 'left', toDirection: 'right' });+ });++ it('does NOT flag a continuity pair that keeps the same direction', () => {+ const scene = {+ shots: [+ { id: 'a', description: 'x', screenDirection: 'left' },+ { id: 'b', description: 'y', screenDirection: 'left', continuityFromShotId: 'a' },+ ],+ };+ expect(findAxisReversals(scene)).toEqual([]);+ });++ it('treats neutral (head-on) as no axis — never a reversal', () => {+ const scene = {+ shots: [+ { id: 'a', description: 'x', screenDirection: 'neutral' },+ { id: 'b', description: 'y', screenDirection: 'right', continuityFromShotId: 'a' },+ ],+ };+ expect(findAxisReversals(scene)).toEqual([]);+ });++ it('does NOT flag a direction flip between UNLINKED shots (a legitimate reverse angle)', () => {+ const scene = {+ shots: [+ { id: 'a', description: 'x', screenDirection: 'left' },+ { id: 'b', description: 'y', screenDirection: 'right' }, // no continuityFromShotId → fresh angle+ ],+ };+ expect(findAxisReversals(scene)).toEqual([]);+ });++ it('skips when either shot has an unclassified (null) direction', () => {+ const scene = {+ shots: [+ { id: 'a', description: 'x', screenDirection: null },+ { id: 'b', description: 'y', screenDirection: 'right', continuityFromShotId: 'a' },+ ],+ };+ expect(findAxisReversals(scene)).toEqual([]);+ });++ it('ignores a continuity ref to an unknown shot id', () => {+ const scene = {+ shots: [+ { id: 'b', description: 'y', screenDirection: 'right', continuityFromShotId: 'ghost' },+ ],+ };+ expect(findAxisReversals(scene)).toEqual([]);+ });++ it('returns [] for a non-array / empty / single-shot scene', () => {+ expect(findAxisReversals({})).toEqual([]);+ expect(findAxisReversals({ shots: 'nope' })).toEqual([]);+ expect(findAxisReversals({ shots: [{ id: 'a', screenDirection: 'left' }] })).toEqual([]);+ });+});++describe('findShotTypeMonotony', () => {+ it('flags a scene where every classified shot shares one framing', () => {+ const scene = {+ shots: [+ { id: 'a', shotType: 'medium' },+ { id: 'b', shotType: 'medium' },+ { id: 'c', shotType: 'medium' },+ ],+ };+ expect(findShotTypeMonotony(scene)).toMatchObject({ shotType: 'medium', classifiedCount: 3, totalShots: 3 });+ });++ it('does NOT flag a varied scene', () => {+ const scene = {+ shots: [+ { id: 'a', shotType: 'wide' },+ { id: 'b', shotType: 'medium' },+ { id: 'c', shotType: 'close' },+ ],+ };+ expect(findShotTypeMonotony(scene)).toBe(null);+ });++ it('does NOT flag when fewer than minClassified shots are classified', () => {+ const scene = {+ shots: [+ { id: 'a', shotType: 'medium' },+ { id: 'b', shotType: 'medium' },+ { id: 'c' }, // unclassified+ { id: 'd' }, // unclassified+ ],+ };+ // Only 2 classified, default minClassified is 3 → not enough confidence.+ expect(findShotTypeMonotony(scene)).toBe(null);+ // Lowering the threshold flags the all-medium classified pair.+ expect(findShotTypeMonotony(scene, { minClassified: 2 })).toMatchObject({ shotType: 'medium', classifiedCount: 2, totalShots: 4 });+ });++ it('ignores unclassified shots when judging monotony', () => {+ const scene = {+ shots: [+ { id: 'a', shotType: 'close' },+ { id: 'b' }, // unclassified — not counted+ { id: 'c', shotType: 'close' },+ { id: 'd', shotType: 'close' },+ ],+ };+ expect(findShotTypeMonotony(scene)).toMatchObject({ shotType: 'close', classifiedCount: 3 });+ });++ it('returns null for non-array / empty shots', () => {+ expect(findShotTypeMonotony({})).toBe(null);+ expect(findShotTypeMonotony({ shots: 'x' })).toBe(null);+ expect(findShotTypeMonotony({ shots: [] })).toBe(null);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 3e03b1e176..1cf7c56d98 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -51,6 +51,7 @@ export * from './creativeDirectorPrompts.js';export * as editorial from './editorial/index.js';export * from './sceneExtractor.js';export * from './scenePrompt.js';+export * from './shotGrammar.js';export * from './seasonStructure.js';export * from './seriesCharacterArc.js';export * from './seriesLlmOverride.js';diff --git a/server/lib/sceneExtractor.js b/server/lib/sceneExtractor.jsindex 368dcd353a..ace2358bec 100644--- a/server/lib/sceneExtractor.js+++ b/server/lib/sceneExtractor.js@@ -20,6 +20,7 @@import { runStagedLLM } from './stageRunner.js';import { BIBLE_KIND, pickPromptFields, isStr, trimTo } from './storyBible.js';+import { normalizeShotType, normalizeScreenDirection } from './shotGrammar.js';export const SOURCE_KIND = Object.freeze({ PROSE: 'prose', TELEPLAY: 'teleplay' });@@ -77,6 +78,11 @@ function sanitizeShot(sh, i) {description,durationSeconds,continuityFromShotId: continuityRaw || null,+ // Film-grammar signals (#1315) — both null when the extractor/UI didn't+ // tag them, so the continuity check skips an unclassified shot rather than+ // guessing. Normalized against their controlled vocabularies above.+ shotType: normalizeShotType(sh.shotType),+ screenDirection: normalizeScreenDirection(sh.screenDirection),};}diff --git a/server/lib/sceneExtractor.test.js b/server/lib/sceneExtractor.test.jsindex 3ab9ef0db6..b473f263a9 100644--- a/server/lib/sceneExtractor.test.js+++ b/server/lib/sceneExtractor.test.js@@ -107,11 +107,43 @@ describe('sanitizeSceneList', () => {}],});expect(out.scenes[0].shots).toEqual([- { id: 'shot-01', description: 'wide on the kitchen', durationSeconds: 5, continuityFromShotId: null },- { id: 'shot-02', description: 'close on the kettle', durationSeconds: 3, continuityFromShotId: 'shot-01' },+ { id: 'shot-01', description: 'wide on the kitchen', durationSeconds: 5, continuityFromShotId: null, shotType: null, screenDirection: null },+ { id: 'shot-02', description: 'close on the kettle', durationSeconds: 3, continuityFromShotId: 'shot-01', shotType: null, screenDirection: null },]);});+ it('captures + normalizes shot-grammar fields (shotType / screenDirection)', () => {+ const out = sanitizeSceneList({+ scenes: [{+ shots: [+ { id: 'shot-01', description: 'master', shotType: 'WIDE', screenDirection: 'Left' },+ { id: 'shot-02', description: 'reverse', shotType: 'CU', screenDirection: 'right' }, // alias + canonical+ { id: 'shot-03', description: 'insert', shotType: 'over the shoulder', screenDirection: 'head-on' }, // alias + neutral synonym+ ],+ }],+ });+ const shots = out.scenes[0].shots;+ expect(shots[0]).toMatchObject({ shotType: 'wide', screenDirection: 'left' });+ expect(shots[1]).toMatchObject({ shotType: 'close', screenDirection: 'right' });+ expect(shots[2]).toMatchObject({ shotType: 'over-the-shoulder', screenDirection: 'neutral' });+ });++ it('defaults shot-grammar fields to null when absent or unrecognized', () => {+ const out = sanitizeSceneList({+ scenes: [{+ shots: [+ { id: 'shot-01', description: 'untagged' }, // absent → null+ { id: 'shot-02', description: 'garbage', shotType: 'banana', screenDirection: 'sideways' }, // unknown → null+ { id: 'shot-03', description: 'wrong type', shotType: 42, screenDirection: {} }, // non-string → null+ ],+ }],+ });+ for (const s of out.scenes[0].shots) {+ expect(s.shotType).toBe(null);+ expect(s.screenDirection).toBe(null);+ }+ });+it('drops continuity references that point to unknown or forward shots', () => {const out = sanitizeSceneList({scenes: [{diff --git a/server/lib/shotGrammar.js b/server/lib/shotGrammar.jsnew file mode 100644index 0000000000..ef80b0204b--- /dev/null+++ b/server/lib/shotGrammar.js@@ -0,0 +1,82 @@+/**+ * Shot-grammar vocabulary + normalizers (#1315) — the canonical controlled+ * vocabularies for a storyboard shot's camera framing (`shotType`) and on-screen+ * direction (`screenDirection`), plus the normalizers that coerce raw LLM/UI+ * values onto them.+ *+ * Pure and dependency-free (no imports) so it's shared without a cycle by the+ * three layers that touch the shot shape:+ * - server/lib/sceneExtractor.js — sanitizes LLM-emitted shots+ * - server/lib/validation.js — the Zod enum for the storyboards stage shot schema+ * - server/lib/editorial/checkRegistry.js — the visual.shot-continuity check+ * reasons over `shotType` (monotony) + `screenDirection` (180°-rule axis reversal)+ *+ * Both fields default to null ("not captured") everywhere so an older outline or+ * a shot the extractor didn't tag is treated as ABSENT (skipped by the continuity+ * check) rather than mis-classified — the absent-vs-empty rule from CLAUDE.md.+ */++// Camera framing / size. Ordered loosely widest→tightest; the continuity check+// reads the membership only (it doesn't assume the order), so reordering is safe.+export const SHOT_TYPES = Object.freeze([+ 'extreme-wide', // landscape / crowd master where figures are small+ 'wide', // full-figure establishing of the space+ 'medium', // waist/chest framing — the default coverage shot+ 'close', // face/detail framing+ 'extreme-close', // an eye, a hand, an object insert+ 'over-the-shoulder', // OTS — frames one subject past another's shoulder+ 'two-shot', // two subjects sharing the frame+ 'pov', // the subject's literal point of view+]);+const SHOT_TYPE_SET = new Set(SHOT_TYPES);++// On-screen direction the subject faces / moves. `neutral` = head-on or+// ambiguous (no axis to cross); `left`/`right` are the screen-relative sides the+// 180°-rule check tracks for axis reversals between continuity-linked shots.+export const SCREEN_DIRECTIONS = Object.freeze(['left', 'right', 'neutral']);+const SCREEN_DIRECTION_SET = new Set(SCREEN_DIRECTIONS);++// Common synonyms the model (or a hand-edit) emits, mapped onto the canonical+// token so a near-miss isn't silently dropped to null. Keys are pre-lowercased.+const SHOT_TYPE_ALIASES = Object.freeze({+ ews: 'extreme-wide', 'extreme wide': 'extreme-wide',+ establishing: 'wide', ws: 'wide', long: 'wide', full: 'wide', 'full-shot': 'wide',+ ms: 'medium', mid: 'medium', 'mid-shot': 'medium',+ cu: 'close', closeup: 'close', 'close-up': 'close',+ ecu: 'extreme-close', 'extreme closeup': 'extreme-close', 'extreme close-up': 'extreme-close',+ insert: 'extreme-close', detail: 'extreme-close',+ ots: 'over-the-shoulder', 'over the shoulder': 'over-the-shoulder',+ two: 'two-shot', '2-shot': 'two-shot', 'two shot': 'two-shot',+ 'point of view': 'pov', "subject's pov": 'pov',+});++/**+ * Normalize a raw shot-type value against {@link SHOT_TYPES}. Lowercases + trims+ * so "Wide" / "WIDE " resolve; maps a known synonym via the alias table;+ * otherwise returns null (unknown / non-string / empty → "not captured").+ * @param {*} raw+ * @returns {string|null}+ */+export function normalizeShotType(raw) {+ if (typeof raw !== 'string') return null;+ const v = raw.trim().toLowerCase();+ if (!v) return null;+ if (SHOT_TYPE_SET.has(v)) return v;+ return SHOT_TYPE_ALIASES[v] || null;+}++/**+ * Normalize a raw screen-direction value against {@link SCREEN_DIRECTIONS}.+ * Head-on synonyms (center / front / head-on) collapse to `neutral`; unknown /+ * non-string / empty → null.+ * @param {*} raw+ * @returns {string|null}+ */+export function normalizeScreenDirection(raw) {+ if (typeof raw !== 'string') return null;+ const v = raw.trim().toLowerCase();+ if (!v) return null;+ if (SCREEN_DIRECTION_SET.has(v)) return v;+ if (v === 'center' || v === 'centre' || v === 'front' || v === 'head-on' || v === 'facing') return 'neutral';+ return null;+}diff --git a/server/lib/shotGrammar.test.js b/server/lib/shotGrammar.test.jsnew file mode 100644index 0000000000..8c095552cd--- /dev/null+++ b/server/lib/shotGrammar.test.js@@ -0,0 +1,65 @@+import { describe, it, expect } from 'vitest';+import {+ SHOT_TYPES,+ SCREEN_DIRECTIONS,+ normalizeShotType,+ normalizeScreenDirection,+} from './shotGrammar.js';++describe('shotGrammar vocabularies', () => {+ it('exposes frozen, non-empty controlled vocabularies', () => {+ expect(Object.isFrozen(SHOT_TYPES)).toBe(true);+ expect(Object.isFrozen(SCREEN_DIRECTIONS)).toBe(true);+ expect(SHOT_TYPES.length).toBeGreaterThan(0);+ expect(SCREEN_DIRECTIONS).toEqual(['left', 'right', 'neutral']);+ });+});++describe('normalizeShotType', () => {+ it('passes canonical tokens through, case- and whitespace-insensitively', () => {+ expect(normalizeShotType('wide')).toBe('wide');+ expect(normalizeShotType(' MEDIUM ')).toBe('medium');+ expect(normalizeShotType('Over-The-Shoulder')).toBe('over-the-shoulder');+ });++ it('maps common synonyms onto canonical tokens', () => {+ expect(normalizeShotType('CU')).toBe('close');+ expect(normalizeShotType('close-up')).toBe('close');+ expect(normalizeShotType('establishing')).toBe('wide');+ expect(normalizeShotType('OTS')).toBe('over-the-shoulder');+ expect(normalizeShotType('insert')).toBe('extreme-close');+ expect(normalizeShotType('point of view')).toBe('pov');+ });++ it('returns null for unknown / non-string / empty', () => {+ expect(normalizeShotType('banana')).toBe(null);+ expect(normalizeShotType('')).toBe(null);+ expect(normalizeShotType(' ')).toBe(null);+ expect(normalizeShotType(42)).toBe(null);+ expect(normalizeShotType(null)).toBe(null);+ expect(normalizeShotType(undefined)).toBe(null);+ expect(normalizeShotType({})).toBe(null);+ });+});++describe('normalizeScreenDirection', () => {+ it('passes canonical tokens through, case- and whitespace-insensitively', () => {+ expect(normalizeScreenDirection('left')).toBe('left');+ expect(normalizeScreenDirection(' RIGHT ')).toBe('right');+ expect(normalizeScreenDirection('Neutral')).toBe('neutral');+ });++ it('collapses head-on synonyms to neutral', () => {+ for (const v of ['center', 'centre', 'front', 'head-on', 'facing']) {+ expect(normalizeScreenDirection(v)).toBe('neutral');+ }+ });++ it('returns null for unknown / non-string / empty', () => {+ expect(normalizeScreenDirection('sideways')).toBe(null);+ expect(normalizeScreenDirection('')).toBe(null);+ expect(normalizeScreenDirection(0)).toBe(null);+ expect(normalizeScreenDirection(null)).toBe(null);+ expect(normalizeScreenDirection(undefined)).toBe(null);+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 54ddabf39e..2eabdaa2bb 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -6,6 +6,7 @@ import { ALL_STYLE_IDS, STYLE_ID } from './writersRoomStylePresets.js';import { BIBLE_LIMITS, RELATIONSHIP_LINK_TYPES, RELATIONSHIP_OPPOSITION_AXES, ATTACHMENT_ROLES } from './storyBible.js';import { MIN_TIMEOUT as STAGE_TIMEOUT_MIN_MS, MAX_TIMEOUT as STAGE_TIMEOUT_MAX_MS } from './aiToolkit/constants.js';import { CHECK_SCOPES, CHECK_SEVERITIES } from './editorial/checkRegistry.js';+import { SHOT_TYPES, SCREEN_DIRECTIONS } from './shotGrammar.js';import { WORK_TRACKERS } from './workTracker.js';// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total@@ -1121,6 +1122,43 @@ export const writersRoomSnapshotSchema = z.object({label: z.string().trim().min(1).max(100).optional()}).strict();+// A single storyboard shot within `stages.storyboards.scenes[].shots[]` (#1315).+// Validates the known shot fields and the new film-grammar enums (`shotType`,+// `screenDirection`) — each nullable + tolerant of the UI's "not captured"+// sentinel (null) and an empty-string clear (preprocessed to undefined). It is+// `.passthrough()` (NOT strip) because render-time hooks stamp extra fields onto+// a shot (`startFrameJobId`) that must survive a re-PATCH of the scenes array;+// the load-bearing normalization still happens in `sanitizeShot`+// (sceneExtractor.js) on the auto-extract path, but the route validates the+// enums up front so an invalid framing/direction is rejected, not silently kept.+export const storyboardShotSchema = z.object({+ // id / description are optional here (not at the sanitizer) so the route stays+ // as tolerant as `sanitizeShot`, which synthesizes a missing id and drops a+ // description-less shot — the route's job is only to reject a bad enum, not to+ // tighten the existing client contract.+ id: z.string().trim().max(80).optional(),+ description: z.string().max(2000).optional(),+ durationSeconds: z.number().int().min(1).max(30).optional(),+ continuityFromShotId: z.string().trim().max(80).nullable().optional(),+ shotType: z.preprocess(+ (v) => (v === '' ? null : v),+ z.enum(SHOT_TYPES).nullable().optional(),+ ),+ screenDirection: z.preprocess(+ (v) => (v === '' ? null : v),+ z.enum(SCREEN_DIRECTIONS).nullable().optional(),+ ),+}).passthrough();++// A storyboard scene as submitted through the visual-stage PATCH. Kept+// `.passthrough()` so the rich, evolving scene shape (heading, slugline,+// dialogue, sceneVideoJobId, …) flows through untouched — only `shots[]` is+// validated (through storyboardShotSchema) so a bad shotType/screenDirection+// is caught at the route instead of persisting unnormalized.+export const storyboardSceneSchema = z.object({+ shots: z.array(storyboardShotSchema).max(64).optional(),+}).passthrough();+export const writersRoomExerciseCreateSchema = z.object({workId: wrIdNullable.optional(),prompt: z.string().max(2000).optional().default(''),diff --git a/server/lib/validation.test.js b/server/lib/validation.test.jsindex 9f2425d833..d17176ed16 100644--- a/server/lib/validation.test.js+++ b/server/lib/validation.test.js@@ -19,7 +19,9 @@ import {writersRoomCharacterUpdateSchema,writersRoomObjectUpdateSchema,editorialCustomCheckUpdateSchema,- pipelineEditorialChecksSettingsSchema+ pipelineEditorialChecksSettingsSchema,+ storyboardShotSchema,+ storyboardSceneSchema} from './validation.js';describe('validation.js', () => {@@ -890,4 +892,43 @@ describe('validation.js', () => {expect(result.data.customChecks[0].futureField).toEqual({ nested: true }); // unknown keys preserved});});++ describe('storyboardShotSchema / storyboardSceneSchema (#1315)', () => {+ it('accepts valid shot-grammar enums', () => {+ const r = storyboardShotSchema.safeParse({ id: 'shot-01', description: 'x', shotType: 'wide', screenDirection: 'left' });+ expect(r.success).toBe(true);+ expect(r.data).toMatchObject({ shotType: 'wide', screenDirection: 'left' });+ });++ it('rejects an unknown shotType / screenDirection', () => {+ expect(storyboardShotSchema.safeParse({ id: 's', shotType: 'banana' }).success).toBe(false);+ expect(storyboardShotSchema.safeParse({ id: 's', screenDirection: 'sideways' }).success).toBe(false);+ });++ it('tolerates the UI sentinels: null and empty-string clear', () => {+ expect(storyboardShotSchema.safeParse({ id: 's', shotType: null, screenDirection: null }).success).toBe(true);+ const r = storyboardShotSchema.safeParse({ id: 's', shotType: '', screenDirection: '' });+ expect(r.success).toBe(true);+ expect(r.data.shotType).toBeNull(); // '' → null (treated as "not captured")+ expect(r.data.screenDirection).toBeNull();+ });++ it('passes through render-time fields stamped onto a shot (startFrameJobId)', () => {+ const r = storyboardShotSchema.safeParse({ id: 's', description: 'x', startFrameJobId: 'job-9' });+ expect(r.success).toBe(true);+ expect(r.data.startFrameJobId).toBe('job-9');+ });++ it('scene schema validates shots[] but passes the rest of the scene through', () => {+ const r = storyboardSceneSchema.safeParse({+ heading: 'INT. ROOM', slugline: 'INT. ROOM — DAY', sceneVideoJobId: 'v1',+ shots: [{ id: 'shot-01', description: 'x', shotType: 'medium', screenDirection: 'right' }],+ });+ expect(r.success).toBe(true);+ expect(r.data.heading).toBe('INT. ROOM');+ expect(r.data.sceneVideoJobId).toBe('v1');+ // A bad enum inside shots[] fails the whole scene.+ expect(storyboardSceneSchema.safeParse({ shots: [{ id: 's', shotType: 'nope' }] }).success).toBe(false);+ });+ });});diff --git a/server/routes/pipeline/issues.js b/server/routes/pipeline/issues.jsindex c4e4d8ccac..a67d60a09f 100644--- a/server/routes/pipeline/issues.js+++ b/server/routes/pipeline/issues.js@@ -13,6 +13,7 @@ import {imageEdgeSchema,refineImagePixelCap,PIXEL_CAP_MESSAGE,+ storyboardSceneSchema,} from '../../lib/validation.js';import * as seriesSvc from '../../services/pipeline/series.js';import * as issuesSvc from '../../services/pipeline/issues.js';@@ -89,7 +90,11 @@ const audioCueInputSchema = z.object({// migration; the service-level sanitizer caps array length.const visualStageInputSchema = stageInputSchema.extend({pages: z.array(z.any()).max(200).optional(),- scenes: z.array(z.any()).max(200).optional(),+ // Scenes stay passthrough (the rich scene shape evolves freely), but each+ // scene's shots[] is validated through storyboardSceneSchema so a bad+ // shotType/screenDirection enum is rejected at the route (#1315) instead of+ // persisting unnormalized. Non-storyboard visual stages simply carry no shots.+ scenes: z.array(storyboardSceneSchema).max(200).optional(),cdProjectId: z.string().trim().max(64).nullable().optional(),videoPath: z.string().trim().max(1000).nullable().optional(),aspectRatio: z.enum(ASPECT_RATIOS).nullable().optional(),diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.jsindex 731c15feb1..e6a1967cc0 100644--- a/server/services/pipeline/editorial/checkRunner.js+++ b/server/services/pipeline/editorial/checkRunner.js@@ -81,8 +81,30 @@ const SOURCE_RESOLVERS = {// 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). Built off the already-loaded issues (no extra I/O); fingerprint the+ // flattened `{ issueNumber, scene }` list so any shot edit (framing, direction,+ // continuity link) stales the finding. Over-eager-but-safe, like reverseOutline.+ 'storyboard.shots': ({ storyboardScenes }) => canonicalStringify(storyboardScenes ?? 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;+}+// 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.@@ -208,6 +230,9 @@ export async function runEditorialChecks(seriesId, options = {}) {needsEditorialArcs ? getSeriesEditorial(seriesId, { series }).catch(() => null) : Promise.resolve(null),]);const manuscript = sectionsCorpus(sections);+ // Storyboard shots for the visual.shot-continuity check (#1315) — built off the+ // already-loaded issues, so no extra I/O regardless of whether the 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@@ -222,7 +247,7 @@ export async function runEditorialChecks(seriesId, options = {}) {// 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, series, reverseOutline, reverseOutlinePlotlines, editorialArcs, editorialArcsComplete });+ const resolvedSources = resolveSources({ manuscript, canon, series, reverseOutline, reverseOutlinePlotlines, editorialArcs, editorialArcsComplete, storyboardScenes });const baseCtx = {seriesId,series,@@ -233,6 +258,7 @@ export async function runEditorialChecks(seriesId, options = {}) {reverseOutlinePlotlines,editorialArcs,editorialArcsComplete,+ storyboardScenes,canon,providerOverride,modelOverride,@@ -380,19 +406,23 @@ export async function getReviewWithStaleness(seriesId) {return sources.includes('reverseOutline') || sources.includes('reverseOutline.plotlines');});const needsEditorialArcs = evaluable.some((c) => checkSources(checkFor(c.checkId)).includes('editorialArcs'));+ // Storyboard shots staleness (#1315) — fetch issues only when an evaluable check+ // declares the source, mirroring the other gated fetches.+ const needsStoryboards = evaluable.some((c) => checkSources(checkFor(c.checkId)).includes('storyboard.shots'));const series = await getSeries(seriesId);- const [sections, canon, outline, editorial] = await Promise.all([+ const [sections, canon, outline, editorial, issues] = await Promise.all([needsManuscript ? collectManuscriptSections(seriesId) : Promise.resolve([]),getSeriesCanon(series),needsReverseOutline ? getReverseOutline(seriesId).catch(() => null) : Promise.resolve(null),- // Reuse the already-loaded series (issues isn't fetched on this path).needsEditorialArcs ? getSeriesEditorial(seriesId, { series }).catch(() => null) : Promise.resolve(null),+ needsStoryboards ? listIssues({ seriesId }).catch(() => []) : Promise.resolve([]),]);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 resolvedSources = resolveSources({ manuscript: sectionsCorpus(sections), canon, series, reverseOutline, reverseOutlinePlotlines, editorialArcs, editorialArcsComplete });+ const storyboardScenes = collectStoryboardScenes(issues);+ const resolvedSources = resolveSources({ manuscript: sectionsCorpus(sections), canon, series, reverseOutline, reverseOutlinePlotlines, editorialArcs, editorialArcsComplete, storyboardScenes });return {...review,comments: review.comments.map((c) => {diff --git a/server/services/pipeline/editorial/checkRunner.test.js b/server/services/pipeline/editorial/checkRunner.test.jsindex a7cf4a1ac6..8791011f09 100644--- a/server/services/pipeline/editorial/checkRunner.test.js+++ b/server/services/pipeline/editorial/checkRunner.test.js@@ -4,7 +4,11 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';// 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' })) }));-vi.mock('../issues.js', () => ({ listIssues: vi.fn(async () => []) }));+// 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.+let issuesState = [];+vi.mock('../issues.js', () => ({ listIssues: vi.fn(async () => issuesState) }));vi.mock('../seriesCanon.js', () => ({getSeriesCanon: vi.fn(async () => ({characters: [{ name: 'Alina' }, { name: 'Alana' }, { name: 'Zog' }],@@ -91,6 +95,7 @@ beforeEach(() => {reviewState = { comments: [] };outlineState = { scenes: [] };editorialState = { characters: [] };+ issuesState = [];seedReviewFromFindings.mockClear();runStagedLLM.mockClear();resolveStageContext.mockClear();@@ -264,6 +269,46 @@ describe('runEditorialChecks', () => {});});+describe('visual.shot-continuity (#1315)', () => {+ // Enable ONLY the shot-continuity check so the assertions don't pick up+ // naming/info-dump findings (and the LLM mock isn't exercised).+ const onlyShotContinuity = {+ pipelineEditorialChecks: {+ checks: Object.fromEntries(+ listChecks().filter((c) => c.id !== 'visual.shot-continuity').map((c) => [c.id, { enabled: false }]),+ ),+ },+ };++ it('flags a 180° axis reversal across continuity-linked shots in a storyboard scene', async () => {+ issuesState = [{+ id: 'i1', seriesId: 's1', number: 1,+ stages: { storyboards: { scenes: [{+ heading: 'INT. THRONE ROOM',+ shots: [+ { id: 'shot-01', description: 'queen faces left', screenDirection: 'left' },+ { id: 'shot-02', description: 'reverse', screenDirection: 'right', continuityFromShotId: 'shot-01' },+ ],+ }] } },+ }];+ const result = await runEditorialChecks('s1', { settings: onlyShotContinuity });+ const findings = result.findings.filter((f) => f.checkId === 'visual.shot-continuity');+ expect(findings).toHaveLength(1);+ expect(findings[0].category).toBe('continuity');+ expect(findings[0].issueNumber).toBe(1);+ expect(findings[0].problem).toMatch(/axis reversal/i);+ expect(runStagedLLM).not.toHaveBeenCalled(); // deterministic — no LLM+ });++ it('skips entirely (gated off) when no issue has storyboard scenes', async () => {+ issuesState = [{ id: 'i1', seriesId: 's1', number: 1, stages: {} }];+ const result = await runEditorialChecks('s1', { settings: onlyShotContinuity });+ const row = result.perCheck.find((p) => p.checkId === 'visual.shot-continuity');+ expect(row.skipped).toBe(true);+ expect(result.findings).toHaveLength(0);+ });+});+describe('source-content hash stamping (#1345)', () => {it('stamps every finding with a non-empty sourceContentHash', async () => {const result = await runEditorialChecks('s1');@@ -365,6 +410,37 @@ describe('getReviewWithStaleness (#1345)', () => {expect(review.comments.find((c) => c.checkId === 'prose.info-dumping').stale).toBe(false);});+ it('stales the storyboard-continuity finding when a shot edit changes the scene (#1315)', async () => {+ // visual.shot-continuity declares 'storyboard.shots'; editing a shot's+ // direction must stale ONLY the continuity finding, not the canon-only naming one.+ issuesState = [{+ id: 'i1', seriesId: 's1', number: 1,+ stages: { storyboards: { scenes: [{+ heading: 'INT. THRONE ROOM',+ shots: [+ { id: 'shot-01', description: 'left', screenDirection: 'left' },+ { id: 'shot-02', description: 'right', screenDirection: 'right', continuityFromShotId: 'shot-01' },+ ],+ }] } },+ }];+ await seedReviewFromRun();+ expect(reviewState.comments.find((c) => c.checkId === 'visual.shot-continuity')).toBeTruthy();+ // Fix the axis (both face left) — the shot list drifts.+ issuesState = [{+ id: 'i1', seriesId: 's1', number: 1,+ stages: { storyboards: { scenes: [{+ heading: 'INT. THRONE ROOM',+ shots: [+ { id: 'shot-01', description: 'left', screenDirection: 'left' },+ { id: 'shot-02', description: 'left now', screenDirection: 'left', continuityFromShotId: 'shot-01' },+ ],+ }] } },+ }];+ const review = await getReviewWithStaleness('s1');+ expect(review.comments.find((c) => c.checkId === 'visual.shot-continuity').stale).toBe(true);+ expect(review.comments.find((c) => c.checkId === 'naming.dissimilar-names').stale).toBe(false);+ });+it('keeps a scene finding fresh when the manuscript changes (reverseOutline-only source)', async () => {outlineState = { scenes: [{ id: 'scene-001', issueNumber: 1, heading: 'Talking heads', anchorQuote: 'q', components: { narrative: false, action: false, dialogue: true } }] };await seedReviewFromRun();