Skip to content

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

fix(pipeline): persist episode role and length repairs (#7155)

[._.]/55ce305cfc99
diff --git a/data.reference/prompts/stages/pipeline-arc-resolve.md b/data.reference/prompts/stages/pipeline-arc-resolve.md
index 6a809f7dc3..cd8cb1bf27 100644
--- a/data.reference/prompts/stages/pipeline-arc-resolve.md
+++ b/data.reference/prompts/stages/pipeline-arc-resolve.md
@@ -145,7 +145,7 @@ Hard contract for this response:
entry, or one existing `seasons[]` entry, or one `episodes[]` entry. Not two.
- Within that record, make **exactly one change**: one `{ "find", "replace" }`
replacement in one long field, OR one short field (title / logline / themes /
- `episodeCountTarget` / `number`), OR one existing character-transition or countdown-reminder patch.
+ `episodeCountTarget` / `number` / episode `arcRole`), OR one complete episode length choice, OR one existing character-transition or countdown-reminder patch. A custom length profile and its two targets count as one indivisible length choice.
- Do **not** add a volume. Keep the record's `id` (and any character /
transition id) so the patch lands on the right record — but do not echo any
other field you are not changing.
@@ -182,6 +182,7 @@ Resolve the findings above with edits that cannot re-create any of these. Concre
6. **Unresolved finale hooks / theme drift** — surface the missing theme or arc payoff in the final volume's `synopsis`.
7. **Preserve volume `id`** for every existing volume you edit. Only assign no `id` to brand-new volumes you are adding. Never delete a volume — if a finding could only be resolved by removing one, write that in the `notes` field instead of doing it.
8. **Correct an episode synopsis when the contradiction *originates* in that episode.** Sometimes a finding can't be fixed at the volume level because the wrong content lives in a specific episode's `synopsis` — e.g. an episode stages an event that a later volume reserves as its own "first" occurrence, or a promised through-line silently disappears from the episodes that should carry it. In those cases the only convergent fix is to rewrite the offending episode's `synopsis` so it stops contradicting the rest of the arc. Return those rewrites in the `episodes[]` output array below, keyed by `seasonNumber` + `episodeNumber`. These are early planning synopses (no script has been drafted yet), so editing them is safe and is preferred over papering over the conflict at the volume level. Rules: edit an episode synopsis ONLY when a finding genuinely originates there; make the smallest change that removes the contradiction while preserving the episode's one dramatic purpose; **replace or compact conflicting language instead of appending another caveat, exception, permission, or ledger entry**; never delete an episode (omit it from `episodes[]` to leave it untouched). Target roughly 150–300 words and never exceed 4,000 characters for one episode synopsis. If a finding could only be resolved by removing issues entirely, write that in the `notes` field instead of doing it.
+ **Episode metadata repairs:** A finding about an issue's dramatic role or production size must update the actual episode metadata, not merely describe a different role or size in its synopsis. An `episodes[]` entry can contain only `arcRole` and/or a length choice, with no `synopsis` when the story text is already correct. Allowed `arcRole` values are `pilot`, `complication`, `midpoint`, `b-plot`, `all-is-lost`, `climax`, `finale`. Length presets are `teaser`, `standard`, `extended`, `finale`; for exact targets supply all three together: `"lengthProfile": "custom", "pageTarget": 36, "minutesTarget": 42`. Custom page targets must be integers from 4 to 120 and minute targets integers from 4 to 240. Do not return partial custom choices, invent metadata fields, or echo unchanged fields. Metadata repairs are for unproduced issues: if changing the target would require rebuilding an existing manuscript or page layout, explain the required review in `notes` instead. Existing idea locks apply, and a changed plan clears expanded beats for regeneration.
9. **Return only the records you actually edited, and key every one of them to a finding.** `characterArcs[]`, `seasons[]`, and `episodes[]` are SPARSE patch lists: include a character arc only if you corrected it, a volume only if you changed it, an episode only if you rewrote it, and the `arc` block only if you changed the arc itself. Every entry — including `arc` — carries `resolves: ["f2", ...]`, the ids of the findings that edit closes. An edit that names no finding is discarded by the server, so do not return untouched records "for completeness": that is the single biggest source of NEW contradictions, because every untargeted rewrite is a chance to break something the verification pass had not flagged.
10. **Patch long prose with exact text replacements; never return it wholesale.** Set top-level `patchMode` to `"exact-text-v1"`. For an existing arc, change `summary` only through `summaryEdits[]` and `protagonistArc` only through `protagonistArcEdits[]`. For an existing volume, change `synopsis` only through `synopsisEdits[]` and `endingHook` only through `endingHookEdits[]`. Each edit is `{ "find": "an exact unique excerpt copied verbatim from the current field", "replace": "the complete corrected excerpt" }`. Use the shortest excerpt that is still unique, normally one sentence or clause. The server rejects a missing or repeated `find`, so copy punctuation and whitespace exactly. To insert text, include a nearby unique sentence in both `find` and `replace`; to delete text, use an empty `replace`. Apply no more than 12 replacements per field. Never put a full stored summary, protagonist arc, or synopsis in `find` or `replace`: that recreates the wholesale-rewrite failure this contract prevents. A short one-clause `endingHook` may be matched whole when no smaller unique excerpt exists. Short fields such as title/logline/themes/count may still be returned directly when a finding names them.
11. **Within an edited record, return only the fields that must change.** A character arc patch must repeat its existing `characterId` (or exact `characterName` when it has no ID), then include only changed top-level fields and changed transitions. Every transition patch must repeat its existing `id`; omit untouched transitions. To remove a transition that is itself the contradiction, return its `id` plus `"delete": true`. Omit every untouched key instead of paraphrasing the stored value "for completeness". The server preserves omitted fields and IDs. This field-level sparsity is load-bearing: rewriting an unrelated field can create the next round's contradiction even when the targeted finding was fixed.
@@ -259,6 +260,6 @@ The `seasons[]` array is a SPARSE list of volume patches — include only the vo
The `characterArcs[]` array is a SPARSE list of existing character-arc patches — include only the character and transition fields you actually corrected, preserve every supplied ID, and carry the finding's `resolves` ids on the character-arc entry. Character arcs and transitions you don't list are left exactly as they are. Unmatched/new IDs are discarded rather than minted.
-The `episodes[]` array is a SPARSE list of episode-synopsis corrections — include only the episodes you actually rewrote (per rule 8). Omit the array entirely (or leave it empty) when every finding was resolved at the arc/volume level. Episodes you don't list are left exactly as they are.
+The `episodes[]` array is a SPARSE list of episode planning corrections — include only the episodes whose synopsis, arc role or length choice you actually changed (per rule 8). Omit the array entirely (or leave it empty) when every finding was resolved at the arc/volume level. Episodes you don't list are left exactly as they are.
Omit the `arc` block entirely when the arc itself needed no edit. Within every record you do return, omit fields that do not need to change. Every direct short field and every exact replacement must be complete and leave the resulting persisted field within the limits above. The server keeps the stored value for every field and substring you leave untouched.
diff --git a/scripts/migrations/005-shape-aware-arc-prompts.js b/scripts/migrations/005-shape-aware-arc-prompts.js
index f2903fb826..c5c9092795 100644
--- a/scripts/migrations/005-shape-aware-arc-prompts.js
+++ b/scripts/migrations/005-shape-aware-arc-prompts.js
@@ -55,7 +55,7 @@ export const NEW_SHIPPED_MD5 = {
'pipeline-arc-verify.md': '4b60a322e35b536405d0fbf543580562', // post-276 distinct climax
'pipeline-volume-verify.md': '9c0839d7fe1760c0891464afd4a3b8fd', // post-274 planning economy
'pipeline-season-episodes.md': '7c24df53c097c2525a52bfb766239647', // post-276 distinct climax
- 'pipeline-arc-resolve.md': '122950b9f5ce84708ac1510ef13b1bce', // post-274 planning economy
+ 'pipeline-arc-resolve.md': '3f5ef41212890889811e4509a131c4e9', // post-274 planning economy
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/019-arc-volume-prompts-canon-context.js b/scripts/migrations/019-arc-volume-prompts-canon-context.js
index 2b6c08f7d5..62225b2b68 100644
--- a/scripts/migrations/019-arc-volume-prompts-canon-context.js
+++ b/scripts/migrations/019-arc-volume-prompts-canon-context.js
@@ -64,7 +64,7 @@ export const ACCEPTED_OLD_MD5 = {
export const NEW_SHIPPED_MD5 = {
'pipeline-arc-overview.md': '5ed760caaf3cf88916ec28b220e2f590', // post-250 arc spine checkpoint
'pipeline-arc-verify.md': '4b60a322e35b536405d0fbf543580562', // post-276 distinct climax
- 'pipeline-arc-resolve.md': '122950b9f5ce84708ac1510ef13b1bce', // post-274 planning economy
+ 'pipeline-arc-resolve.md': '3f5ef41212890889811e4509a131c4e9', // post-274 planning economy
'pipeline-volume-verify.md': '9c0839d7fe1760c0891464afd4a3b8fd', // post-274 planning economy
};
diff --git a/scripts/migrations/023-resolve-prompt-episode-anchor.js b/scripts/migrations/023-resolve-prompt-episode-anchor.js
index d89687bbf5..024a854f8e 100644
--- a/scripts/migrations/023-resolve-prompt-episode-anchor.js
+++ b/scripts/migrations/023-resolve-prompt-episode-anchor.js
@@ -39,7 +39,7 @@ export const ACCEPTED_OLD_MD5 = {
// drift-catch test stays green against the live data.reference sample; a fresh
// install at the pre-123 hash still advances cleanly via the accepted-OLD list.
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-resolve.md': '122950b9f5ce84708ac1510ef13b1bce', // post-274 planning economy
+ 'pipeline-arc-resolve.md': '3f5ef41212890889811e4509a131c4e9', // post-274 planning economy
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/123-arc-resolve-episode-corrections.js b/scripts/migrations/123-arc-resolve-episode-corrections.js
index 86d7647d35..c6c87d8521 100644
--- a/scripts/migrations/123-arc-resolve-episode-corrections.js
+++ b/scripts/migrations/123-arc-resolve-episode-corrections.js
@@ -28,7 +28,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-resolve.md': '122950b9f5ce84708ac1510ef13b1bce', // post-274 planning economy
+ 'pipeline-arc-resolve.md': '3f5ef41212890889811e4509a131c4e9', // post-274 planning economy
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/245-arc-resolve-finding-keyed-patches.js b/scripts/migrations/245-arc-resolve-finding-keyed-patches.js
index e3e4eee0f6..0c5e86c22f 100644
--- a/scripts/migrations/245-arc-resolve-finding-keyed-patches.js
+++ b/scripts/migrations/245-arc-resolve-finding-keyed-patches.js
@@ -28,7 +28,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-resolve.md': '122950b9f5ce84708ac1510ef13b1bce', // post-274 planning economy
+ 'pipeline-arc-resolve.md': '3f5ef41212890889811e4509a131c4e9', // post-274 planning economy
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/251-arc-resolve-field-sparsity.js b/scripts/migrations/251-arc-resolve-field-sparsity.js
index 105fc551c5..d6f41b3951 100644
--- a/scripts/migrations/251-arc-resolve-field-sparsity.js
+++ b/scripts/migrations/251-arc-resolve-field-sparsity.js
@@ -12,7 +12,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-resolve.md': '122950b9f5ce84708ac1510ef13b1bce', // post-274 planning economy
+ 'pipeline-arc-resolve.md': '3f5ef41212890889811e4509a131c4e9', // post-274 planning economy
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/252-arc-resolve-avoid-list.js b/scripts/migrations/252-arc-resolve-avoid-list.js
index b0bbd447d7..74dcdad6c3 100644
--- a/scripts/migrations/252-arc-resolve-avoid-list.js
+++ b/scripts/migrations/252-arc-resolve-avoid-list.js
@@ -14,7 +14,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-resolve.md': '122950b9f5ce84708ac1510ef13b1bce', // post-274 planning economy
+ 'pipeline-arc-resolve.md': '3f5ef41212890889811e4509a131c4e9', // post-274 planning economy
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/253-arc-resolve-spine-scope.js b/scripts/migrations/253-arc-resolve-spine-scope.js
index e7f980acbd..9916a2f798 100644
--- a/scripts/migrations/253-arc-resolve-spine-scope.js
+++ b/scripts/migrations/253-arc-resolve-spine-scope.js
@@ -16,7 +16,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-resolve.md': '122950b9f5ce84708ac1510ef13b1bce', // post-274 planning economy
+ 'pipeline-arc-resolve.md': '3f5ef41212890889811e4509a131c4e9', // post-274 planning economy
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/254-arc-resolve-character-arcs.js b/scripts/migrations/254-arc-resolve-character-arcs.js
index 9c4e3a669b..2b0052f844 100644
--- a/scripts/migrations/254-arc-resolve-character-arcs.js
+++ b/scripts/migrations/254-arc-resolve-character-arcs.js
@@ -15,7 +15,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-resolve.md': '122950b9f5ce84708ac1510ef13b1bce',
+ 'pipeline-arc-resolve.md': '3f5ef41212890889811e4509a131c4e9',
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/258-arc-resolve-exact-text-patches.js b/scripts/migrations/258-arc-resolve-exact-text-patches.js
index 58e419d1cc..9b1de9e009 100644
--- a/scripts/migrations/258-arc-resolve-exact-text-patches.js
+++ b/scripts/migrations/258-arc-resolve-exact-text-patches.js
@@ -14,7 +14,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-resolve.md': '122950b9f5ce84708ac1510ef13b1bce',
+ 'pipeline-arc-resolve.md': '3f5ef41212890889811e4509a131c4e9',
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/259-arc-resolve-text-budgets.js b/scripts/migrations/259-arc-resolve-text-budgets.js
index 6fe112c310..6fa547ec02 100644
--- a/scripts/migrations/259-arc-resolve-text-budgets.js
+++ b/scripts/migrations/259-arc-resolve-text-budgets.js
@@ -11,7 +11,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-resolve.md': '122950b9f5ce84708ac1510ef13b1bce',
+ 'pipeline-arc-resolve.md': '3f5ef41212890889811e4509a131c4e9',
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/260-arc-resolve-isolated-repairs.js b/scripts/migrations/260-arc-resolve-isolated-repairs.js
index ada419283d..e4dc284774 100644
--- a/scripts/migrations/260-arc-resolve-isolated-repairs.js
+++ b/scripts/migrations/260-arc-resolve-isolated-repairs.js
@@ -17,7 +17,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-resolve.md': '122950b9f5ce84708ac1510ef13b1bce',
+ 'pipeline-arc-resolve.md': '3f5ef41212890889811e4509a131c4e9',
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/267-arc-resolve-character-arc-budgets.js b/scripts/migrations/267-arc-resolve-character-arc-budgets.js
index d7e3a081a2..520bfbc53e 100644
--- a/scripts/migrations/267-arc-resolve-character-arc-budgets.js
+++ b/scripts/migrations/267-arc-resolve-character-arc-budgets.js
@@ -17,7 +17,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-resolve.md': '122950b9f5ce84708ac1510ef13b1bce',
+ 'pipeline-arc-resolve.md': '3f5ef41212890889811e4509a131c4e9',
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/275-pipeline-planning-economy.js b/scripts/migrations/275-pipeline-planning-economy.js
index 62fadb9642..b682948d7c 100644
--- a/scripts/migrations/275-pipeline-planning-economy.js
+++ b/scripts/migrations/275-pipeline-planning-economy.js
@@ -24,7 +24,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-resolve.md': '122950b9f5ce84708ac1510ef13b1bce',
+ 'pipeline-arc-resolve.md': '3f5ef41212890889811e4509a131c4e9',
'pipeline-arc-verify.md': '4b60a322e35b536405d0fbf543580562',
'pipeline-volume-verify.md': '9c0839d7fe1760c0891464afd4a3b8fd',
};
diff --git a/scripts/migrations/378-arc-countdown-repair.js b/scripts/migrations/378-arc-countdown-repair.js
index bec9a3e600..23c7fc9f81 100644
--- a/scripts/migrations/378-arc-countdown-repair.js
+++ b/scripts/migrations/378-arc-countdown-repair.js
@@ -1,6 +1,6 @@
import { makePromptReplaceMigration } from './_lib.js';
export const ACCEPTED_OLD_MD5 = { 'pipeline-arc-resolve.md': ['638b988c84b3e5599f7a2ce09fa149ce'] };
-export const NEW_SHIPPED_MD5 = { 'pipeline-arc-resolve.md': '122950b9f5ce84708ac1510ef13b1bce' };
+export const NEW_SHIPPED_MD5 = { 'pipeline-arc-resolve.md': '3f5ef41212890889811e4509a131c4e9' };
const { applyMigration, up } = makePromptReplaceMigration({
accepted: ACCEPTED_OLD_MD5, current: NEW_SHIPPED_MD5, label: 'Arc countdown repair',
customizedHint: () => ' Merge the countdown metadata and sparse reminder-ID repair contract from data.reference/prompts/stages/pipeline-arc-resolve.md into your customized prompt.',
diff --git a/scripts/migrations/379-arc-episode-metadata-repair.js b/scripts/migrations/379-arc-episode-metadata-repair.js
new file mode 100644
index 0000000000..905ace3c31
--- /dev/null
+++ b/scripts/migrations/379-arc-episode-metadata-repair.js
@@ -0,0 +1,9 @@
+import { makePromptReplaceMigration } from './_lib.js';
+export const ACCEPTED_OLD_MD5 = { 'pipeline-arc-resolve.md': ['122950b9f5ce84708ac1510ef13b1bce'] };
+export const NEW_SHIPPED_MD5 = { 'pipeline-arc-resolve.md': '3f5ef41212890889811e4509a131c4e9' };
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5, current: NEW_SHIPPED_MD5, label: 'Arc episode metadata repair',
+ customizedHint: () => ' Merge the sparse episode role and length repair contract from data.reference/prompts/stages/pipeline-arc-resolve.md into your customized prompt.',
+});
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/379-arc-episode-metadata-repair.test.js b/scripts/migrations/379-arc-episode-metadata-repair.test.js
new file mode 100644
index 0000000000..cc4bfce28b
--- /dev/null
+++ b/scripts/migrations/379-arc-episode-metadata-repair.test.js
@@ -0,0 +1,6 @@
+import { describe } from 'vitest';
+import { runPromptMigrationTests } from './_testHelpers.js';
+import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './379-arc-episode-metadata-repair.js';
+describe('migration 379 — episode planning metadata repairs', () => {
+ runPromptMigrationTests({ migration, applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5, prefix: 'migration-379-episode-metadata-' });
+});
diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.js
index 44e237d23e..5ca7fac5c6 100644
--- a/scripts/setup-data-drift.test.js
+++ b/scripts/setup-data-drift.test.js
@@ -35,7 +35,7 @@ const EXPECTED_STAGE_OLD = {
'pipeline-arc-verify.md': ['52e31abc93e3105176236fcaa5d1575a', 'ff56d8387162017e08d5d0491060ddd6', '36aa70cdfc25d7549573a4d556e7702c', '83347e7d923580a3062033ab39b3c14b', '68f6956d7e09ebdb3870d8726b1b2a7a', '9f32e91bd33b97d30e1cbb2e697f4fc3', '90712f66ec68061ebed2147044e5baee', 'a397f158fd9c0dca1c8dbe62df253f70'],
'importer-issue-proposal.md': ['a6838832f8289932836db84ee565b870'],
'pipeline-volume-verify.md': ['03f3c874cb80e1c98abcf03168fa7a92', 'c6ea28e972ad6e229bafb2d602b4dda3', '49458d36700cb94e34806d536ffe2940', '3e8a8f00d5faaee9d8e08a49d801b812'],
- 'pipeline-arc-resolve.md': ['0611db539437083621e19bb88b005e8d', '0787128babf3c4c50e2f2cdb60214030', '5b340885c6e8f8afc63424d6b5bc7eb7', '87bc5c01f1a8a97b681727a38b05edc6', '8bb134554c122d1583c479ab3010e53d', '8e348f3d1894382889f9f0ee7d5c6792', '96f73a7e90526d65ef2bb100fb1cd4bf', 'a8677bbe1eb38f871fb152a5b0fec7c6', 'cc27b4da1d1a13c35e35d1c2d6183815', '31eca76b68f40de1b93734fe9bc9f4bb', '17fbb066d7957dc2e345df1795bb0d9d', 'ebd85d3a0b5949f16877c25ca498cce9', '2349bce80e9df8caafa391a6106327b6', 'aa2e463ebe0857859d79aa0c6ccb0256', '638b988c84b3e5599f7a2ce09fa149ce'],
+ 'pipeline-arc-resolve.md': ['122950b9f5ce84708ac1510ef13b1bce', '0611db539437083621e19bb88b005e8d', '0787128babf3c4c50e2f2cdb60214030', '5b340885c6e8f8afc63424d6b5bc7eb7', '87bc5c01f1a8a97b681727a38b05edc6', '8bb134554c122d1583c479ab3010e53d', '8e348f3d1894382889f9f0ee7d5c6792', '96f73a7e90526d65ef2bb100fb1cd4bf', 'a8677bbe1eb38f871fb152a5b0fec7c6', 'cc27b4da1d1a13c35e35d1c2d6183815', '31eca76b68f40de1b93734fe9bc9f4bb', '17fbb066d7957dc2e345df1795bb0d9d', 'ebd85d3a0b5949f16877c25ca498cce9', '2349bce80e9df8caafa391a6106327b6', 'aa2e463ebe0857859d79aa0c6ccb0256', '638b988c84b3e5599f7a2ce09fa149ce'],
'pipeline-script-verify.md': ['ed6c8101644cfe56a100eb6bfe3587f3'],
'pipeline-extract-scenes.md': ['59fa5ee305ce53d91eb15224d8b546d3', 'c51fb208568d0d903eb43b437478b0ba'],
'writers-room-places.md': ['24a33628cc94d80fa5ca60831d973daf', '7f1f80eb63d67a21161994cde115045e'],
@@ -89,7 +89,7 @@ const EXPECTED_STAGE_NEW = {
'pipeline-arc-verify.md': '4b60a322e35b536405d0fbf543580562',
'importer-issue-proposal.md': '9ba2ff965fba61efb85a3568bb530055',
'pipeline-volume-verify.md': '9c0839d7fe1760c0891464afd4a3b8fd',
- 'pipeline-arc-resolve.md': '122950b9f5ce84708ac1510ef13b1bce',
+ 'pipeline-arc-resolve.md': '3f5ef41212890889811e4509a131c4e9',
'pipeline-script-verify.md': '722c62462d05462603cf67ca0ed1dee8',
'pipeline-extract-scenes.md': '9f404b0c4721b23932a6d2dcfc1fba43',
'writers-room-places.md': 'a7f68e51dd6b4421d20f5bd9d855d9b4',
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index 561340b7cc..574b0eae29 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -1625,6 +1625,99 @@ describe('arcPlanner — resolveVerifyIssues', () => {
]);
});
+ it('repairs episode length and role without rewriting its synopsis, then rolls back both rounds', async () => {
+ const s = await setupSeries();
+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'A crew must make a costly choice.' } });
+ const season = await seasonsSvc.createSeason(s.id, { title: 'Volume', episodeCountTarget: 1 });
+ const issue = await issuesSvc.createIssue({ seriesId: s.id, seasonId: season.id, title: 'Turn', arcRole: 'b-plot' });
+ await issuesSvc.updateStage(issue.id, 'idea', { input: 'The unchanged story.', output: 'Original beats.', status: 'ready' });
+ const before = await issuesSvc.getIssue(issue.id);
+ const snapshot = await planner.snapshotArcState(s.id);
+ const findings = [{ severity: 'medium', problem: 'The central turn needs an extended issue.' }];
+ stageRunnerSpy = vi.fn(async () => ({ content: { episodes: [{
+ resolves: ['f1'], seasonNumber: season.number, episodeNumber: before.number,
+ arcRole: before.arcRole, lengthProfile: 'custom', pageTarget: 36, minutesTarget: 42,
+ }] } }));
+
+ const length = await planner.resolveVerifyIssues(s.id, { findings, isolated: true });
+ const extended = await issuesSvc.getIssue(issue.id);
+ expect(length.applied).toBe(true);
+ expect(extended).toMatchObject({ lengthProfile: 'custom', pageTarget: 36, minutesTarget: 42 });
+ expect(extended.stages.idea).toMatchObject({ input: 'The unchanged story.', output: '', status: 'empty' });
+ stageRunnerSpy = vi.fn(async () => ({ content: { episodes: [{
+ resolves: ['f1'], seasonNumber: season.number, episodeNumber: before.number, arcRole: 'complication',
+ }] } }));
+ const role = await planner.resolveVerifyIssues(s.id, { findings, isolated: true });
+ expect((await issuesSvc.getIssue(issue.id)).arcRole).toBe('complication');
+
+ const restored = await planner.restoreArcState(s.id, snapshot, {
+ episodeEdits: [...planner.resolvedEpisodeEdits(length), ...planner.resolvedEpisodeEdits(role)],
+ });
+ expect(restored.episodesRestored).toBe(1);
+ const after = await issuesSvc.getIssue(issue.id);
+ expect(after).toMatchObject({ arcRole: before.arcRole, lengthProfile: before.lengthProfile, pageTarget: before.pageTarget, minutesTarget: before.minutesTarget });
+ expect(after.stages.idea).toMatchObject({ input: 'The unchanged story.', output: 'Original beats.', status: 'ready' });
+ });
+
+ it('keeps a later authored page-count choice when rolling back its own role correction', async () => {
+ const s = await setupSeries();
+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'A crew must make a costly choice.' } });
+ const season = await seasonsSvc.createSeason(s.id, { title: 'Volume', episodeCountTarget: 1 });
+ const issue = await issuesSvc.createIssue({ seriesId: s.id, seasonId: season.id, title: 'Turn', arcRole: 'b-plot' });
+ await issuesSvc.updateStage(issue.id, 'idea', { input: 'Original synopsis.', output: 'Beats for the original length.', status: 'ready' });
+ const snapshot = await planner.snapshotArcState(s.id);
+ stageRunnerSpy = vi.fn(async () => ({ content: { episodes: [{
+ resolves: ['f1'], seasonNumber: season.number, episodeNumber: issue.number,
+ arcRole: 'complication', lengthProfile: 'custom', pageTarget: 36, minutesTarget: 42,
+ }] } }));
+ const repaired = await planner.resolveVerifyIssues(s.id, { findings: [{ severity: 'medium', problem: 'Correct the turn metadata.' }] });
+ await issuesSvc.updateIssue(issue.id, { pageTarget: 48 });
+ await planner.restoreArcState(s.id, snapshot, { episodeEdits: planner.resolvedEpisodeEdits(repaired) });
+ const restored = await issuesSvc.getIssue(issue.id);
+ expect(restored).toMatchObject({ arcRole: 'b-plot', lengthProfile: 'custom', pageTarget: 48, minutesTarget: 42 });
+ expect(restored.stages.idea).toMatchObject({ input: 'Original synopsis.', output: '', status: 'empty' });
+ });
+
+ it.each(['manuscript', 'page layout', 'back-cover image'])('refuses metadata and accompanying synopsis changes beneath an existing %s', async (production) => {
+ const s = await setupSeries();
+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'A crew must make a costly choice.' } });
+ const season = await seasonsSvc.createSeason(s.id, { title: 'Volume', episodeCountTarget: 1 });
+ const issue = await issuesSvc.createIssue({ seriesId: s.id, seasonId: season.id, title: 'Turn' });
+ await issuesSvc.updateStage(issue.id, 'idea', { input: 'Established plan.' });
+ if (production === 'manuscript') await issuesSvc.updateStage(issue.id, 'prose', { output: 'Existing manuscript.', status: 'ready' });
+ else if (production === 'page layout') await issuesSvc.updateStage(issue.id, 'comicPages', { pages: [{ pageNumber: 1, panels: [] }], status: 'ready' });
+ else await issuesSvc.updateStage(issue.id, 'comicPages', { backCover: { proofImage: { filename: 'back-cover.png' } } });
+ const produced = await issuesSvc.getIssue(issue.id);
+ stageRunnerSpy = vi.fn(async () => ({ content: { episodes: [{
+ resolves: ['f1'], seasonNumber: season.number, episodeNumber: issue.number,
+ synopsis: 'Different plan.', lengthProfile: 'extended',
+ }] } }));
+ const result = await planner.resolveVerifyIssues(s.id, { findings: [{ severity: 'medium', problem: 'Needs more space.' }] });
+ expect(result.applied).toBe(false);
+ expect(result.episodesResolved[0].skipped).toBe('existing-production');
+ const after = await issuesSvc.getIssue(issue.id);
+ expect(after.lengthProfile).toBe(issue.lengthProfile);
+ expect(after.stages.idea.input).toBe('Established plan.');
+ expect(after.stages.prose).toEqual(produced.stages.prose);
+ expect(after.stages.comicPages).toEqual(produced.stages.comicPages);
+ expect(planner.resolvedEpisodeEdits(result)).toEqual([]);
+ });
+
+ it('does not persist an unkeyed role change or a malformed custom length', async () => {
+ const s = await setupSeries();
+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'A crew must make a costly choice.' } });
+ const season = await seasonsSvc.createSeason(s.id, { title: 'Volume', episodeCountTarget: 1 });
+ const issue = await issuesSvc.createIssue({ seriesId: s.id, seasonId: season.id, title: 'Turn', arcRole: 'b-plot' });
+ stageRunnerSpy = vi.fn(async () => ({ content: { episodes: [
+ { seasonNumber: season.number, episodeNumber: issue.number, arcRole: 'complication' },
+ { resolves: ['f1'], seasonNumber: season.number, episodeNumber: issue.number, lengthProfile: 'custom', pageTarget: 5000, minutesTarget: 42 },
+ ] } }));
+ const result = await planner.resolveVerifyIssues(s.id, { findings: [{ severity: 'medium', problem: 'Needs more space.' }] });
+ expect(result.applied).toBe(false);
+ expect(await issuesSvc.getIssue(issue.id)).toMatchObject({ arcRole: 'b-plot', lengthProfile: issue.lengthProfile, pageTarget: issue.pageTarget });
+ expect(planner.resolvedEpisodeEdits(result)).toEqual([]);
+ });
+
// The pre-episode arc-spine gate verifies an episode-EMPTY plan (#3789). A
// resolver handed the full lineup answered spine findings with episode
// rewrites the gate never read: they could not close what was flagged, and
diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.js
index d8f03e6836..23b750a969 100644
--- a/server/services/pipeline/arcPlanner/arcCore.js
+++ b/server/services/pipeline/arcPlanner/arcCore.js
@@ -10,7 +10,7 @@
import { runStagedLLM } from '../../stageRunner.js';
import { ServerError } from '../../../lib/errorHandler.js';
import { stripAnsi } from '../../../lib/ansiStrip.js';
-import { ARC_LOCKABLE_FIELDS, getSeries, updateSeries } from '../series.js';
+import { ARC_LOCKABLE_FIELDS, MANUSCRIPT_TYPES, getSeries, updateSeries } from '../series.js';
import { listIssues, listIssuesForSeries, recomputeIssueNumbersForSeries, updateIssue, updateStageWithLatest, updateStagesWithLatest } from '../issues.js';
import { emitRecordUpdated, withReexportSuppressed } from '../../sharing/recordEvents.js';
import { getSeason } from '../seasons.js';
@@ -682,7 +682,7 @@ function countCharacterArcChanges(patch, current) {
* replacement, the ignored spelling of a long prose field) is not one either —
* rejecting on those would fail candidates that were already going to be no-ops.
*/
-export function isolatedCandidateRejection(edits, { exactTextMode = false, series = {}, matchedSeasons } = {}) {
+export function isolatedCandidateRejection(edits, { exactTextMode = false, series = {}, matchedSeasons, issues = [] } = {}) {
const touched = [];
if (edits.arc) {
const changes = countFieldChanges(edits.arc, series.arc || {}, {
@@ -717,7 +717,14 @@ export function isolatedCandidateRejection(edits, { exactTextMode = false, serie
// would drop (no integer episode number, past its cap) is not counted as a
// record this candidate touches.
for (const episode of shapeEpisodeResolutions(edits.episodes)) {
- touched.push({ label: `episode ${episode.episodeNumber}`, changes: 1 });
+ // A custom profile and its two targets are one indivisible length choice.
+ const existing = matchIssueForEpisodeEdit(issues, seasonIdByNumberOf(series), episode);
+ const changes = Number(Boolean(episode.synopsis) && (!existing || episode.synopsis !== existing.stages?.idea?.input))
+ + Number('arcRole' in episode && (!existing || episode.arcRole !== existing.arcRole))
+ + Number('lengthProfile' in episode && (!existing || EPISODE_METADATA_FIELDS.slice(1)
+ .some((field) => Object.hasOwn(episode, field) && episode[field] !== existing[field])));
+ if (!changes) continue;
+ touched.push({ label: `episode ${episode.episodeNumber}`, changes });
}
if (touched.length === 0) return 'it changed nothing this gate would persist';
if (touched.length > 1) {
@@ -733,8 +740,8 @@ export function isolatedCandidateRejection(edits, { exactTextMode = false, serie
// Character arcs are patched in place by existing IDs; episode (issue) records
// are never CREATED or DELETED here, and their drafted scripts are never
-// clobbered — a full-arc round may rewrite an episode's planning synopsis (see
-// `applyEpisodeResolutions`), and nothing else. If a
+// clobbered — a full-arc round may rewrite an episode's planning synopsis or
+// an unproduced issue's role/length (see `applyEpisodeResolutions`). If a
// finding's only actionable resolution would require deleting issues, the LLM
// is told to flag that in the response's `notes` field rather than executing it.
// `options.findings` empty / omitted = re-run verify first and resolve
@@ -855,7 +862,10 @@ export async function resolveVerifyIssues(seriesId, options = {}) {
// the reason. The post-apply verifier and rollback still judge everything that
// DOES get through.
const isolationRejected = isolated
- ? isolatedCandidateRejection(edits, { exactTextMode, series, matchedSeasons: matchedExisting })
+ ? isolatedCandidateRejection(edits, {
+ exactTextMode, series, matchedSeasons: matchedExisting,
+ issues: edits.episodes.length ? await listIssues({ seriesId }) : [],
+ })
: null;
if (isolationRejected) {
console.log(`⚠️ arc-resolve: discarded an isolated repair candidate — ${isolationRejected}`);
@@ -1027,8 +1037,11 @@ export async function resolveVerifyIssues(seriesId, options = {}) {
};
}
+const EPISODE_METADATA_FIELDS = ['arcRole', 'lengthProfile', 'pageTarget', 'minutesTarget'];
+const episodeMetadataOf = (issue) => Object.fromEntries(EPISODE_METADATA_FIELDS.map((field) => [field, issue[field] ?? null]));
+
/**
- * Apply the auto-resolve pass's episode-synopsis corrections to the canonical
+ * Apply the auto-resolve pass's episode planning corrections to the canonical
* issue records. Each correction targets one issue by its series-global episode
* number (with `seasonNumber` as a disambiguating cross-check). Writes the new
* synopsis to the issue's `idea.input` seed. If that issue already has expanded
@@ -1037,8 +1050,11 @@ export async function resolveVerifyIssues(seriesId, options = {}) {
* regenerates them from the corrected synopsis instead of leaving stale beats
* that still encode the contradiction.
*
+ * Role/length changes are limited to unproduced issues and clear expanded beats.
+ * Metadata and beat invalidation share one owning-service write.
* A locked `idea` stage is left untouched (the user froze it) and reported as
- * skipped. Returns `[{ issueId, number, seasonNumber, clearedBeats, skipped, idea }]`
+ * skipped. Returns entries with the written `idea` and/or sparse `metadata`, plus
+ * identity, `clearedBeats`, and an optional `skipped` reason
* for the conductor to surface; never throws — a bad match is dropped, not fatal.
*
* `idea` is the stage AS THIS CALL LEFT IT, and it is what makes the entry a
@@ -1053,7 +1069,7 @@ export async function applyEpisodeResolutions(seriesId, series, episodes) {
const issues = await listIssues({ seriesId });
const seasonIdByNumber = seasonIdByNumberOf(series);
const applied = [];
- for (const edit of episodes) {
+ for (const edit of shapeEpisodeResolutions(episodes)) {
// Season match required when the named season resolves, else series-global
// number; fail-safe to no-match on a numbering-scheme mismatch (see
// matchIssueForEpisodeEdit). A bad match is logged below, never fatal.
@@ -1069,13 +1085,37 @@ export async function applyEpisodeResolutions(seriesId, series, episodes) {
applied.push({ issueId: issue.id, number: issue.number, seasonNumber: edit.seasonNumber, skipped: 'locked' });
continue;
}
- const hadBeats = !!(issue.stages?.idea?.output && issue.stages.idea.output.trim());
- const written = await updateStageWithLatest(issue.id, 'idea', (current) => (
- hadBeats
- ? { input: edit.synopsis, output: '', status: 'empty', errorMessage: '' }
- : { input: edit.synopsis }
- )).catch((err) => {
- console.log(`⚠️ arc-resolve: episode ${edit.episodeNumber} synopsis edit failed: ${err.message}`);
+ const metadata = Object.fromEntries(EPISODE_METADATA_FIELDS
+ .filter((field) => Object.hasOwn(edit, field) && edit[field] !== issue[field])
+ .map((field) => [field, edit[field]]));
+ const metadataChanged = Object.keys(metadata).length > 0;
+ const hasSynopsis = typeof edit.synopsis === 'string' && edit.synopsis.trim().length > 0;
+ if (!metadataChanged && !hasSynopsis) {
+ applied.push({ issueId: issue.id, number: issue.number, seasonNumber: edit.seasonNumber, skipped: 'unchanged' });
+ continue;
+ }
+ // This repair owns the plan, not regeneration of an existing manuscript or
+ // page layout. A length/role change after production needs explicit review.
+ const pages = issue.stages?.comicPages;
+ if (metadataChanged && (MANUSCRIPT_TYPES.some((stage) => {
+ const value = issue.stages?.[stage];
+ return value?.output?.trim() || value?.input?.trim();
+ }) || pages?.pages?.length || ['cover', 'backCover'].some((slot) => pages?.[slot]?.proofImage || pages?.[slot]?.finalImage))) {
+ applied.push({ issueId: issue.id, number: issue.number, seasonNumber: edit.seasonNumber, skipped: 'existing-production' });
+ continue;
+ }
+ const hadBeats = Boolean(issue.stages?.idea?.output?.trim());
+ const ideaPatch = {
+ ...(hasSynopsis ? { input: edit.synopsis } : {}),
+ ...(hadBeats ? { output: '', status: 'empty', errorMessage: '' } : {}),
+ };
+ const writesIdea = Object.keys(ideaPatch).length > 0;
+ // Metadata and any resulting beat invalidation belong to one stored write.
+ const write = metadataChanged
+ ? updateIssue(issue.id, { ...metadata, ...(writesIdea ? { stages: { idea: ideaPatch } } : {}) })
+ : updateStageWithLatest(issue.id, 'idea', () => ideaPatch).then((result) => result.issue);
+ const written = await write.catch((err) => {
+ console.log(`⚠️ arc-resolve: episode ${edit.episodeNumber} planning edit failed: ${err.message}`);
return null;
});
applied.push({
@@ -1083,7 +1123,13 @@ export async function applyEpisodeResolutions(seriesId, series, episodes) {
number: issue.number,
seasonNumber: edit.seasonNumber,
clearedBeats: hadBeats,
- ...(written ? { idea: ideaSnapshotOf(written.stage) } : { skipped: 'write-failed' }),
+ ...(written ? {
+ ...(writesIdea ? { idea: ideaSnapshotOf(written.stages?.idea) } : {}),
+ ...(metadataChanged ? {
+ metadata: Object.fromEntries(Object.keys(metadata).map((field) => [field, written[field]])),
+ metadataGuard: episodeMetadataOf(written),
+ } : {}),
+ } : { skipped: 'write-failed' }),
});
}
if (applied.length) {
@@ -1107,7 +1153,7 @@ const sameIdea = (a, b) => a.input === b.input && a.output === b.output && a.sta
/**
* The episode-synopsis writes ONE resolve pass actually landed, as
- * `[{ issueId, idea }]` — the exact-mutation manifest a rollback needs so it can
+ * `[{ issueId, idea?, metadata?, metadataGuard? }]` — the exact-mutation manifest a rollback needs so it can
* tell its own round's edits from a write that arrived from somewhere else while
* the verification was running. Derived from the applier's own report — an entry
* carries `idea` only when the write went through, never when it was skipped or
@@ -1119,8 +1165,12 @@ const sameIdea = (a, b) => a.input === b.input && a.output === b.output && a.sta
*/
export const resolvedEpisodeEdits = (resolved) => (Array.isArray(resolved?.episodesResolved)
? resolved.episodesResolved
- .filter((entry) => entry?.issueId && entry.idea)
- .map((entry) => ({ issueId: entry.issueId, idea: entry.idea }))
+ .filter((entry) => entry?.issueId && (entry.idea || entry.metadata))
+ .map((entry) => ({
+ issueId: entry.issueId,
+ ...(entry.idea ? { idea: entry.idea } : {}),
+ ...(entry.metadata ? { metadata: entry.metadata, metadataGuard: entry.metadataGuard } : {}),
+ }))
: []);
// Every issue in the series, without per-stage run history: `listIssues` caps at
@@ -1131,7 +1181,7 @@ const listEpisodesForSnapshot = (seriesId) => listIssuesForSeries(seriesId, { wi
/**
* Capture everything ONE auto-resolve round can rewrite — the series arc,
- * per-character arcs, volume records, and each episode's planning synopsis
+ * per-character arcs, volume records, and each episode's planning synopsis and role/length metadata
* (plus which volume it sits under) — so a round that leaves verification WORSE
* can be reverted instead of committed. Read-only; the caller holds the snapshot
* for the duration of the round (see `runArcVerify`'s regression guard).
@@ -1150,6 +1200,7 @@ export async function snapshotArcState(seriesId) {
id: iss.id,
seasonId: iss.seasonId ?? null,
idea: ideaSnapshotOf(iss.stages?.idea),
+ metadata: episodeMetadataOf(iss),
})),
};
}
@@ -1170,8 +1221,8 @@ export async function snapshotArcState(seriesId) {
* A locked `idea` stage IS skipped — the resolve pass never touched it.
*
* `options.episodeEdits` is the round's exact mutation manifest (see
- * `resolvedEpisodeEdits`): pass it and only those episodes' `idea` fields are
- * eligible, and only while the value the resolver wrote is still the one
+ * `resolvedEpisodeEdits`): pass it and only those episodes' recorded idea and
+ * metadata changes are eligible, and only while the value the resolver wrote is still the one
* standing — "differs from the snapshot" was never proof the round owned the
* difference. Two deliberate limits on that:
* - Volume reassignment is never manifest-gated. The volume list is being
@@ -1202,10 +1253,16 @@ export async function restoreArcState(seriesId, snapshot, { episodeEdits = null
const byId = new Map(issues.map((iss) => [iss.id, iss]));
// What the round is on record as having written to each episode, or null when
// the caller kept the pre-manifest "restore every difference" contract.
- const ownedIdea = Array.isArray(episodeEdits)
- ? new Map(episodeEdits.map((e) => [e.issueId, e.idea]))
- : null;
+ const ownedEdits = Array.isArray(episodeEdits) ? new Map() : null;
+ for (const edit of Array.isArray(episodeEdits) ? episodeEdits : []) {
+ const prior = ownedEdits.get(edit.issueId) || {};
+ ownedEdits.set(edit.issueId, {
+ ...prior, ...edit,
+ metadata: { ...prior.metadata, ...edit.metadata },
+ });
+ }
const stageUpdates = [];
+ const metadataUpdates = [];
const reassign = [];
for (const snap of snapshot.episodes) {
const cur = byId.get(snap.id);
@@ -1215,19 +1272,36 @@ export async function restoreArcState(seriesId, snapshot, { episodeEdits = null
if ((cur.seasonId ?? null) !== snap.seasonId) reassign.push(snap);
if (cur.stages?.idea?.locked === true) continue;
const idea = ideaSnapshotOf(cur.stages?.idea);
- if (sameIdea(idea, snap.idea)) continue;
- if (ownedIdea) {
- const written = ownedIdea.get(snap.id);
- // Either the round never wrote this episode, or its write has since been
- // overwritten — in both cases what stands is someone else's, not the
- // regressive candidate this rollback is undoing.
- if (!written || !sameIdea(idea, written)) continue;
+ const owned = ownedEdits?.get(snap.id);
+ let metadataPatch = {};
+ // Legacy snapshots do not own metadata. For current snapshots, restore only
+ // fields this round changed and only while its result still stands. Length
+ // is one choice: a later page-count edit must not have its profile reset.
+ if (snap.metadata) {
+ const lengthFields = EPISODE_METADATA_FIELDS.slice(1);
+ const lengthStillOwned = !ownedEdits || (owned?.metadata && lengthFields.every((field) => {
+ const guard = owned.metadataGuard || owned.metadata;
+ return !Object.hasOwn(guard, field) || (cur[field] ?? null) === guard[field];
+ }));
+ metadataPatch = Object.fromEntries(EPISODE_METADATA_FIELDS.filter((field) => (
+ Object.hasOwn(snap.metadata, field) && (cur[field] ?? null) !== snap.metadata[field]
+ && (!ownedEdits || (Object.hasOwn(owned?.metadata || {}, field)
+ && (cur[field] ?? null) === owned.metadata[field]
+ && (field === 'arcRole' || lengthStillOwned)))
+ )).map((field) => [field, snap.metadata[field]]));
+ if (Object.keys(metadataPatch).length) metadataUpdates.push({ issueId: snap.id, patch: metadataPatch });
+ }
+ if (!sameIdea(idea, snap.idea) && (!ownedEdits || (owned?.idea && sameIdea(idea, owned.idea)))) {
+ const restoredMetadata = { ...episodeMetadataOf(cur), ...metadataPatch };
+ const metadataStillChanged = snap.metadata && EPISODE_METADATA_FIELDS
+ .some((field) => restoredMetadata[field] !== snap.metadata[field]);
+ // A later author choice can keep a new length or role. Restore our old
+ // synopsis, but never resurrect beats sized for the superseded plan.
+ const restoredIdea = metadataStillChanged && snap.idea.output
+ ? { ...snap.idea, output: '', status: 'empty' }
+ : snap.idea;
+ stageUpdates.push({ issueId: snap.id, stageId: 'idea', computeFn: () => ({ ...restoredIdea, errorMessage: '' }) });
}
- stageUpdates.push({
- issueId: snap.id,
- stageId: 'idea',
- computeFn: () => ({ ...snap.idea, errorMessage: '' }),
- });
}
// Same write ordering as `commitSeasonsWithRemap`: seasons first, so a crash
// between writes can't leave an issue pointing at a volume that isn't in
@@ -1242,11 +1316,13 @@ export async function restoreArcState(seriesId, snapshot, { episodeEdits = null
await updateIssue(snap.id, { seasonId: snap.seasonId }, { skipRenumber: true });
}
if (reassign.length) await recomputeIssueNumbersForSeries(seriesId);
+ for (const { issueId, patch } of metadataUpdates) await updateIssue(issueId, patch);
await updateStagesWithLatest(seriesId, stageUpdates);
});
emitRecordUpdated('series', seriesId);
console.log(`↩️ arc-resolve: reverted a regressive round for series ${seriesId.slice(0, 12)} — ${stageUpdates.length} episode synopsis(es), ${reassign.length} reassignment(s)`);
- return { restored: true, episodesRestored: stageUpdates.length, reassignedIssueCount: reassign.length };
+ const episodesRestored = new Set([...stageUpdates, ...metadataUpdates].map((entry) => entry.issueId)).size;
+ return { restored: true, episodesRestored, reassignedIssueCount: reassign.length };
}
// Preserve per-field arc locks. When `currentSeries.locked.arcFields[k]` is
diff --git a/server/services/pipeline/arcPlanner/context.js b/server/services/pipeline/arcPlanner/context.js
index 7b4635b95f..816b73deb9 100644
--- a/server/services/pipeline/arcPlanner/context.js
+++ b/server/services/pipeline/arcPlanner/context.js
@@ -18,7 +18,7 @@ import {
renderCharacterEvolutionsForPrompt,
} from '../../../lib/seriesCharacterArc.js';
import { describeStructure, recommendStructure } from '../../../lib/seasonStructure.js';
-import { computeIssueTargets, DEFAULT_LENGTH_PROFILE, LENGTH_PROFILE_NAMES } from '../../../lib/issueLength.js';
+import { computeIssueTargets, CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX, DEFAULT_LENGTH_PROFILE, LENGTH_PROFILE_NAMES } from '../../../lib/issueLength.js';
import { getUniverse } from '../../universeBuilder.js';
import { getSeriesPlanningCanon, scopeCanonForSeries } from '../seriesCanon.js';
import { CHARACTER_NARRATIVE_ARC_MAX, renderCanonForPrompt, renderCategoriesForPrompt, renderCharacterNarrativeContext, renderCompositesForPrompt, renderEntitiesSummary } from '../../../lib/universePromptRenderers.js';
@@ -593,9 +593,9 @@ export const RESOLVE_EPISODE_MAX = 50;
/**
* Shape the auto-resolve pass's optional `episodes[]` output — a SPARSE list of
- * episode-synopsis corrections the resolver applies when a finding originates at
+ * episode planning corrections the resolver applies when a finding originates at
* the episode level (see pipeline-arc-resolve.md rule 8). Each entry must carry
- * an integer `episodeNumber` and a non-empty `synopsis`; `seasonNumber` is
+ * an integer `episodeNumber` and a synopsis or valid planning metadata; `seasonNumber` is
* optional disambiguation. Malformed entries are dropped so a partial response
* never throws.
*/
@@ -605,7 +605,18 @@ export function shapeEpisodeResolutions(rawEpisodes) {
for (const raw of rawEpisodes) {
const synopsis = typeof raw?.synopsis === 'string' ? raw.synopsis.trim() : '';
const episodeNumber = Number(raw?.episodeNumber);
- if (!synopsis || !Number.isInteger(episodeNumber)) continue;
+ if (!Number.isInteger(episodeNumber)) continue;
+ const metadata = {};
+ if (ARC_ROLES.has(raw?.arcRole)) metadata.arcRole = raw.arcRole;
+ if (SEASON_LENGTH_PRESETS.has(raw?.lengthProfile)) metadata.lengthProfile = raw.lengthProfile;
+ // A custom length is one complete choice. Reject partial/out-of-range
+ // values rather than silently falling back to standard production targets.
+ if (raw?.lengthProfile === 'custom'
+ && Number.isInteger(raw.pageTarget) && raw.pageTarget >= CUSTOM_PAGE_MIN && raw.pageTarget <= CUSTOM_PAGE_MAX
+ && Number.isInteger(raw.minutesTarget) && raw.minutesTarget >= CUSTOM_MINUTE_MIN && raw.minutesTarget <= CUSTOM_MINUTE_MAX) {
+ Object.assign(metadata, { lengthProfile: 'custom', pageTarget: raw.pageTarget, minutesTarget: raw.minutesTarget });
+ }
+ if (!synopsis && !Object.keys(metadata).length) continue;
const seasonNumberRaw = Number(raw?.seasonNumber);
out.push({
seasonNumber: Number.isInteger(seasonNumberRaw) ? seasonNumberRaw : null,
@@ -615,7 +626,8 @@ export function shapeEpisodeResolutions(rawEpisodes) {
// (200k) let a sequence of continuity repairs turn a compact plan into a
// near-manuscript. Boundary-aware trimming avoids manufacturing the
// half-sentence that the next verification round would immediately flag.
- synopsis: trimToClause(synopsis, ARC_LIMITS.EPISODE_SYNOPSIS_MAX),
+ ...(synopsis ? { synopsis: trimToClause(synopsis, ARC_LIMITS.EPISODE_SYNOPSIS_MAX) } : {}),
+ ...metadata,
});
if (out.length >= RESOLVE_EPISODE_MAX) break;
}