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-2172]): craft-knowledge prompt upgrades — anti-patterns, Stability Trap, foreshadowing ledger
[._.]/ Adam Eivy88f6512641a0
diff --git a/data.reference/prompts/_partials/craft-anti-patterns.md b/data.reference/prompts/_partials/craft-anti-patterns.mdnew file mode 100644index 0000000000..0f70a33f27--- /dev/null+++ b/data.reference/prompts/_partials/craft-anti-patterns.md@@ -0,0 +1,25 @@+## Craft rules — anti-patterns to avoid++These are hard-won lessons about prose that reads as machine-generated. Follow them while drafting; a first draft that respects them needs far less editorial repair.++- **No triadic sensory lists.** Avoid the "X. Y. Z." rhythm of three parallel sensory fragments in a row (e.g. "The rain fell. The wind howled. The cold bit."). Combine two of them and cut the third.+- **"did not [verb]" ≤ once per chapter.** Negated-action constructions ("she did not move," "he did not answer") are a crutch. Prefer showing what the character *does* instead. Allow at most one per chapter.+- **No "thought about X" constructions.** Never write "she thought about the letter" or "he considered his options." Replace the reported thought with the thought itself (rendered directly), an action that reveals it, or a line of dialogue.+- **"the way X did Y" similes ≤ twice per chapter.** The "…the way the light did…" / "…the way she always did…" simile pattern reads as filler. Cap it at two per chapter; earn each one.+- **No over-explaining after showing.** If a scene demonstrates something — a character's fear, a relationship's tension, a stakes shift — do not have the narrator restate it afterward. Trust the demonstration and move on.+- **Section breaks ≤ two per chapter.** Hard section breaks (blank-line / horizontal-rule scene cuts within a chapter) fragment momentum. Use at most two per chapter.+- **Vary paragraph length.** Never write three or more consecutive paragraphs of similar length. Break the pattern deliberately — a one-line paragraph after two dense ones, or vice versa.+- **End each chapter differently from previous chapters.** Do not fall into a repeated closing rhythm (every chapter ending on a line of dialogue, or a lone-image beat, or an em-dash). Vary how endings land across the work.+- **At least 70% in-scene, not summary.** The majority of the prose should be dramatized moment-to-moment scene, not narrated summary ("Over the next week, they…"). Summary is for compression between scenes, not the default mode.+- **Dialogue sounds like speech, not polished prose.** People interrupt, trail off, use contractions and fragments, dodge the question. Do not write dialogue that reads like edited essay prose.+- **Include at least one genuinely surprising moment.** Every chapter should contain at least one beat the reader could not have predicted a paragraph earlier — a reveal, a reversal, an unexpected reaction. Predictable-throughout is a failure state.++## Stability Trap countermeasures++AI-drafted stories drift toward *stability*: characters resist real change, conflicts resolve too cleanly, nothing is truly lost, everything is revealed at once, and the emotional register sits at "room temperature." Actively push against this:++- **Characters must end TRULY different.** By the end of the chapter/issue, at least one character is meaningfully changed — a belief broken, a relationship altered, a line crossed. A character who ends exactly where they began is a warning sign.+- **Let bad things stay bad.** Not every wound gets bandaged. Resist the reflex to soften, walk back, or console away a hard beat before the scene ends.+- **Allow irreversible loss.** Real stakes require that some things cannot be undone — a death, a betrayal, a burned bridge. At least one consequence in the arc should be permanent.+- **Withhold information (information economy).** Do not reveal everything the moment it becomes relevant. Hold back what the character or reader doesn't yet need; let questions sit unanswered across scenes.+- **A choice with no real cost is not a real choice.** Every meaningful decision must cost the character something they wanted. If a choice is free, raise the price or cut it.diff --git a/data.reference/prompts/stages/pipeline-arc-overview.md b/data.reference/prompts/stages/pipeline-arc-overview.mdindex ea4efd6b6a..6dcfba4204 100644--- a/data.reference/prompts/stages/pipeline-arc-overview.md+++ b/data.reference/prompts/stages/pipeline-arc-overview.md@@ -60,6 +60,13 @@ The series is grounded in this World Builder world: **{{worldName}}**. When you- **`logline`** — one sentence; what changes in this season.- **`endingHook`** — the image or line that pulls the audience into season N+1. Skippable for the final season (leave empty).- **`episodeCountTarget`** — integer. Divide `issueCountTarget` across the seasons roughly proportionally to season weight. Sum of all `episodeCountTarget`s should approximately equal `issueCountTarget`.+6. **Foreshadowing ledger (2–6 seeds).** Plan the major setups the series plants early and pays off later — a Chekhov's gun, a prophecy, an unexplained scar, a withheld secret. For each seed record:+ - **`label`** — a short name for the seed (e.g. *The locked room*, *Mara's limp*, *The recurring bell*).+ - **`plantIssue`** — the 1-indexed issue number where it's first planted (subtly introduced, not explained).+ - **`reinforceIssues`** — 0 or more issue numbers between plant and payoff where the seed is quietly reinforced so the reader doesn't forget it. Keep it a light touch — a glimpse, not a recap.+ - **`payoffIssue`** — the issue number where it fires / is resolved.+ - **`note`** — one sentence on what the payoff delivers.+ - **Distance rule:** `payoffIssue` must be **at least 3 issues after** `plantIssue`. A payoff that lands right after its plant isn't foreshadowing — it's just setup-and-immediate-use. Spread seeds so the reader has time to forget before the gun fires.## Output contract@@ -80,6 +87,15 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c"endingHook": "string","episodeCountTarget": 8}+ ],+ "foreshadowing": [+ {+ "label": "string (short name for the planted seed)",+ "plantIssue": 1,+ "reinforceIssues": [3],+ "payoffIssue": 6,+ "note": "string (what the payoff delivers)"+ }]}```diff --git a/data.reference/prompts/stages/pipeline-prose.md b/data.reference/prompts/stages/pipeline-prose.mdindex a3c9fe8776..58ca884c6e 100644--- a/data.reference/prompts/stages/pipeline-prose.md+++ b/data.reference/prompts/stages/pipeline-prose.md@@ -60,4 +60,6 @@ A self-contained short-story draft for this issue, **{{lengthTargets.proseWordsM- **Land the ending on a cliffhanger or strong lead-in to the next issue** — a reveal that flips what the reader thought, a character in unresolved peril, or an antagonist's arrival. The last paragraph is what the comic's final-page panel will render, so make it visually decisive. Resolution-only endings are not acceptable; serialized comics need pull.- Don't invent contradictions to the character bible. Add details, but match the established ones.+{{> craft-anti-patterns }}+Return ONLY the prose. No commentary, no header summarizing the piece, no preamble. Start with the first `## Scene 1 — …` heading.diff --git a/data.reference/prompts/stages/writers-room-continue.md b/data.reference/prompts/stages/writers-room-continue.mdindex 9e0c2716ae..ca113154cd 100644--- a/data.reference/prompts/stages/writers-room-continue.md+++ b/data.reference/prompts/stages/writers-room-continue.md@@ -32,6 +32,10 @@ Read the surrounding prose and propose **2 to 4** short continuation options theMatch the established voice, tense, and point of view. Do not contradict what comes after the cursor. Prefer concrete, scene-level moves (an action, a line of dialogue, a turn) over abstract advice. If the selected passage is non-empty, treat it as the focus and suggest how to extend or pivot from it specifically.+When your suggestions include drafted prose (`kind: "prose"` or `"dialogue"`), hold that snippet to the same craft bar the rest of the work is drafted against:++{{> craft-anti-patterns }}+Each option has:- `kind`: "beat" (a direction to take) | "prose" (a ready-to-insert snippet) | "dialogue" (a suggested line)- `label`: a 3–8 word summary of the directiondiff --git a/scripts/migrations/003-update-pipeline-stage-prompts.js b/scripts/migrations/003-update-pipeline-stage-prompts.jsindex 70c37121aa..1f800ff547 100644--- a/scripts/migrations/003-update-pipeline-stage-prompts.js+++ b/scripts/migrations/003-update-pipeline-stage-prompts.js@@ -32,6 +32,7 @@ export const ACCEPTED_OLD_MD5 = {'30ac30ec2b9d3e2a9eb869c181732cc6', // post-003 / pre-027 — the hash this migration originally produced'd1f8e3f1d214725b5aa67f309a81cd7d', // post-027 / pre-054'bef1bc2767b78f585f2bd89f3d615130', // post-054 / pre-054-fence+ '25e3d58c2741bd98acd5d08ba70d8a5e', // post-127 / pre-164 (scene markers)],'pipeline-comic-script.md': [ 'a4303016c34b65e4b0e641fe71252de3','40e5fdc1a1e68a7419b7dad936366c1a', // pre-003 (original)@@ -52,7 +53,7 @@ export const ACCEPTED_OLD_MD5 = {export const NEW_SHIPPED_MD5 = {'pipeline-idea-expansion.md': 'd6fa86a435f978336661dcabca67258f', // post-127 (scene markers)- 'pipeline-prose.md': '25e3d58c2741bd98acd5d08ba70d8a5e', // post-127 (scene markers)+ 'pipeline-prose.md': '430d38ed2da59e0d4212e65edc499a74', // post-164 (craft anti-patterns)'pipeline-comic-script.md': '49af30c05f008b20f6998a0f113f7d87', // post-127 (scene markers)'pipeline-tv-script.md': '376f779f4687b598f1c92ca4e770fd5a', // retired upstream (no data.reference)'pipeline-season-episodes.md': '50c68a29c3ebc275db3095d06bd87100', // post-005diff --git a/scripts/migrations/005-shape-aware-arc-prompts.js b/scripts/migrations/005-shape-aware-arc-prompts.jsindex cca5d0fa73..7f202c0029 100644--- a/scripts/migrations/005-shape-aware-arc-prompts.js+++ b/scripts/migrations/005-shape-aware-arc-prompts.js@@ -24,6 +24,7 @@ export const ACCEPTED_OLD_MD5 = {'pipeline-arc-overview.md': ['6a3ecab43d1f46b7ef9aab6c69ea0326', // pre-005 (original)'d34d72b8e49ba303d38607845dd87f1c', // post-005 / pre-019 — the hash this migration originally produced+ '0a1f6ffa6908522e3690c5e9e53a6ee0', // post-019 / pre-164 (foreshadowing ledger)],'pipeline-arc-verify.md': ['52e31abc93e3105176236fcaa5d1575a', // pre-005 (original)@@ -43,7 +44,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-arc-overview.md': '0a1f6ffa6908522e3690c5e9e53a6ee0', // post-019+ 'pipeline-arc-overview.md': '612f8b04950e2ff26dd350dd76a062fe', // post-164 (foreshadowing ledger)'pipeline-arc-verify.md': '36aa70cdfc25d7549573a4d556e7702c', // post-019'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940', // post-019'pipeline-season-episodes.md': '50c68a29c3ebc275db3095d06bd87100', // post-005 (live sample)diff --git a/scripts/migrations/019-arc-volume-prompts-canon-context.js b/scripts/migrations/019-arc-volume-prompts-canon-context.jsindex 656d1a1323..d644a76da6 100644--- a/scripts/migrations/019-arc-volume-prompts-canon-context.js+++ b/scripts/migrations/019-arc-volume-prompts-canon-context.js@@ -39,6 +39,7 @@ export const ACCEPTED_OLD_MD5 = {'pipeline-arc-overview.md': ['d34d72b8e49ba303d38607845dd87f1c', // current (pre-Phase B) shipped'6a3ecab43d1f46b7ef9aab6c69ea0326', // pre-005 (shape-aware), still in setup-data.js OLD list+ '0a1f6ffa6908522e3690c5e9e53a6ee0', // post-019 / pre-164 (foreshadowing ledger)],'pipeline-arc-verify.md': ['ff56d8387162017e08d5d0491060ddd6', // current (pre-Phase B) shipped@@ -57,7 +58,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-arc-overview.md': '0a1f6ffa6908522e3690c5e9e53a6ee0', // post-019+ 'pipeline-arc-overview.md': '612f8b04950e2ff26dd350dd76a062fe', // post-164 (foreshadowing ledger)'pipeline-arc-verify.md': '36aa70cdfc25d7549573a4d556e7702c', // post-019'pipeline-arc-resolve.md': 'cc27b4da1d1a13c35e35d1c2d6183815', // post-123 (episodes[] correction channel)'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940', // post-019diff --git a/scripts/migrations/027-text-stage-prompts-entities-summary.js b/scripts/migrations/027-text-stage-prompts-entities-summary.jsindex 09f6d6bbbd..85e77e06d1 100644--- a/scripts/migrations/027-text-stage-prompts-entities-summary.js+++ b/scripts/migrations/027-text-stage-prompts-entities-summary.js@@ -42,6 +42,7 @@ export const ACCEPTED_OLD_MD5 = {'bfea5aeeb471aae9749baee765b473a7', // pre-003 (in setup-data OLD list)'d1f8e3f1d214725b5aa67f309a81cd7d', // post-027 / pre-054'bef1bc2767b78f585f2bd89f3d615130', // post-054 / pre-054-fence+ '25e3d58c2741bd98acd5d08ba70d8a5e', // post-127 / pre-164 (scene markers)],'pipeline-teleplay.md': ['376f779f4687b598f1c92ca4e770fd5a', // pre-027 shipped@@ -66,7 +67,7 @@ export const ACCEPTED_OLD_MD5 = {};export const NEW_SHIPPED_MD5 = {- 'pipeline-prose.md': '25e3d58c2741bd98acd5d08ba70d8a5e', // post-127 (scene markers)+ 'pipeline-prose.md': '430d38ed2da59e0d4212e65edc499a74', // post-164 (craft anti-patterns)'pipeline-teleplay.md': '2ea9974ac3803658b2314db1f5818b77', // post-128 (canonical scene list)'pipeline-comic-script.md': '49af30c05f008b20f6998a0f113f7d87', // post-127 (scene markers)'universe-character-expand.md': '67b6e73ed47f318451a730088b4cff14',diff --git a/scripts/migrations/054-source-agnostic-stage-prompts.js b/scripts/migrations/054-source-agnostic-stage-prompts.jsindex 835011868a..d395a3e683 100644--- a/scripts/migrations/054-source-agnostic-stage-prompts.js+++ b/scripts/migrations/054-source-agnostic-stage-prompts.js@@ -25,7 +25,7 @@ import { makePromptReplaceMigration } from './_lib.js';// Pre-change shipped hashes (the source-slot templates before this change).export const ACCEPTED_OLD_MD5 = {'pipeline-idea-expansion.md': [ '93e9552c6662811e597a97296f3776a4','1f3c5d077a5ef9a4b610335d5e3edd9c', 'b5c47c94ffc74637983c95761ab0c66c', '49a208628290543ba2607a5ed48fdc8c'],- 'pipeline-prose.md': [ '84523d531eeafa60959c65c553b2563f','d1f8e3f1d214725b5aa67f309a81cd7d', 'bef1bc2767b78f585f2bd89f3d615130'],+ 'pipeline-prose.md': [ '84523d531eeafa60959c65c553b2563f','d1f8e3f1d214725b5aa67f309a81cd7d', 'bef1bc2767b78f585f2bd89f3d615130', '25e3d58c2741bd98acd5d08ba70d8a5e'],'pipeline-comic-script.md': [ 'a4303016c34b65e4b0e641fe71252de3','133d200d069c2e8173b7c129eea58f53', 'e530fc76b89cedaef848ad7ec99c934c', 'dea7d497d1cb38e7574f236f4ff8e644', 'e9ee70bf18888492edada6633cd9928a', '7c05ecde539f04c9fa91e87543057204'],'pipeline-teleplay.md': ['1280ef6b1ad68fa44070ca7478ec2a5f', '2568e14beaa574d43f8018a5def51d04', 'afa4215330bf856429d70d7e2f856605'],};@@ -34,7 +34,7 @@ export const ACCEPTED_OLD_MD5 = {// migration installs). Mirror these into setup-data.js's drift table.export const NEW_SHIPPED_MD5 = {'pipeline-idea-expansion.md': 'd6fa86a435f978336661dcabca67258f', // post-127 (scene markers)- 'pipeline-prose.md': '25e3d58c2741bd98acd5d08ba70d8a5e', // post-127 (scene markers)+ 'pipeline-prose.md': '430d38ed2da59e0d4212e65edc499a74', // post-164 (craft anti-patterns)'pipeline-comic-script.md': '49af30c05f008b20f6998a0f113f7d87', // post-127 (scene markers)'pipeline-teleplay.md': '2ea9974ac3803658b2314db1f5818b77', // post-128 (canonical scene list)};diff --git a/scripts/migrations/127-pipeline-scene-markers-prompts.js b/scripts/migrations/127-pipeline-scene-markers-prompts.jsindex 8a6fb3e199..1df018bb34 100644--- a/scripts/migrations/127-pipeline-scene-markers-prompts.js+++ b/scripts/migrations/127-pipeline-scene-markers-prompts.js@@ -24,13 +24,13 @@ import { makePromptReplaceMigration } from './_lib.js';export const ACCEPTED_OLD_MD5 = {'pipeline-idea-expansion.md': ['93e9552c6662811e597a97296f3776a4'], // post-124 (scope-discipline)- 'pipeline-prose.md': ['84523d531eeafa60959c65c553b2563f'], // post-054-fence+ 'pipeline-prose.md': ['84523d531eeafa60959c65c553b2563f', '25e3d58c2741bd98acd5d08ba70d8a5e'], // post-054-fence; post-127/pre-164 (scene markers)'pipeline-comic-script.md': ['a4303016c34b65e4b0e641fe71252de3'], // post-126 (visible text exactness)};export const NEW_SHIPPED_MD5 = {'pipeline-idea-expansion.md': 'd6fa86a435f978336661dcabca67258f', // post-127 (scene markers)- 'pipeline-prose.md': '25e3d58c2741bd98acd5d08ba70d8a5e', // post-127 (scene markers)+ 'pipeline-prose.md': '430d38ed2da59e0d4212e65edc499a74', // post-164 (craft anti-patterns)'pipeline-comic-script.md': '49af30c05f008b20f6998a0f113f7d87', // post-127 (scene markers)};diff --git a/scripts/migrations/164-craft-knowledge-prompt-upgrades.js b/scripts/migrations/164-craft-knowledge-prompt-upgrades.jsnew file mode 100644index 0000000000..4240956b36--- /dev/null+++ b/scripts/migrations/164-craft-knowledge-prompt-upgrades.js@@ -0,0 +1,70 @@+/**+ * CWQE Phase 8 — craft-knowledge prompt upgrades (#2172).+ *+ * Three shipped stage templates gained craft-corpus content:+ *+ * - `pipeline-prose.md` + `writers-room-continue.md` now inject the new shared+ * `{{> craft-anti-patterns }}` partial (24-rule anti-pattern list + Stability+ * Trap countermeasures). The partial file itself is NEW, so setup-data.js+ * copies it into existing installs' `data/prompts/_partials/` on the next+ * boot (missing-file → copy) — no migration needed for the partial. But the+ * two stage files ALREADY exist on existing installs, so setup-data.js's+ * copy-missing pass never rewrites them: this migration adds the `{{>` line.+ *+ * - `pipeline-arc-overview.md` now emits a `foreshadowing` ledger+ * (plant → reinforce → payoff, plant-to-payoff distance ≥ 3 issues) persisted+ * onto `series.arc.foreshadowing` and consumed by the `chekhov.setups-payoffs`+ * editorial check.+ *+ * `scripts/setup-data.js` only copies *missing* prompt files, so existing+ * installs keep their old templates until this migration rewrites them. It's the+ * first hash-driven update for `pipeline-prose.md` and `pipeline-arc-overview.md`+ * since their current shipped hashes (migration-tracked in the drift baseline),+ * and the first EVER for `writers-room-continue.md` — so no earlier migration's+ * MD5 tables need resyncing.+ *+ * Customization-safe: only installs whose copy still hashes to the prior shipped+ * version are auto-updated; customized prompts are left intact and warned about.+ *+ * Strategy: hash-driven prompt-replace via `./_lib.js`. Idempotent.+ */++import { makePromptReplaceMigration } from './_lib.js';++// Pre-change shipped hashes (the current shipped bodies before #2172).+export const ACCEPTED_OLD_MD5 = {+ 'pipeline-prose.md': ['25e3d58c2741bd98acd5d08ba70d8a5e'],+ 'writers-room-continue.md': ['93bfe80543ceca39842201a78b8393fa'],+ 'pipeline-arc-overview.md': ['0a1f6ffa6908522e3690c5e9e53a6ee0'],+};++// Post-change shipped hashes (partial injected / foreshadowing ledger added).+export const NEW_SHIPPED_MD5 = {+ 'pipeline-prose.md': '430d38ed2da59e0d4212e65edc499a74',+ 'writers-room-continue.md': '67663696c97ebaeb23de25f7410cfdd4',+ 'pipeline-arc-overview.md': '612f8b04950e2ff26dd350dd76a062fe',+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'craft-knowledge prompt upgrades',+ customizedHint: (filename) =>+ ` To upgrade it manually, diff:\n` ++ ` data.reference/prompts/stages/${filename}\n` ++ ` against your current:\n` ++ ` data/prompts/stages/${filename}\n` ++ (filename === 'pipeline-arc-overview.md'+ ? ` and add the "Foreshadowing ledger" instruction + the "foreshadowing"\n` ++ ` output-contract array (plant → reinforce → payoff, distance ≥ 3 issues).`+ : ` and add the "{{> craft-anti-patterns }}" partial reference.`),+ skipFooter: (count) =>+ `⚠️ ${count} craft-knowledge prompt(s) could not be auto-updated because\n` ++ ` they were customized. Generation still works, but those prompts will\n` ++ ` miss the anti-pattern rules / Stability Trap countermeasures (prose,\n` ++ ` writers-room) or the foreshadowing ledger (arc overview) until you\n` ++ ` merge them from data.reference/prompts/stages/.`,+});++export { applyMigration };+export default { up };diff --git a/scripts/migrations/164-craft-knowledge-prompt-upgrades.test.js b/scripts/migrations/164-craft-knowledge-prompt-upgrades.test.jsnew file mode 100644index 0000000000..c19b74090c--- /dev/null+++ b/scripts/migrations/164-craft-knowledge-prompt-upgrades.test.js@@ -0,0 +1,14 @@+import { describe } from 'vitest';++import { runPromptMigrationTests } from './_testHelpers.js';+import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './164-craft-knowledge-prompt-upgrades.js';++describe('migration 164 — craft-knowledge prompt upgrades', () => {+ runPromptMigrationTests({+ migration,+ applyMigration,+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ prefix: 'migration-164-',+ });+});diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.jsindex c8a1e8948d..84d3b1c8f3 100644--- a/scripts/setup-data-drift.test.js+++ b/scripts/setup-data-drift.test.js@@ -25,11 +25,12 @@ const migrationsDir = join(dirname(fileURLToPath(import.meta.url)), 'migrations'// that the sweep itself is expected to carry it.const EXPECTED_STAGE_OLD = {'pipeline-idea-expansion.md': ['1ee44cf95851ff8debf18729ebcd40b4', '1f3c5d077a5ef9a4b610335d5e3edd9c', '41facefbc0c0549d456bef9111f95ab9', '49a208628290543ba2607a5ed48fdc8c', '93e9552c6662811e597a97296f3776a4', 'aee25112b2c596f643b17c559b772c22', 'b5c47c94ffc74637983c95761ab0c66c', 'c50f016639d41cd8244f5ff13429f997'],- 'pipeline-prose.md': ['30ac30ec2b9d3e2a9eb869c181732cc6', '84523d531eeafa60959c65c553b2563f', 'bef1bc2767b78f585f2bd89f3d615130', 'bfea5aeeb471aae9749baee765b473a7', 'd1f8e3f1d214725b5aa67f309a81cd7d'],+ 'pipeline-prose.md': ['30ac30ec2b9d3e2a9eb869c181732cc6', '84523d531eeafa60959c65c553b2563f', 'bef1bc2767b78f585f2bd89f3d615130', 'bfea5aeeb471aae9749baee765b473a7', 'd1f8e3f1d214725b5aa67f309a81cd7d', '25e3d58c2741bd98acd5d08ba70d8a5e'],+ 'writers-room-continue.md': ['93bfe80543ceca39842201a78b8393fa'],'pipeline-comic-script.md': ['133d200d069c2e8173b7c129eea58f53', '1e0af305c27d0c80c4b482d2ebcb4a0d', '40e5fdc1a1e68a7419b7dad936366c1a', '7c05ecde539f04c9fa91e87543057204', 'a4303016c34b65e4b0e641fe71252de3', 'beab031951859ca13579cdb9c4dbe769', 'dea7d497d1cb38e7574f236f4ff8e644', 'e530fc76b89cedaef848ad7ec99c934c', 'e9ee70bf18888492edada6633cd9928a'],'pipeline-teleplay.md': ['1280ef6b1ad68fa44070ca7478ec2a5f', '2568e14beaa574d43f8018a5def51d04', '376f779f4687b598f1c92ca4e770fd5a', '3f6fecc25573ed054b47db392250034a', 'afa4215330bf856429d70d7e2f856605'],'pipeline-season-episodes.md': ['6e349ad26bed8a0ccb042571f03f03eb', 'c4928e2a5f833358116b29d2d669888d'],- 'pipeline-arc-overview.md': ['6a3ecab43d1f46b7ef9aab6c69ea0326', 'd34d72b8e49ba303d38607845dd87f1c'],+ 'pipeline-arc-overview.md': ['6a3ecab43d1f46b7ef9aab6c69ea0326', 'd34d72b8e49ba303d38607845dd87f1c', '0a1f6ffa6908522e3690c5e9e53a6ee0'],'pipeline-arc-verify.md': ['52e31abc93e3105176236fcaa5d1575a', 'ff56d8387162017e08d5d0491060ddd6'],'pipeline-volume-verify.md': ['03f3c874cb80e1c98abcf03168fa7a92', 'c6ea28e972ad6e229bafb2d602b4dda3'],'pipeline-arc-resolve.md': ['5b340885c6e8f8afc63424d6b5bc7eb7', '87bc5c01f1a8a97b681727a38b05edc6', '8e348f3d1894382889f9f0ee7d5c6792', 'a8677bbe1eb38f871fb152a5b0fec7c6'],@@ -50,11 +51,12 @@ const EXPECTED_STAGE_OLD = {};const EXPECTED_STAGE_NEW = {'pipeline-idea-expansion.md': 'd6fa86a435f978336661dcabca67258f',- 'pipeline-prose.md': '25e3d58c2741bd98acd5d08ba70d8a5e',+ 'pipeline-prose.md': '430d38ed2da59e0d4212e65edc499a74',+ 'writers-room-continue.md': '67663696c97ebaeb23de25f7410cfdd4','pipeline-comic-script.md': '49af30c05f008b20f6998a0f113f7d87','pipeline-teleplay.md': '2ea9974ac3803658b2314db1f5818b77','pipeline-season-episodes.md': '50c68a29c3ebc275db3095d06bd87100',- 'pipeline-arc-overview.md': '0a1f6ffa6908522e3690c5e9e53a6ee0',+ 'pipeline-arc-overview.md': '612f8b04950e2ff26dd350dd76a062fe','pipeline-arc-verify.md': '36aa70cdfc25d7549573a4d556e7702c','pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940','pipeline-arc-resolve.md': 'cc27b4da1d1a13c35e35d1c2d6183815',diff --git a/server/lib/craftAntiPatternsPartial.test.js b/server/lib/craftAntiPatternsPartial.test.jsnew file mode 100644index 0000000000..e48d7f4697--- /dev/null+++ b/server/lib/craftAntiPatternsPartial.test.js@@ -0,0 +1,49 @@+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'fs';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';++import { expandPartials, listPartialReferences } from './promptPartials.js';+import { applyTemplate } from './promptTemplate.js';++// The craft-anti-patterns partial (#2172) is shipped in data.reference and+// injected into two stage prompts. These pins guard against the partial being+// renamed/deleted (which would make buildPrompt throw at render time) and+// against the injection line being dropped from either stage on a future edit.+const REF = join(dirname(fileURLToPath(import.meta.url)), '../../data.reference/prompts');+const partialsDir = join(REF, '_partials');+const stage = (name) => readFileSync(join(REF, 'stages', name), 'utf-8');++describe('craft-anti-patterns partial (#2172)', () => {+ it('is referenced by both the prose and writers-room-continue stage prompts', () => {+ expect(listPartialReferences(stage('pipeline-prose.md'))).toContain('craft-anti-patterns');+ expect(listPartialReferences(stage('writers-room-continue.md'))).toContain('craft-anti-patterns');+ });++ it('expands through the fs-backed partial engine into the anti-pattern + Stability Trap content', async () => {+ const expanded = await expandPartials(stage('pipeline-prose.md'), { partialsDir });+ // The include marker is gone and the partial body landed inline.+ expect(expanded).not.toContain('{{> craft-anti-patterns }}');+ expect(expanded).toContain('No triadic sensory lists');+ expect(expanded).toContain('Stability Trap countermeasures');+ expect(expanded).toContain('Characters must end TRULY different');+ expect(expanded).toContain('A choice with no real cost is not a real choice');+ });++ it('survives the full buildPrompt pipeline (expandPartials → applyTemplate) with no unresolved partials', async () => {+ // partial → variable pass is exactly what promptService.buildPrompt does.+ for (const name of ['pipeline-prose.md', 'writers-room-continue.md']) {+ const expanded = await expandPartials(stage(name), { partialsDir });+ const rendered = applyTemplate(expanded, {});+ expect(rendered).not.toContain('{{>');+ expect(rendered).toContain('Include at least one genuinely surprising moment');+ }+ });++ it('carries no mustache variables of its own (context-agnostic across both stages)', () => {+ // A pure-prose partial must not introduce {{vars}} that would render+ // differently (or blank) depending on the including stage's context.+ const body = readFileSync(join(partialsDir, 'craft-anti-patterns.md'), 'utf-8');+ expect(body).not.toMatch(/\{\{[^>]/);+ });+});diff --git a/server/lib/editorial/authoredForeshadowing.test.js b/server/lib/editorial/authoredForeshadowing.test.jsnew file mode 100644index 0000000000..f5302a3a21--- /dev/null+++ b/server/lib/editorial/authoredForeshadowing.test.js@@ -0,0 +1,65 @@+import { describe, it, expect } from 'vitest';++import { authoredSetupPayoffSummary, authoredForeshadowingSummary } from './checkInfra.js';++// #2172: the arc-overview-emitted foreshadowing ledger (series.arc.foreshadowing)+// is consumed by the Chekhov check by folding it into the SAME authoredSetups+// block the reader-map hooks/payoffs render into — so the shipped Chekhov prompt+// picks it up through its existing `{{#authoredSetups}}` section with no template+// change. These pins guard that folding contract.+const ledger = [+ { label: 'The locked drawer', plantIssue: 1, reinforceIssues: [3], payoffIssue: 6, note: 'the revolver fires' },+ { label: 'Mara’s limp', plantIssue: 2, payoffIssue: 9 },+];++describe('authoredForeshadowingSummary (#2172)', () => {+ it('returns empty string for a missing/empty ledger', () => {+ expect(authoredForeshadowingSummary(null)).toBe('');+ expect(authoredForeshadowingSummary([])).toBe('');+ expect(authoredForeshadowingSummary('nope')).toBe('');+ });++ it('renders each seed as a plant → reinforce → payoff line', () => {+ const out = authoredForeshadowingSummary(ledger);+ expect(out).toContain('Authored foreshadowing ledger');+ expect(out).toContain('The locked drawer — the revolver fires (plant issue 1 → reinforced issue 3 → payoff issue 6)');+ expect(out).toContain('Mara’s limp (plant issue 2 → payoff issue 9)');+ });++ it('drops entries with no label or note', () => {+ expect(authoredForeshadowingSummary([{ plantIssue: 1, payoffIssue: 5 }])).toBe('');+ });+});++describe('authoredSetupPayoffSummary folds in the foreshadowing ledger (#2172)', () => {+ it('appends the ledger block after the reader-map hooks/payoffs', () => {+ const readerMap = {+ hooks: [{ label: 'Who is the masked figure?', atArcPosition: 1 }],+ payoffs: [{ label: 'The figure is unmasked', atArcPosition: 6 }],+ };+ const out = authoredSetupPayoffSummary(readerMap, ledger);+ expect(out).toContain('Authored hooks');+ expect(out).toContain('Authored payoffs');+ expect(out).toContain('Authored foreshadowing ledger');+ // Ledger block comes last.+ expect(out.indexOf('Authored foreshadowing ledger')).toBeGreaterThan(out.indexOf('Authored hooks'));+ });++ it('renders the ledger even when there is no reader map (ledger-only series)', () => {+ const out = authoredSetupPayoffSummary(null, ledger);+ expect(out).toContain('Authored foreshadowing ledger');+ expect(out).not.toContain('Authored hooks');+ });++ it('is backward-compatible: no ledger arg behaves like before', () => {+ const readerMap = { hooks: [{ label: 'A hook' }], payoffs: [] };+ const out = authoredSetupPayoffSummary(readerMap);+ expect(out).toContain('Authored hooks');+ expect(out).not.toContain('foreshadowing');+ });++ it('returns empty string when nothing is authored on either side', () => {+ expect(authoredSetupPayoffSummary(null, null)).toBe('');+ expect(authoredSetupPayoffSummary({ hooks: [], payoffs: [] }, [])).toBe('');+ });+});diff --git a/server/lib/editorial/checkInfra.js b/server/lib/editorial/checkInfra.jsindex 76f1c6f71f..dbd33d295b 100644--- a/server/lib/editorial/checkInfra.js+++ b/server/lib/editorial/checkInfra.js@@ -221,6 +221,11 @@ export const EDITORIAL_SOURCES = Object.freeze(['series.styleGuide','series.arc.tickingClock','series.arc.readerMap',+ // The authored foreshadowing ledger (#2172): the arc-overview-emitted+ // plant → reinforce → payoff seeds the Chekhov check reconciles its detected+ // setups/payoffs against. Lives on the already-loaded series record (no extra+ // I/O); fingerprinting it stales Chekhov findings when the author edits the ledger.+ 'series.arc.foreshadowing','series.arc.themes',// The author-supplied real-world fact reference the opt-in research.fact-accuracy// check reconciles the prose against (#1588). Lives on the already-loaded series@@ -331,15 +336,51 @@ function renderReaderMapEntryLine(e) {return `- ${text}${pos}`;}-export function authoredSetupPayoffSummary(readerMap) {+// Render one foreshadowing-ledger entry (#2172) to a `- text (plant issue N →+// reinforced issue M → payoff issue P)` line so the Chekhov check reconciles+// its detected plants/payoffs against the author-declared ledger instead of+// inferring every seed from scratch. Returns '' for an entry with no usable+// label/note so callers can `.filter(Boolean)`.+function renderForeshadowingEntryLine(e) {+ const label = typeof e?.label === 'string' ? e.label.trim() : '';+ const note = typeof e?.note === 'string' ? e.note.trim() : '';+ const text = label && note ? `${label} — ${note}` : (label || note);+ if (!text) return '';+ const span = [];+ if (Number.isFinite(e?.plantIssue)) span.push(`plant issue ${e.plantIssue}`);+ if (Array.isArray(e?.reinforceIssues) && e.reinforceIssues.length) {+ span.push(`reinforced issue ${e.reinforceIssues.join(', ')}`);+ }+ if (Number.isFinite(e?.payoffIssue)) span.push(`payoff issue ${e.payoffIssue}`);+ return span.length ? `- ${text} (${span.join(' → ')})` : `- ${text}`;+}++// Build the authored-foreshadowing-ledger block (#2172). Exported for the+// Chekhov check + unit tests; returns '' when nothing is authored so the+// prompt's `{{#authoredSetups}}` section renders nothing.+export function authoredForeshadowingSummary(foreshadowing) {+ const entries = Array.isArray(foreshadowing) ? foreshadowing : [];+ const lines = entries.map(renderForeshadowingEntryLine).filter(Boolean);+ if (!lines.length) return '';+ return `Authored foreshadowing ledger (planted seeds the writer logged — plant → reinforce → payoff):\n${lines.join('\n')}`;+}++// `foreshadowing` (#2172) is the author-declared plant→reinforce→payoff ledger+// on `series.arc.foreshadowing`; it's folded into the SAME authored-setups+// block the reader-map hooks/payoffs render into, so the Chekhov prompt+// consumes it through its existing `{{#authoredSetups}}` section without a+// template change.+export function authoredSetupPayoffSummary(readerMap, foreshadowing) {const hooks = Array.isArray(readerMap?.hooks) ? readerMap.hooks : [];const payoffs = Array.isArray(readerMap?.payoffs) ? readerMap.payoffs : [];const hookLines = hooks.map(renderReaderMapEntryLine).filter(Boolean);const payoffLines = payoffs.map(renderReaderMapEntryLine).filter(Boolean);- if (!hookLines.length && !payoffLines.length) return '';+ const ledgerBlock = authoredForeshadowingSummary(foreshadowing);+ if (!hookLines.length && !payoffLines.length && !ledgerBlock) return '';const parts = [];if (hookLines.length) parts.push(`Authored hooks (questions the writer planted):\n${hookLines.join('\n')}`);if (payoffLines.length) parts.push(`Authored payoffs (resolutions the writer logged):\n${payoffLines.join('\n')}`);+ if (ledgerBlock) parts.push(ledgerBlock);return parts.join('\n\n');}diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.jsindex fd77edf950..2d75d6e741 100644--- a/server/lib/editorial/checkRegistry.test.js+++ b/server/lib/editorial/checkRegistry.test.js@@ -797,12 +797,12 @@ describe('chekhov.setups-payoffs — LLM check (#1299)', () => {...overrides,});- it('is registered as a series-scoped LLM check reading manuscript + reader-map', () => {+ it('is registered as a series-scoped LLM check reading manuscript + reader-map + foreshadowing ledger', () => {const check = getCheck(CHEKHOV);expect(check.kind).toBe('llm');expect(check.scope).toBe('series');expect(check.category).toBe('continuity');- expect(check.sources).toEqual(['manuscript', 'series.arc.readerMap']);+ expect(check.sources).toEqual(['manuscript', 'series.arc.readerMap', 'series.arc.foreshadowing']);expect(check.needsManuscript).toBe(true);});diff --git a/server/lib/editorial/checks/continuity.js b/server/lib/editorial/checks/continuity.jsindex c313260218..8fd949dc5b 100644--- a/server/lib/editorial/checks/continuity.js+++ b/server/lib/editorial/checks/continuity.js@@ -389,7 +389,7 @@ export const continuityChecks = [},{id: 'chekhov.setups-payoffs',- sources: ['manuscript', 'series.arc.readerMap'],+ sources: ['manuscript', 'series.arc.readerMap', 'series.arc.foreshadowing'],label: "Chekhov's guns (setups & payoffs)",description:'Classifies each setup/payoff thread as paired, false-setup (planted, never fired — cut it), orphaned-payoff (fired, never planted — unearned), or distant (paid off so many issues after the setup the reader may have forgotten). Reconciles its detected setups/payoffs against the authored reader-map hooks/payoffs.',@@ -432,8 +432,10 @@ export const continuityChecks = [],gate: (ctx) => (ctx.manuscript || '').trim().length > 0,run: (ctx) => {- // Authored hooks/payoffs are fixed per-call overhead (re-sent on each chunk).- const authoredSetups = authoredSetupPayoffSummary(ctx.series?.arc?.readerMap);+ // Authored hooks/payoffs + the foreshadowing ledger (#2172) are fixed+ // per-call overhead (re-sent on each chunk). The ledger is folded into the+ // same authoredSetups block so the prompt consumes it unchanged.+ const authoredSetups = authoredSetupPayoffSummary(ctx.series?.arc?.readerMap, ctx.series?.arc?.foreshadowing);// 0 disables the distant sub-check; >0 is the issue-gap threshold. Pass a// string so the prompt's `{{#distantGap}}` section renders only when enabled.const distantGap = ctx.config?.distantGap ?? 4;diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex d71e66a456..62e2ccc02a 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -134,7 +134,14 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// overrides and last-writer-wins the loss back onto the newer peer. Bump makes// the older peer reject the ahead-version series transfer instead. Per-category// gate → only series sync pauses with old peers.- pipelineSeries: 9,+ // v10 = `series.arc.foreshadowing` added (#2172) — the arc-overview-emitted+ // plant → reinforce → payoff ledger the Chekhov check consumes. Same additive+ // field INSIDE the series.arc payload as readerMap (v2) / tickingClock (v3): a+ // ≤v9 peer that re-sanitizes a series through its foreshadowing-unaware+ // `sanitizeArc` would silently strip the ledger and last-writer-wins the loss+ // back onto the newer peer. Bump makes the older peer reject the ahead-version+ // series transfer instead. Per-category gate → only series sync pauses with old peers.+ pipelineSeries: 10,// NOT bumped for the manuscript-review sibling doc now bundled on series// pushes/exports (`data/pipeline-series/{id}/manuscript-review.json`).// Unlike `readerMap` (v2), the review is NOT a field inside the seriesdiff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.jsindex c7666d229f..81f591055b 100644--- a/server/lib/schemaVersions.test.js+++ b/server/lib/schemaVersions.test.js@@ -27,11 +27,11 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {it('declares pipeline collection layout versions', () => {// pipelineIssues bumped to 2 when stages.audio.audioMode + cues[] were added.expect(PORTOS_SCHEMA_VERSIONS.pipelineIssues).toBe(2);- // pipelineSeries bumped to 9 when series.severityWeights + blockingSeverities- // were added (#1616) (v2 = readerMap, v3 = tickingClock, v4 = styleGuide,- // v5 = coverImage, v6 = characterArcs, v7 = factCritical + factReference,- // v8 = editorialCheckConfig).- expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(9);+ // pipelineSeries bumped to 10 when series.arc.foreshadowing was added (#2172)+ // (v2 = readerMap, v3 = tickingClock, v4 = styleGuide, v5 = coverImage,+ // v6 = characterArcs, v7 = factCritical + factReference,+ // v8 = editorialCheckConfig, v9 = severityWeights + blockingSeverities).+ expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(10);});it('declares mediaCollections layout version', () => {@@ -45,7 +45,7 @@ describe('buildPortosMeta', () => {expect(meta.portosVersion).toMatch(/^\d+\.\d+\.\d+/);expect(meta.schemaVersions.universes).toBe(7);expect(meta.schemaVersions.pipelineIssues).toBe(2);- expect(meta.schemaVersions.pipelineSeries).toBe(9);+ expect(meta.schemaVersions.pipelineSeries).toBe(10);});it('overrides merge into schemaVersions', async () => {diff --git a/server/lib/storyArc.js b/server/lib/storyArc.jsindex 0f11087fe5..88ba41b81e 100644--- a/server/lib/storyArc.js+++ b/server/lib/storyArc.js@@ -81,6 +81,28 @@ export const TICKING_CLOCK_LIMITS = Object.freeze({});export const TICKING_CLOCK_KINDS = Object.freeze(['deadline', 'event', 'countdown', 'prophecy', 'bomb', 'custom']);+// Foreshadowing ledger — the authored plant → reinforce → payoff record the+// arc-overview stage emits (#2172). Where `readerMap.hooks`/`payoffs` are the+// reader-experience questions/answers and `tickingClock` is a single named+// countdown, the foreshadowing ledger is a LIST of individual seeds: for each,+// the issue it's planted in, the issues that reinforce it, and the issue it+// pays off in. The `chekhov.setups-payoffs` editorial check consumes this+// ledger so it reconciles the prose against author-declared plants instead of+// inferring every setup from scratch. Lives at `series.arc.foreshadowing`.+export const FORESHADOW_LIMITS = Object.freeze({+ LABEL_MAX: 200,+ NOTE_MAX: 1000,+ ENTRIES_MAX: 60,+ REINFORCE_MAX: 20,+ ISSUE_MAX: 9999,+ // The craft target the arc-overview prompt is instructed to hit: a plant and+ // its payoff should sit at least this many issues apart so the reader has+ // forgotten the seed by the time it fires. Exposed so the sanitizer can stamp+ // a `distanceOk` flag (informative, non-destructive — a too-close entry is+ // kept, not dropped) and so the check/tests share one source of truth.+ MIN_PLANT_PAYOFF_DISTANCE: 3,+});+// Per-episode arc roles produced by the season-episodes generator and// persisted on the issue so downstream stages (idea-expansion in particular)// know whether they're writing a pilot vs. midpoint vs. finale episode.@@ -416,6 +438,67 @@ export function renderTickingClock(clock) {return parts.join(' ');}+// Foreshadowing-ledger entry ids are minted as `fs-<uuid>` so the client can+// key list rows and a payoff can be traced back to its seed. Accepts an+// opaque imported id that already matches the shape.+const FS_ID_RE = /^fs-[a-zA-Z0-9-]+$/;+const ensureFsId = (raw) => (isStr(raw) && FS_ID_RE.test(raw) ? raw : `fs-${randomUUID()}`);++// Clean a list of issue-number positions (the reinforce beats): coerce each to+// a non-negative int within range, drop non-finite entries, dedupe, sort+// ascending, and cap. An empty/invalid input yields [].+function cleanReinforceIssues(raw) {+ if (!Array.isArray(raw)) return [];+ const seen = new Set();+ for (const v of raw) {+ const n = optPosition(v, FORESHADOW_LIMITS.ISSUE_MAX);+ if (n != null) seen.add(n);+ if (seen.size >= FORESHADOW_LIMITS.REINFORCE_MAX) break;+ }+ return [...seen].sort((a, b) => a - b);+}++/**+ * Sanitize one foreshadowing-ledger entry. Returns `null` when the entry+ * carries no identifying content (no label/note and no plant/payoff position)+ * so an empty row from the LLM is dropped. A too-close plant→payoff span is+ * NOT dropped — it's kept with `distanceOk: false` so the data stays faithful+ * to what the author/LLM declared and the editorial check can still see it.+ */+export function sanitizeForeshadowingEntry(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const label = trimTo(raw.label, FORESHADOW_LIMITS.LABEL_MAX);+ const note = trimTo(raw.note, FORESHADOW_LIMITS.NOTE_MAX);+ const plantIssue = optPosition(raw.plantIssue, FORESHADOW_LIMITS.ISSUE_MAX);+ const payoffIssue = optPosition(raw.payoffIssue, FORESHADOW_LIMITS.ISSUE_MAX);+ const reinforceIssues = cleanReinforceIssues(raw.reinforceIssues);+ if (!label && !note && plantIssue == null && payoffIssue == null) return null;+ // distanceOk is only meaningful when BOTH ends are pinned; when either is+ // absent we can't judge the span, so report `null` (unknown) rather than a+ // misleading `false`.+ const distanceOk = plantIssue != null && payoffIssue != null+ ? payoffIssue - plantIssue >= FORESHADOW_LIMITS.MIN_PLANT_PAYOFF_DISTANCE+ : null;+ return { id: ensureFsId(raw.id), label, plantIssue, reinforceIssues, payoffIssue, note, distanceOk };+}++/**+ * Sanitize the optional `series.arc.foreshadowing` ledger. Always returns an+ * array (empty when nothing is authored) — mirroring `themes`, which is also a+ * plain always-array field on the arc. Drops malformed/empty entries and caps+ * the list.+ */+export function sanitizeForeshadowing(raw) {+ if (!Array.isArray(raw)) return [];+ const out = [];+ for (const entry of raw) {+ const v = sanitizeForeshadowingEntry(entry);+ if (v) out.push(v);+ if (out.length >= FORESHADOW_LIMITS.ENTRIES_MAX) break;+ }+ return out;+}+/*** Sanitize the optional `series.arc` field. Returns `null` if the input is* empty (no identifying fields) — callers store `null` to mean "no arc yet."@@ -444,9 +527,12 @@ export function sanitizeArc(raw) {// The ticking clock is identifying content as well — an arc whose only// authored decision is "this story has a countdown" must round-trip.const tickingClock = sanitizeTickingClock(raw.tickingClock);- if (!logline && !summary && !protagonistArc && themes.length === 0 && !shape && !readerMap && !tickingClock) return null;+ // The foreshadowing ledger is identifying content too — an arc whose only+ // authored content is a set of planted seeds must survive.+ const foreshadowing = sanitizeForeshadowing(raw.foreshadowing);+ if (!logline && !summary && !protagonistArc && themes.length === 0 && !shape && !readerMap && !tickingClock && foreshadowing.length === 0) return null;const status = ARC_STATUSES.includes(raw.status) ? raw.status : 'draft';- return { logline, summary, protagonistArc, themes, shape, readerMap, tickingClock, status };+ return { logline, summary, protagonistArc, themes, shape, readerMap, tickingClock, foreshadowing, status };}/**diff --git a/server/lib/storyArc.test.js b/server/lib/storyArc.test.jsindex c470d6ee37..2fff42f48e 100644--- a/server/lib/storyArc.test.js+++ b/server/lib/storyArc.test.js@@ -17,6 +17,9 @@ const {buildSeason,sanitizeReaderMap,sanitizeTickingClock,+ sanitizeForeshadowing,+ sanitizeForeshadowingEntry,+ FORESHADOW_LIMITS,renderTickingClock,TICKING_CLOCK_LIMITS,TICKING_CLOCK_KINDS,@@ -54,6 +57,7 @@ describe('storyArc — sanitizeArc', () => {shape: null,readerMap: null,tickingClock: null,+ foreshadowing: [],status: 'draft',});});@@ -546,3 +550,55 @@ describe('storyArc — buildSeason', () => {expect(buildSeason({ logline: 'just a logline' })).toBe(null);});});++describe('storyArc — sanitizeForeshadowing (#2172)', () => {+ it('returns [] for non-array input', () => {+ expect(sanitizeForeshadowing(null)).toEqual([]);+ expect(sanitizeForeshadowing(undefined)).toEqual([]);+ expect(sanitizeForeshadowing('x')).toEqual([]);+ expect(sanitizeForeshadowing({})).toEqual([]);+ });++ it('drops entries with no identifying content', () => {+ expect(sanitizeForeshadowingEntry(null)).toBe(null);+ expect(sanitizeForeshadowingEntry({})).toBe(null);+ expect(sanitizeForeshadowingEntry({ label: ' ' })).toBe(null);+ expect(sanitizeForeshadowing([{}, { note: '' }])).toEqual([]);+ });++ it('mints an fs- id, clamps positions, dedupes+sorts reinforce issues', () => {+ const [entry] = sanitizeForeshadowing([+ { label: 'The locked room', plantIssue: 1, reinforceIssues: [5, 3, 3, -2], payoffIssue: 6, note: 'the room opens' },+ ]);+ expect(entry.id).toMatch(/^fs-/);+ expect(entry.label).toBe('The locked room');+ expect(entry.plantIssue).toBe(1);+ expect(entry.payoffIssue).toBe(6);+ // -2 clamps to 0; duplicate 3 collapses; sorted ascending.+ expect(entry.reinforceIssues).toEqual([0, 3, 5]);+ });++ it('flags distanceOk true when payoff is >= MIN distance after plant, false when too close, null when unknown', () => {+ expect(sanitizeForeshadowingEntry({ label: 'a', plantIssue: 1, payoffIssue: 1 + FORESHADOW_LIMITS.MIN_PLANT_PAYOFF_DISTANCE }).distanceOk).toBe(true);+ expect(sanitizeForeshadowingEntry({ label: 'a', plantIssue: 1, payoffIssue: 2 }).distanceOk).toBe(false);+ // A too-close entry is kept (not dropped), just flagged.+ expect(sanitizeForeshadowingEntry({ label: 'a', plantIssue: 1, payoffIssue: 2 })).not.toBe(null);+ // Unknown span (one end missing) → null, not a misleading false.+ expect(sanitizeForeshadowingEntry({ label: 'a', plantIssue: 1 }).distanceOk).toBe(null);+ });++ it('caps the ledger at ENTRIES_MAX', () => {+ const many = Array.from({ length: FORESHADOW_LIMITS.ENTRIES_MAX + 5 }, (_, i) => ({ label: `seed ${i}`, plantIssue: 1 }));+ expect(sanitizeForeshadowing(many)).toHaveLength(FORESHADOW_LIMITS.ENTRIES_MAX);+ });++ it('sanitizeArc round-trips the foreshadowing ledger and survives on ledger alone', () => {+ const arc = sanitizeArc({ foreshadowing: [{ label: 'Mara’s limp', plantIssue: 2, payoffIssue: 8 }] });+ expect(arc).not.toBe(null);+ expect(arc.foreshadowing).toHaveLength(1);+ expect(arc.foreshadowing[0].label).toBe('Mara’s limp');+ // An arc with no foreshadowing still exposes the field as an array.+ const bare = sanitizeArc({ logline: 'just a logline' });+ expect(bare.foreshadowing).toEqual([]);+ });+});diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex 74cca33170..4fa5eae7df 100644--- a/server/services/dataSync.pipelineUniverse.test.js+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -1053,12 +1053,12 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {const result = await dataSync.applyRemote('pipeline', {series: [{ id: 'ser-1', name: 'Foundry', updatedAt: '2026-05-17T11:00:00Z' }],issues: [],- }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 10, pipelineIssues: 1, mediaCollections: 1 } } });+ }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 11, pipelineIssues: 1, mediaCollections: 1 } } });expect(result.applied).toBe(false);expect(result.blockedBySchema).toBeDefined();// The reported gap is scoped to the relevant category — NOT mis-attributed.expect(result.blockedBySchema.ahead).toEqual([- { category: 'pipelineSeries', senderV: 10, receiverV: 9 },+ { category: 'pipelineSeries', senderV: 11, receiverV: 10 },]);expect(readSeriesState()).toEqual([]); // nothing written});diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.jsindex 0f82cc6c3d..8f3b3de129 100644--- a/server/services/pipeline/arcPlanner/arcCore.js+++ b/server/services/pipeline/arcPlanner/arcCore.js@@ -58,6 +58,10 @@ export async function generateArcOverview(seriesId, options = {}) {// Same for the ticking clock — the overview prompt doesn't author it, so// preserve any existing countdown across a regenerate.tickingClock: series.arc?.tickingClock ?? null,+ // The arc-overview prompt DOES author the foreshadowing ledger (#2172) —+ // take the LLM's if present, else preserve any existing one so a regenerate+ // that omits it doesn't silently wipe the seeds.+ foreshadowing: content?.foreshadowing ?? series.arc?.foreshadowing ?? null,status: 'draft',});const seasons = shapeSeasonOutlines(content?.seasonOutlines);@@ -227,6 +231,8 @@ export async function refineArc(seriesId, feedback, options = {}) {// The arc-refine prompt edits the narrative fields only — preserve the// ticking clock (like readerMap/shape) so a refine never wipes it.tickingClock: arc.tickingClock ?? null,+ // Same for the foreshadowing ledger — a narrative refine must not wipe it.+ foreshadowing: arc.foreshadowing ?? null,status: 'draft',});// sanitizeArc returns null only when every identifying field is empty — which,@@ -390,6 +396,9 @@ export async function resolveVerifyIssues(seriesId, options = {}) {readerMap: series.arc?.readerMap ?? null,// Same for the ticking clock — auto-resolve must not wipe the countdown.tickingClock: series.arc?.tickingClock ?? null,+ // The resolve prompt doesn't author the foreshadowing ledger — take it if+ // present, else preserve any existing one so auto-resolve never wipes it.+ foreshadowing: content?.arc?.foreshadowing ?? series.arc?.foreshadowing ?? null,status: 'draft',});diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.jsindex 6addf0cfa3..9d40748526 100644--- a/server/services/pipeline/editorial/checkRunner.js+++ b/server/services/pipeline/editorial/checkRunner.js@@ -79,6 +79,9 @@ const SOURCE_RESOLVERS = {'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.diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex 9b57d7990d..ffb388cfc1 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -101,7 +101,7 @@ export const LOCKABLE_STAGES = Object.freeze(['arc']);// while preserving locked ones verbatim. Sibling to the binary `locked.arc`// (which freezes everything); the two stack — `locked.arc: true` always wins.export const ARC_LOCKABLE_FIELDS = Object.freeze([- 'logline', 'summary', 'protagonistArc', 'themes', 'shape', 'readerMap', 'tickingClock',+ 'logline', 'summary', 'protagonistArc', 'themes', 'shape', 'readerMap', 'tickingClock', 'foreshadowing',]);// Series Autopilot run marker (full autonomous mode). A thin, persisteddiff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.jsindex 1ab58f043c..33257c3aaf 100644--- a/server/services/sharing/integration.test.js+++ b/server/services/sharing/integration.test.js@@ -2333,7 +2333,7 @@ describe('sharing round-trip', () => {const result = await importer.processManifest(bucket.id, exp.filename);expect(result.skipped).toBe(true);expect(result.reason).toBe('portos-schema-ahead');- expect(result.ahead).toEqual([{ category: 'pipelineSeries', senderV: 99, receiverV: 9 }]);+ expect(result.ahead).toEqual([{ category: 'pipelineSeries', senderV: 99, receiverV: 10 }]);expect(result.producedByVersion).toBe('99.0.0');// Series stayed tombstoned (or absent) — apply was refused.await expect(series.getSeries(s.id)).rejects.toThrow();