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
key arc auto-resolve edits to the findings they close and apply seasons as a sparse patch (#3724)
[._.]/ Adam Eivyc1629099923c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 7d610bae56..b561c6ac72 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -216,6 +216,8 @@- **An arc auto-resolve round that makes the story worse now gets reverted even when the verifier re-words itself.** Autopilot already refuses to keep a repair round that hands back more blocking findings than it was given while leaving its assignment standing — but it decided "still standing" by comparing the verifier's prose to the previous round's, near-verbatim. Verification is an AI pass: it re-phrases the same defect every time it files it, and re-labels where the defect lives when a round renumbers volumes. So the guard read each restatement as a brand-new finding, concluded the round had done its job, and kept the damage — which is how a run could still go from one blocking finding to three to five and then pause on a plan the repair pass had degraded. Two findings are now matched on what they are *about* (the place they name, or the substance they restate) rather than on wording, so a paraphrased repeat is recognized, the round's edits are put back, and the run pauses on the findings you actually had — one verify and one repair round earlier, before either is billed.+- **An arc auto-resolve round now only touches the volumes it was asked to fix.** The repair pass was an unconditional broad rewrite: findings went in as anonymous prose, and the response had to come back carrying the **full** volume lineup — so a round handed a single blocking finding could legitimately re-author every volume and several episode synopses, and any volume it forgot to echo back was deleted. Every one of those untargeted rewrites was a fresh chance to author the contradiction the *next* verification pass files as a brand-new blocker, which is how a run climbed from one finding to three to five without ever fixing anything. Findings are now handed over with stable ids, every proposed edit has to name the finding it closes, and an edit that names none is dropped before it reaches your series. The volume list became a sparse patch: only the volumes actually rewritten come back, everything else is left exactly as it was, and a volume can no longer be deleted by omission — the pass recommends the deletion in its notes and leaves the record alone. Installs on the shipped prompt pick this up automatically; a customized arc-resolve prompt keeps working under the old unkeyed contract (and now says so in the log) until you merge the new instruction in.+## Dependencies- **Two high-severity advisories cleared; all three parts of PortOS now audit clean.** A YAML parsing flaw that lets a crafted document pin a CPU core, and a random-id generator that could spin forever on a zero-length request, were both reachable through libraries PortOS installs. Neither is triggerable by anything PortOS itself does, but both are gone. The YAML one is worth a note for anyone maintaining a fork: the version PortOS had *already* pinned as the safe one is the version this new advisory covers, so a pin that looked current was not — the check that guards these pins now knows the higher floor and will fail a build that drifts back.diff --git a/data.reference/prompts/stages/pipeline-arc-resolve.md b/data.reference/prompts/stages/pipeline-arc-resolve.mdindex 9df1c4c7c6..168702e31b 100644--- a/data.reference/prompts/stages/pipeline-arc-resolve.md+++ b/data.reference/prompts/stages/pipeline-arc-resolve.md@@ -74,7 +74,7 @@ The recommended structure for this issue budget is **{{recommendedStructure}}**## Findings to resolve-The verification pass flagged these problems. Resolve **every** one of them in your output:+The verification pass flagged these problems. Resolve **every** one of them in your output. Each finding carries a `findingId` (`f1`, `f2`, …) — every edit you return must name the finding(s) it closes by that id:```json{{findingsJson}}@@ -88,8 +88,9 @@ The verification pass flagged these problems. Resolve **every** one of them in y4. **Character contradictions** — adjust the offending volume's `synopsis` (or the protagonist arc) so the contradiction disappears. Do not silently delete the contradicting beat — replace it with one that preserves the dramatic intent.5. **Dropped subplots** — add the missing payoff to a later volume's `synopsis` or `endingHook`, OR remove the dangling setup from the earlier volume if the payoff would derail the arc.6. **Unresolved finale hooks / theme drift** — surface the missing theme or arc payoff in the final volume's `synopsis`.-7. **Preserve volume `id`** for every existing volume you keep. Only assign no `id` to brand-new volumes you are adding. If you remove a volume, simply omit it from the response — the server will reconcile child issues separately.+7. **Preserve volume `id`** for every existing volume you edit. Only assign no `id` to brand-new volumes you are adding. Never delete a volume — if a finding could only be resolved by removing one, write that in the `notes` field instead of doing it.8. **Correct an episode synopsis when the contradiction *originates* in that episode.** Sometimes a finding can't be fixed at the volume level because the wrong content lives in a specific episode's `synopsis` — e.g. an episode stages an event that a later volume reserves as its own "first" occurrence, or a promised through-line silently disappears from the episodes that should carry it. In those cases the only convergent fix is to rewrite the offending episode's `synopsis` so it stops contradicting the rest of the arc. Return those rewrites in the `episodes[]` output array below, keyed by `seasonNumber` + `episodeNumber`. These are early planning synopses (no script has been drafted yet), so editing them is safe and is preferred over papering over the conflict at the volume level. Rules: edit an episode synopsis ONLY when a finding genuinely originates there; make the smallest change that removes the contradiction while preserving the episode's dramatic purpose; never delete an episode (omit it from `episodes[]` to leave it untouched). If a finding could only be resolved by removing issues entirely, write that in the `notes` field instead of doing it.+9. **Return only the records you actually edited, and key every one of them to a finding.** `seasons[]` and `episodes[]` are SPARSE patch lists: include a volume only if you rewrote it, an episode only if you rewrote it, and the `arc` block only if you rewrote 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.## Output contract@@ -98,6 +99,7 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c```json{"arc": {+ "resolves": ["f1"],"logline": "string","summary": "string (~500 words, multi-paragraph; escape newlines as \\n)","themes": ["string", "..."],@@ -105,6 +107,7 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c},"seasons": [{+ "resolves": ["f1", "f3"],"id": "sea-... (omit only for brand-new volumes)","number": 1,"title": "string",@@ -117,15 +120,18 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c],"episodes": [{+ "resolves": ["f2"],"seasonNumber": 2,"episodeNumber": 13,"synopsis": "string (the corrected episode synopsis — only for episodes whose own content caused a finding)"}],- "notes": "string (optional — flag any finding you could only partially resolve, and explain why. Empty string if every finding is fully addressed.)"+ "notes": "string (optional — flag any finding you could only partially resolve, and explain why. Empty string if every finding is fully addressed. Also name any volume or issue you believe should be DELETED, since you must not delete one yourself.)"}```-The `seasons[]` array must be the FULL list of volumes you want the series to have after the resolve — not a delta. Any current volume not in the response is treated as removed.+The `seasons[]` array is a SPARSE list of volume rewrites — include only the volumes you actually edited, each carrying its `resolves` ids. Volumes you don't list are left exactly as they are; nothing is deleted by omission. Omit the array entirely (or leave it empty) when no volume needed editing.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.++Omit the `arc` block entirely when the arc itself needed no rewrite. Every field you do include in a record you're editing must be complete — the server keeps the stored value for any field you leave out, but it does not merge two halves of a sentence.diff --git a/scripts/migrations/005-shape-aware-arc-prompts.js b/scripts/migrations/005-shape-aware-arc-prompts.jsindex db9593f792..ee0e3a33f2 100644--- a/scripts/migrations/005-shape-aware-arc-prompts.js+++ b/scripts/migrations/005-shape-aware-arc-prompts.js@@ -40,6 +40,7 @@ export const ACCEPTED_OLD_MD5 = {'50c68a29c3ebc275db3095d06bd87100', // post-005 / pre-172 (structure rules)],'pipeline-arc-resolve.md': [+ 'cc27b4da1d1a13c35e35d1c2d6183815', // post-123 / pre-245 — the episodes[] channel, before edits had to name a finding'87bc5c01f1a8a97b681727a38b05edc6', // pre-005 (original)'a8677bbe1eb38f871fb152a5b0fec7c6', // post-005 / pre-019 — the hash this migration originally produced'8e348f3d1894382889f9f0ee7d5c6792', // post-019 / pre-023@@ -52,7 +53,7 @@ export const NEW_SHIPPED_MD5 = {'pipeline-arc-verify.md': '36aa70cdfc25d7549573a4d556e7702c', // post-019'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940', // post-019'pipeline-season-episodes.md': 'a88e8e78a949b7aaf500d03314e2ea0b', // post-172 (structure rules)- 'pipeline-arc-resolve.md': 'cc27b4da1d1a13c35e35d1c2d6183815', // post-123 (episodes[] correction channel)+ 'pipeline-arc-resolve.md': '8bb134554c122d1583c479ab3010e53d', // post-245 (finding-keyed sparse patches)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/019-arc-volume-prompts-canon-context.js b/scripts/migrations/019-arc-volume-prompts-canon-context.jsindex e43aaeb3b0..10082259f9 100644--- a/scripts/migrations/019-arc-volume-prompts-canon-context.js+++ b/scripts/migrations/019-arc-volume-prompts-canon-context.js@@ -47,6 +47,7 @@ export const ACCEPTED_OLD_MD5 = {'52e31abc93e3105176236fcaa5d1575a', // pre-005 (shape-aware), still in setup-data.js OLD list],'pipeline-arc-resolve.md': [+ 'cc27b4da1d1a13c35e35d1c2d6183815', // post-123 / pre-245 — the episodes[] channel, before edits had to name a finding'5b340885c6e8f8afc63424d6b5bc7eb7', // post-023 / pre-123 — episode-synopsis anchor, before the episodes[] channel'8e348f3d1894382889f9f0ee7d5c6792', // post-019 / pre-023 — the hash this migration originally produced; included so a re-run after a `data/migrations.applied.json` reset can cleanly advance an install at the intermediate state to the post-123 live sample'a8677bbe1eb38f871fb152a5b0fec7c6', // pre-019 (pre-Phase B) shipped@@ -61,7 +62,7 @@ export const ACCEPTED_OLD_MD5 = {export const NEW_SHIPPED_MD5 = {'pipeline-arc-overview.md': '74d6c26548660d85fc345b2099c63b6c', // post-173 (MICE thread nesting)'pipeline-arc-verify.md': '36aa70cdfc25d7549573a4d556e7702c', // post-019- 'pipeline-arc-resolve.md': 'cc27b4da1d1a13c35e35d1c2d6183815', // post-123 (episodes[] correction channel)+ 'pipeline-arc-resolve.md': '8bb134554c122d1583c479ab3010e53d', // post-245 (finding-keyed sparse patches)'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940', // post-019};diff --git a/scripts/migrations/023-resolve-prompt-episode-anchor.js b/scripts/migrations/023-resolve-prompt-episode-anchor.jsindex 2eb729e9a5..2a16b94867 100644--- a/scripts/migrations/023-resolve-prompt-episode-anchor.js+++ b/scripts/migrations/023-resolve-prompt-episode-anchor.js@@ -27,6 +27,7 @@ import { makePromptReplaceMigration } from './_lib.js';// maintaining local copies.export const ACCEPTED_OLD_MD5 = {'pipeline-arc-resolve.md': [+ 'cc27b4da1d1a13c35e35d1c2d6183815', // post-123 / pre-245 — the episodes[] channel, before edits had to name a finding'5b340885c6e8f8afc63424d6b5bc7eb7', // post-023 / pre-123 — episode-synopsis anchor, the hash this migration originally produced'8e348f3d1894382889f9f0ee7d5c6792', // post-019 (worldCanonText) shipped — current pre-023'a8677bbe1eb38f871fb152a5b0fec7c6', // pre-019 (pre-canon), still in setup-data.js OLD list@@ -39,7 +40,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': 'cc27b4da1d1a13c35e35d1c2d6183815',+ 'pipeline-arc-resolve.md': '8bb134554c122d1583c479ab3010e53d', // post-245 (finding-keyed sparse patches)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/123-arc-resolve-episode-corrections.js b/scripts/migrations/123-arc-resolve-episode-corrections.jsindex 84d7208373..fca1df222c 100644--- a/scripts/migrations/123-arc-resolve-episode-corrections.js+++ b/scripts/migrations/123-arc-resolve-episode-corrections.js@@ -21,12 +21,13 @@ import { makePromptReplaceMigration } from './_lib.js';export const ACCEPTED_OLD_MD5 = {'pipeline-arc-resolve.md': [+ 'cc27b4da1d1a13c35e35d1c2d6183815', // post-123 / pre-245 — the episodes[] channel, before edits had to name a finding'5b340885c6e8f8afc63424d6b5bc7eb7', // pre-123 (episodes forbidden)],};export const NEW_SHIPPED_MD5 = {- 'pipeline-arc-resolve.md': 'cc27b4da1d1a13c35e35d1c2d6183815', // post-123 (episodes[] channel)+ 'pipeline-arc-resolve.md': '8bb134554c122d1583c479ab3010e53d', // post-245 (finding-keyed sparse patches)};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.jsnew file mode 100644index 0000000000..24d3614aeb--- /dev/null+++ b/scripts/migrations/245-arc-resolve-finding-keyed-patches.js@@ -0,0 +1,52 @@+/**+ * Update the `pipeline-arc-resolve` stage prompt to emit finding-keyed, sparse+ * patches instead of a full arc/volume rewrite (#3724).+ *+ * The resolve pass used to be an unconditional broad rewrite: `seasons[]` had+ * to be "the FULL list of volumes you want the series to have after the+ * resolve", and nothing tied a proposed edit to the finding it was supposed to+ * close. A round handed ONE blocking finding could legitimately rewrite every+ * volume, and each untargeted rewrite was a fresh chance to author the+ * contradiction the next verify files as a NEW blocker — the shape behind the+ * 1 → 3 → 5 non-convergence on 2026-08-09.+ *+ * The new prompt stamps each finding with a stable `findingId` (`f1`…`fN`),+ * requires every entry in `arc` / `seasons[]` / `episodes[]` to name the+ * findings it closes via `resolves[]`, and turns `seasons[]` into a SPARSE+ * patch list — a volume the resolver leaves out is untouched rather than+ * deleted. `resolveVerifyIssues` drops any edit that names no input finding.+ *+ * Strategy: hash-driven prompt-replace via `./_lib.js`. Idempotent.+ */++import { makePromptReplaceMigration } from './_lib.js';++export const ACCEPTED_OLD_MD5 = {+ 'pipeline-arc-resolve.md': [+ 'cc27b4da1d1a13c35e35d1c2d6183815', // pre-245 (post-123 episodes[] channel)+ ],+};++export const NEW_SHIPPED_MD5 = {+ 'pipeline-arc-resolve.md': '8bb134554c122d1583c479ab3010e53d', // post-245 (finding-keyed sparse patches)+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'arc-resolve stage prompt',+ customizedHint: (filename) =>+ ` To key resolve edits to findings manually, diff:\n` ++ ` data.reference/prompts/stages/${filename}\n` ++ ` against your current:\n` ++ ` data/prompts/stages/${filename}\n` ++ ` and merge instruction 9 + the resolves[] fields in the output contract.`,+ skipFooter: (count) =>+ `⚠️ ${count} prompt(s) could not be auto-updated because they were customized.\n` ++ ` Arc auto-resolve will keep working, but until you merge the resolves[]\n` ++ ` contract its edits stay unkeyed — every round can still rewrite volumes\n` ++ ` no finding asked it to touch.`,+});++export { applyMigration };+export default { up };diff --git a/scripts/migrations/245-arc-resolve-finding-keyed-patches.test.js b/scripts/migrations/245-arc-resolve-finding-keyed-patches.test.jsnew file mode 100644index 0000000000..c853b2789b--- /dev/null+++ b/scripts/migrations/245-arc-resolve-finding-keyed-patches.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 './245-arc-resolve-finding-keyed-patches.js';++describe('migration 245 - arc-resolve finding-keyed sparse patches', () => {+ runPromptMigrationTests({+ migration,+ applyMigration,+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ prefix: 'migration-245-',+ });+});diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.jsindex e3ea9c4108..bcca2b6b6a 100644--- a/scripts/setup-data-drift.test.js+++ b/scripts/setup-data-drift.test.js@@ -33,7 +33,7 @@ const EXPECTED_STAGE_OLD = {'pipeline-arc-overview.md': ['6a3ecab43d1f46b7ef9aab6c69ea0326', 'd34d72b8e49ba303d38607845dd87f1c', '0a1f6ffa6908522e3690c5e9e53a6ee0', '612f8b04950e2ff26dd350dd76a062fe'],'pipeline-arc-verify.md': ['52e31abc93e3105176236fcaa5d1575a', 'ff56d8387162017e08d5d0491060ddd6'],'pipeline-volume-verify.md': ['03f3c874cb80e1c98abcf03168fa7a92', 'c6ea28e972ad6e229bafb2d602b4dda3'],- 'pipeline-arc-resolve.md': ['5b340885c6e8f8afc63424d6b5bc7eb7', '87bc5c01f1a8a97b681727a38b05edc6', '8e348f3d1894382889f9f0ee7d5c6792', 'a8677bbe1eb38f871fb152a5b0fec7c6'],+ 'pipeline-arc-resolve.md': ['5b340885c6e8f8afc63424d6b5bc7eb7', '87bc5c01f1a8a97b681727a38b05edc6', '8e348f3d1894382889f9f0ee7d5c6792', 'a8677bbe1eb38f871fb152a5b0fec7c6', 'cc27b4da1d1a13c35e35d1c2d6183815'],'pipeline-script-verify.md': ['ed6c8101644cfe56a100eb6bfe3587f3'],'pipeline-extract-scenes.md': ['59fa5ee305ce53d91eb15224d8b546d3', 'c51fb208568d0d903eb43b437478b0ba'],'writers-room-places.md': ['24a33628cc94d80fa5ca60831d973daf', '7f1f80eb63d67a21161994cde115045e'],@@ -63,7 +63,7 @@ const EXPECTED_STAGE_NEW = {'pipeline-arc-overview.md': '74d6c26548660d85fc345b2099c63b6c','pipeline-arc-verify.md': '36aa70cdfc25d7549573a4d556e7702c','pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940',- 'pipeline-arc-resolve.md': 'cc27b4da1d1a13c35e35d1c2d6183815',+ 'pipeline-arc-resolve.md': '8bb134554c122d1583c479ab3010e53d','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.jsindex 6a9770558a..1c3268414e 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -825,28 +825,138 @@ describe('arcPlanner — resolveVerifyIssues', () => {expect((await issuesSvc.getIssue(ep.id)).seasonId).toBe(v1.id);});- it('drops orphans to null seasonId when no replacement can be matched', async () => {+ it('treats an empty seasons[] as a no-op, not a volume wipe (#3724 sparse patch)', async () => {+ // `seasons[]` is a SPARSE patch list: a resolve round that edits nothing at+ // the volume level leaves the lineup — and every episode under it — alone.+ // Before #3724 this same response deleted the only volume and dropped its+ // issue into the ungrouped bucket.const s = await setupSeries();await seriesSvc.updateSeries(s.id, { arc: { logline: 'L' } });const oldS = await seasonsSvc.createSeason(s.id, { title: 'Only Season', episodeCountTarget: 3 });const i1 = await issuesSvc.createIssue({ seriesId: s.id, seasonId: oldS.id, title: 'Orphan' });- // LLM returns zero seasons — nothing to remap to, issue should go ungrouped.stageRunnerSpy = vi.fn(async () => ({content: {- arc: { logline: 'L2', summary: 'S', themes: [], protagonistArc: '' },+ arc: { resolves: ['f1'], logline: 'L2', summary: 'S', themes: [], protagonistArc: '' },seasons: [],- notes: 'collapsed',+ notes: 'recommend collapsing Only Season — not doing it here',},runId: 'r', providerId: 'p', model: 'm',}));- await planner.resolveVerifyIssues(s.id, {+ const out = await planner.resolveVerifyIssues(s.id, {findings: [{ severity: 'medium', problem: 'X', suggestion: 'Y' }],});- const finalI1 = await issuesSvc.getIssue(i1.id);- expect(finalI1.seasonId).toBeNull();+ expect(out.series.arc.logline).toBe('L2'); // the targeted arc edit still lands+ expect(out.series.seasons.map((x) => x.id)).toEqual([oldS.id]);+ expect((await issuesSvc.getIssue(i1.id)).seasonId).toBe(oldS.id);+ });++ it('leaves volumes the response omits exactly as they are', async () => {+ const s = await setupSeries();+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L' } });+ const v1 = await seasonsSvc.createSeason(s.id, { number: 1, title: 'Vol 1', synopsis: 'v1 original', episodeCountTarget: 3 });+ const v2 = await seasonsSvc.createSeason(s.id, { number: 2, title: 'Vol 2', synopsis: 'v2 original', episodeCountTarget: 3 });++ stageRunnerSpy = vi.fn(async () => ({+ content: {+ arc: { resolves: ['f1'], logline: 'L2', summary: 'S', themes: [], protagonistArc: '' },+ // Only volume 2 was edited — volume 1 isn't in the response at all.+ seasons: [{ resolves: ['f1'], id: v2.id, number: 2, title: 'Vol 2', synopsis: 'v2 rewritten' }],+ notes: '',+ },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ const out = await planner.resolveVerifyIssues(s.id, {+ findings: [{ severity: 'high', problem: 'volume 2 drops the mentor', suggestion: 'pay it off' }],+ });++ expect(out.series.seasons.map((x) => x.id)).toEqual([v1.id, v2.id]);+ expect(out.series.seasons[0].synopsis).toBe('v1 original'); // untouched+ expect(out.series.seasons[1].synopsis).toBe('v2 rewritten');+ });++ it('drops arc / volume / episode edits that name no input finding', async () => {+ const s = await setupSeries();+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L', summary: 'original summary' } });+ const v1 = await seasonsSvc.createSeason(s.id, { number: 1, title: 'Vol 1', synopsis: 'v1 original', episodeCountTarget: 2 });+ const v2 = await seasonsSvc.createSeason(s.id, { number: 2, title: 'Vol 2', synopsis: 'v2 original', episodeCountTarget: 2 });+ const issue = await issuesSvc.createIssue({ seriesId: s.id, seasonId: v1.id, title: 'Ep' });+ await issuesSvc.updateStage(issue.id, 'idea', { input: 'ep original', status: 'empty' });+ const fresh = await issuesSvc.getIssue(issue.id);++ stageRunnerSpy = vi.fn(async () => ({+ content: {+ // Untargeted arc rewrite — dropped. `resolves` naming an id the round+ // never handed out counts as naming nothing.+ arc: { resolves: ['f9'], logline: 'HIJACKED', summary: 'HIJACKED', themes: [], protagonistArc: '' },+ seasons: [+ { resolves: ['f1'], id: v1.id, number: 1, title: 'Vol 1', synopsis: 'v1 rewritten' },+ { resolves: [], id: v2.id, number: 2, title: 'Vol 2', synopsis: 'v2 collateral rewrite' },+ ],+ episodes: [{ seasonNumber: 1, episodeNumber: fresh.number, synopsis: 'ep collateral rewrite' }],+ notes: '',+ },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ const out = await planner.resolveVerifyIssues(s.id, {+ findings: [{ severity: 'high', problem: 'volume 1 stages the eclipse twice', suggestion: 'fix' }],+ });++ expect(out.series.arc.logline).toBe('L');+ expect(out.series.arc.summary).toBe('original summary');+ expect(out.series.seasons[0].synopsis).toBe('v1 rewritten'); // the one targeted edit lands+ expect(out.series.seasons[1].synopsis).toBe('v2 original');+ expect(out.episodesResolved).toEqual([]);+ expect((await issuesSvc.getIssue(issue.id)).stages.idea.input).toBe('ep original');+ });++ it('applies an unkeyed response as a legacy patch (install still on the pre-#3724 prompt)', async () => {+ // A customized `pipeline-arc-resolve.md` never gets migration 245, so its+ // model can't know about `resolves`. Dropping everything would silently turn+ // auto-resolve into a round-burning no-op — those responses apply unkeyed,+ // still under the safer sparse-patch semantics.+ const s = await setupSeries();+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L' } });+ const v1 = await seasonsSvc.createSeason(s.id, { number: 1, title: 'Vol 1', synopsis: 'v1 original', episodeCountTarget: 2 });++ stageRunnerSpy = vi.fn(async () => ({+ content: {+ arc: { logline: 'L2', summary: 'S', themes: [], protagonistArc: '' },+ seasons: [{ id: v1.id, number: 1, title: 'Vol 1', synopsis: 'v1 rewritten' }],+ notes: '',+ },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ const out = await planner.resolveVerifyIssues(s.id, {+ findings: [{ severity: 'high', problem: 'X', suggestion: 'Y' }],+ });++ expect(out.series.arc.logline).toBe('L2');+ expect(out.series.seasons[0].synopsis).toBe('v1 rewritten');+ });++ it('renders findings into the prompt stamped with stable findingIds', async () => {+ const s = await setupSeries();+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L' } });+ stageRunnerSpy = vi.fn(async () => ({+ content: { arc: { resolves: ['f2'], logline: 'L2', summary: 'S' }, seasons: [], notes: '' },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ await planner.resolveVerifyIssues(s.id, {+ findings: [+ { severity: 'high', problem: 'first defect', suggestion: '' },+ { severity: 'high', problem: 'second defect', suggestion: '' },+ ],+ });++ const { findingsJson } = stageRunnerSpy.mock.calls[0][1];+ expect(JSON.parse(findingsJson).map((f) => f.findingId)).toEqual(['f1', 'f2']);});it('preserves series.arc.readerMap when the resolve LLM does not author one', async () => {@@ -1032,6 +1142,54 @@ describe('arcPlanner — resolveVerifyIssues', () => {});});+describe('selectFindingKeyedEdits (pure resolve-edit filter, #3724)', () => {+ const findings = [{ problem: 'a' }, { problem: 'b' }];+ const select = (content) => planner.selectFindingKeyedEdits(content, findings);++ it('keeps edits naming an input finding and drops the rest', () => {+ const out = select({+ arc: { resolves: ['f2'], logline: 'x' },+ seasons: [{ resolves: ['f1'] }, { resolves: ['f7'] }, { resolves: [] }],+ episodes: [{ resolves: ['f1'] }, {}],+ });+ expect(out.legacy).toBe(false);+ expect(out.arc?.logline).toBe('x');+ expect(out.arcDropped).toBe(false);+ expect(out.seasons).toHaveLength(1);+ expect(out.seasonsDropped).toBe(2);+ expect(out.episodes).toHaveLength(1);+ expect(out.episodesDropped).toBe(1);+ });++ it('normalizes ids (case + whitespace) and ignores non-string entries', () => {+ const out = select({ seasons: [{ resolves: [' F1 ', 42, null, 'f1'] }] });+ expect(out.seasons).toHaveLength(1);+ });++ it('drops an untargeted arc block while keeping the volumes that are targeted', () => {+ const out = select({ arc: { resolves: [] }, seasons: [{ resolves: ['f1'] }] });+ expect(out.arc).toBeNull();+ expect(out.arcDropped).toBe(true);+ expect(out.seasons).toHaveLength(1);+ });++ it('falls back to legacy (apply-all) only when NOTHING in the response declares resolves', () => {+ const legacy = select({ arc: { logline: 'x' }, seasons: [{ id: 's1' }], episodes: [{ synopsis: 'y' }] });+ expect(legacy).toMatchObject({ legacy: true, arcDropped: false, seasonsDropped: 0, episodesDropped: 0 });+ expect(legacy.arc?.logline).toBe('x');+ // One keyed entry proves the model is on the new contract — the unkeyed+ // siblings in the SAME response are then genuine drops, not legacy.+ expect(select({ seasons: [{ resolves: ['f1'] }, { id: 's2' }] }))+ .toMatchObject({ legacy: false, seasonsDropped: 1 });+ });++ it('tolerates a missing/garbage response', () => {+ expect(select(null)).toMatchObject({ legacy: true, arc: null, seasons: [], episodes: [] });+ expect(select({ arc: 'not an object', seasons: 'nope', episodes: [null, 3] }))+ .toMatchObject({ arc: null, seasons: [], episodes: [] });+ });+});+describe('arcPlanner — snapshotArcState / restoreArcState (resolve-round rollback)', () => {beforeEach(() => {fileStore.clear();diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.jsindex 63a2ff1df7..201fcc3d2c 100644--- a/server/services/pipeline/arcPlanner/arcCore.js+++ b/server/services/pipeline/arcPlanner/arcCore.js@@ -16,7 +16,7 @@ import { emitRecordUpdated, withReexportSuppressed } from '../../sharing/recordEimport { getSeason } from '../seasons.js';import { READER_MAP_BEAT_KINDS, buildSeason, cleanThemes, renderArcShapeGuidance, renderArcShapePositionSummary, sanitizeArc, sanitizeReaderMap, sanitizeSeason, sanitizeSeasonList } from '../../../lib/storyArc.js';import { runPromptRefineRaw, trimChanges } from '../refineHelpers.js';-import { ERR_VALIDATION, SHAPE_GUIDANCE_NONE, appendTickingClock, buildArcBaseContext, buildArcOverviewContext, buildNeighborVolumes, buildReaderMapContext, buildResolveContext, buildVerifyContext, compareIssuesByPosition, makeErr, matchIssueForEpisodeEdit, renderVolumeIssue, resolveWorldContext, seasonIdByNumberOf, shapeEpisodeResolutions, shapeFindings, shapeSeasonOutlines, shapeVerifyIssues } from './context.js';+import { ERR_VALIDATION, SHAPE_GUIDANCE_NONE, appendTickingClock, buildArcBaseContext, buildArcOverviewContext, buildNeighborVolumes, buildReaderMapContext, buildResolveContext, buildVerifyContext, compareIssuesByPosition, findingIdSet, makeErr, matchIssueForEpisodeEdit, matchResolvedFindings, renderVolumeIssue, resolveWorldContext, seasonIdByNumberOf, shapeEpisodeResolutions, shapeFindings, shapeSeasonOutlines, shapeVerifyIssues } from './context.js';export async function generateArcOverview(seriesId, options = {}) {const series = await getSeries(seriesId);@@ -347,6 +347,47 @@ export async function verifyVolume(seriesId, seasonId, options = {}) {return { issues, raw: content, runId, providerId, model, seasonId };}+/**+ * Split one auto-resolve response into the edits that actually name a finding+ * the round was handed, and the ones to drop (#3724). Pure.+ *+ * Every entry in `arc` / `seasons[]` / `episodes[]` has to carry+ * `resolves: ["f2", …]` naming at least one input finding — an edit that names+ * none can't be closing anything, so applying it is all blast radius and no+ * benefit. Returns `{ legacy, arc, arcDropped, seasons, seasonsDropped,+ * episodes, episodesDropped }`.+ *+ * `legacy` is the escape hatch for an install whose `pipeline-arc-resolve.md`+ * was customized before #3724 and therefore never got the migration: when NOT+ * ONE entry in the whole response declares a `resolves` array, the model is+ * plainly running the old contract, and dropping everything would silently turn+ * auto-resolve into a no-op that burns a round per pass. Those responses are+ * applied unkeyed (still as a sparse patch, which is strictly safer than the+ * old full-list rewrite) and logged. A response that keys SOME of its edits is+ * on the new contract, so its unkeyed entries are genuine drops.+ */+export function selectFindingKeyedEdits(content, findings) {+ const validIds = findingIdSet(findings);+ const isEdit = (e) => !!e && typeof e === 'object';+ const arcEdit = isEdit(content?.arc) ? content.arc : null;+ const seasonsRaw = (Array.isArray(content?.seasons) ? content.seasons : []).filter(isEdit);+ const episodesRaw = (Array.isArray(content?.episodes) ? content.episodes : []).filter(isEdit);+ const legacy = ![arcEdit, ...seasonsRaw, ...episodesRaw]+ .some((e) => e && matchResolvedFindings(e, validIds).declared);+ const targeted = (raw) => legacy || matchResolvedFindings(raw, validIds).matched.length > 0;+ const seasons = seasonsRaw.filter(targeted);+ const episodes = episodesRaw.filter(targeted);+ return {+ legacy,+ arc: arcEdit && targeted(arcEdit) ? arcEdit : null,+ arcDropped: !!arcEdit && !targeted(arcEdit),+ seasons,+ seasonsDropped: seasonsRaw.length - seasons.length,+ episodes,+ episodesDropped: episodesRaw.length - episodes.length,+ };+}+// Per-episode (issue) records are NOT touched — those are user-owned scripts// and shouldn't get clobbered by a structural fix. If a finding's only// actionable resolution would require deleting issues, the LLM is told to@@ -399,12 +440,27 @@ export async function resolveVerifyIssues(seriesId, options = {}) {},);+ // Keep only the edits that name a finding this round was handed (#3724). An+ // untargeted rewrite is pure blast radius: it can't close anything, and every+ // volume it touches is a chance to author the contradiction the next verify+ // files as a brand-new blocker.+ const edits = selectFindingKeyedEdits(content, findings);+ if (edits.legacy) {+ console.log(`⚠️ arc-resolve: response carries no resolves[] — applying it unkeyed (installed pipeline-arc-resolve.md predates #3724)`);+ }+ if (edits.arcDropped) {+ console.log(`⚠️ arc-resolve: dropped the arc-level edit — it named no input finding`);+ }+ if (edits.seasonsDropped || edits.episodesDropped) {+ console.log(`⚠️ arc-resolve: dropped ${edits.seasonsDropped} volume + ${edits.episodesDropped} episode edit(s) naming no input finding`);+ }+const arc = sanitizeArc({- logline: content?.arc?.logline || series.arc.logline || '',- summary: content?.arc?.summary || series.arc.summary || '',- themes: content?.arc?.themes ?? series.arc.themes,- protagonistArc: content?.arc?.protagonistArc ?? series.arc.protagonistArc ?? '',- shape: content?.arc?.shape ?? series.arc.shape ?? null,+ logline: edits.arc?.logline || series.arc.logline || '',+ summary: edits.arc?.summary || series.arc.summary || '',+ themes: edits.arc?.themes ?? series.arc.themes,+ protagonistArc: edits.arc?.protagonistArc ?? series.arc.protagonistArc ?? '',+ shape: edits.arc?.shape ?? series.arc.shape ?? null,// The resolve prompt doesn't author the reader map — preserve any existing// one so auto-resolve never silently wipes a reader map the user already// built on the next step. Mirrors `generateArcOverview` above.@@ -413,7 +469,7 @@ export async function resolveVerifyIssues(seriesId, options = {}) {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,+ foreshadowing: edits.arc?.foreshadowing ?? series.arc?.foreshadowing ?? null,status: 'draft',});@@ -421,7 +477,13 @@ export async function resolveVerifyIssues(seriesId, options = {}) {// brand-new entry (no `id`), otherwise preserve the existing `id` so child// issues still join their season cleanly. The sanitizer enforces the// canonical shape regardless.- const proposedSeasons = Array.isArray(content?.seasons) ? content.seasons : [];+ //+ // `seasons[]` is a SPARSE PATCH LIST (#3724), not the full volume lineup: the+ // response carries only the volumes the resolver actually edited, and every+ // existing volume it left out rides through untouched below. That removes the+ // old "omit a volume and it is deleted" footgun — deletion is now an explicit+ // `notes` recommendation, matching how episode deletion already worked.+ const proposedSeasons = edits.seasons;// Resolve each proposal to an existing record BEFORE minting. The resolve// prompt frequently returns a rewritten volume WITHOUT echoing its `id`;// matching on id alone read that as a brand-new season and minted one. With@@ -430,41 +492,42 @@ export async function resolveVerifyIssues(seriesId, options = {}) {// round ADDED a duplicate "Volume 1" instead of clearing a finding, and// arc-verify could never converge. See the divergence pause on 2026-08-09.const matchedExisting = matchProposedSeasons(series.seasons, proposedSeasons);- // Track each entry's provenance (existing id vs freshly minted) so we can- // remap orphaned child issues after sanitization.- const seasonEntries = proposedSeasons.map((raw, idx) => {+ // Patched rewrites keyed by the record they land on, plus the genuinely-new+ // volumes to append. Untouched existing volumes are carried through verbatim.+ const patchedById = new Map();+ const mintedSeasons = [];+ proposedSeasons.forEach((raw, idx) => {const existing = matchedExisting[idx];if (existing) {- return {- season: sanitizeSeason({- ...existing,- title: typeof raw.title === 'string' ? raw.title : existing.title,- number: Number.isFinite(raw.number) ? raw.number : existing.number,- logline: typeof raw.logline === 'string' ? raw.logline : existing.logline,- synopsis: typeof raw.synopsis === 'string' ? raw.synopsis : existing.synopsis,- endingHook: typeof raw.endingHook === 'string' ? raw.endingHook : existing.endingHook,- episodeCountTarget: Number.isFinite(raw.episodeCountTarget)- ? raw.episodeCountTarget- : existing.episodeCountTarget,- themes: Array.isArray(raw.themes) ? raw.themes : existing.themes,- }),- sourceId: existing.id,- };+ patchedById.set(existing.id, sanitizeSeason({+ ...existing,+ title: typeof raw.title === 'string' ? raw.title : existing.title,+ number: Number.isFinite(raw.number) ? raw.number : existing.number,+ logline: typeof raw.logline === 'string' ? raw.logline : existing.logline,+ synopsis: typeof raw.synopsis === 'string' ? raw.synopsis : existing.synopsis,+ endingHook: typeof raw.endingHook === 'string' ? raw.endingHook : existing.endingHook,+ episodeCountTarget: Number.isFinite(raw.episodeCountTarget)+ ? raw.episodeCountTarget+ : existing.episodeCountTarget,+ themes: Array.isArray(raw.themes) ? raw.themes : existing.themes,+ }));+ return;}- return {- season: buildSeason({- number: raw?.number,- title: raw?.title,- logline: raw?.logline,- synopsis: raw?.synopsis,- endingHook: raw?.endingHook,- episodeCountTarget: raw?.episodeCountTarget,- }),- sourceId: null,- };- }).filter((entry) => entry?.season);+ const minted = buildSeason({+ number: raw?.number,+ title: raw?.title,+ logline: raw?.logline,+ synopsis: raw?.synopsis,+ endingHook: raw?.endingHook,+ episodeCountTarget: raw?.episodeCountTarget,+ });+ if (minted) mintedSeasons.push(minted);+ });- const seasons = sanitizeSeasonList(seasonEntries.map((e) => e.season));+ const seasons = sanitizeSeasonList([+ ...(series.seasons || []).map((s) => patchedById.get(s.id) || s),+ ...mintedSeasons,+ ]);// `preserveDroppedSeasons` (autopilot unlock-for-run) rides through so an// auto-resolve can rewrite a volume but never delete one — see the option's@@ -484,7 +547,7 @@ export async function resolveVerifyIssues(seriesId, options = {}) {const episodesResolved = await applyEpisodeResolutions(seriesId,updated,- shapeEpisodeResolutions(content?.episodes),+ shapeEpisodeResolutions(edits.episodes),);const notes = typeof content?.notes === 'string' ? content.notes.trim().slice(0, 2000) : '';diff --git a/server/services/pipeline/arcPlanner/context.js b/server/services/pipeline/arcPlanner/context.jsindex 84249076df..163541a492 100644--- a/server/services/pipeline/arcPlanner/context.js+++ b/server/services/pipeline/arcPlanner/context.js@@ -661,12 +661,52 @@ export function matchIssueForEpisodeEdit(issues, seasonIdByNumber, edit) {: issues.find((i) => i.number === edit.episodeNumber);}+// ---------------------------------------------------------------------------+// Finding-keyed resolve edits (#3724). The resolve pass used to hand the LLM a+// bare finding list and take back a whole-arc rewrite, with nothing tying a+// proposed edit to the finding it was supposed to close — so a round handed ONE+// finding could legitimately rewrite every volume, and each untargeted rewrite+// was a fresh chance to author the contradiction the next verify files as a new+// blocker. Findings now go out stamped with a stable index-based id and every+// edit has to name at least one of them in `resolves[]`.+// ---------------------------------------------------------------------------++/** The stable id a finding is rendered under, by its position in the round's list. Pure. */+export const findingIdAt = (index) => `f${index + 1}`;++/** Copy the round's findings with their `findingId` stamped on for the prompt. Pure. */+export const stampFindingIds = (findings) => (Array.isArray(findings) ? findings : [])+ .map((f, i) => ({ findingId: findingIdAt(i), ...f }));++/** The set of ids a round's edits are allowed to name. Pure. */+export const findingIdSet = (findings) => new Set(+ (Array.isArray(findings) ? findings : []).map((_, i) => findingIdAt(i)),+);++/**+ * Read one proposed edit's `resolves[]` against the round's valid finding ids.+ * Returns `{ declared, matched }`: `declared` says the edit carried a+ * `resolves` array at all (absent = the model is running a pre-#3724 prompt,+ * which the caller treats as legacy rather than as a drop), `matched` is the+ * de-duplicated list of input findings it actually names. Pure.+ */+export function matchResolvedFindings(raw, validIds) {+ const declared = Array.isArray(raw?.resolves);+ if (!declared) return { declared: false, matched: [] };+ const matched = [];+ for (const entry of raw.resolves) {+ const id = typeof entry === 'string' ? entry.trim().toLowerCase() : '';+ if (id && validIds.has(id) && !matched.includes(id)) matched.push(id);+ }+ return { declared: true, matched };+}+export async function buildResolveContext(series, findings, preloadedWorld) {const ctx = await buildVerifyContext(series, preloadedWorld);const structure = recommendStructure(series.issueCountTarget);return {...ctx,- findingsJson: JSON.stringify(findings, null, 2),+ findingsJson: JSON.stringify(stampFindingIds(findings), null, 2),recommendedStructure: structure? describeStructure(structure): '(no target episode count set)',diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex 546387aeac..3bf110ee67 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -1444,6 +1444,15 @@ describe('isResolveRegression (pure resolve-round damage check)', () => {)).toBe(true);});+ it('matches a restatement that only re-words the OPENING clause', () => {+ // The narrow shape a leading-prefix fingerprint misses: same defect, same+ // place, but the verifier opens the sentence differently on the second call.+ expect(sameFinding(+ f('the mentor subplot introduced in the opening never pays off', 'V3'),+ f('nothing ever pays off the mentor subplot introduced in the opening', 'V3'),+ )).toBe(true);+ });+it('matches a re-punctuated, re-cased, re-pluralized restatement', () => {expect(sameFinding({ severity: 'high', location: 'V1', problem: 'Both volumes stage the first eclipse.' },