Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: resolve verified character arc findings
[._.]/ Adam Eivyd32e594141a7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex dc585a1aef..970657506e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -6,6 +6,8 @@- **Foundation structure repair retains shrinking corrective progress.** A broad structure rewrite whose specialized arc verification improved from many blockers to a smaller residual used to get one correction attempt and then roll the entire improvement back. The repair now continues a bounded correction sequence while the blocker count stays monotonic, still restoring the original checkpoint if the set grows or cannot clear within the cap.+- **Arc verification can now repair the per-character milestones it judges.** The verifier already read canonical per-character arcs, but its resolver could only edit the series arc, volumes, and issue synopses, so a contradiction in a character transition was impossible to close and repeated retries rewrote unrelated records instead. Finding-keyed character-arc patches now preserve character and transition IDs, merge only named fields, participate in regression rollback, and migrate existing prompt installations to the sparse contract.+- **Completed CoS agents no longer strand a worktree because of their own completion marker.** The `.agent-done` sentinel is consumed before worktree cleanup, but Git still reported the untracked file as ordinary authored work and the safety gate preserved the otherwise-clean checkout with a high-priority warning. Cleanup now ignores only that runtime marker: sentinel-only trees are removed normally, while any real source change still preserves the worktree and is named in the warning.- **A failed CoS task now diagnoses itself and comes back on its own.** A failing task used to pile up a queue of approval-gated tasks — the crash filed one, the provider failure filed another, repeated orphaning filed a third — and then, even after the cause was fixed, the original task sat `blocked` until someone un-blocked it by hand (or the 14-day reaper quietly retired it as stale). Both halves of that are now automatic. Every failure-driven investigation is filed through one producer, so they share a single approval policy, a single storm counter, and a single dedup fingerprint: unattended by default, held for you in exactly the two cases where another unattended agent would just repeat itself — the same cause was already investigated in the last 24 hours, or failures are cascading rather than isolated — and the task says which of the two it is. Completing an investigation, whether an agent finished it or you fixed the cause and ticked it off, then automatically retries every task that failure was blocking. Bounded at two automatic retries per task, after which the task stays blocked and says the retry loop gave up rather than still showing the original failure. A task you terminated or paused, one parked awaiting your arbitration, and one waiting on a repository path you have to fix are never revived behind your back.diff --git a/data.reference/prompts/stages/pipeline-arc-resolve.md b/data.reference/prompts/stages/pipeline-arc-resolve.mdindex dfe914bbb0..bfe6b831bc 100644--- a/data.reference/prompts/stages/pipeline-arc-resolve.md+++ b/data.reference/prompts/stages/pipeline-arc-resolve.md@@ -1,6 +1,6 @@# Pipeline — Arc Verification Auto-Resolve-You are a senior story editor cleaning up a planned series so it passes verification. The user ran a continuity pass against their arc + volumes/seasons and got back a list of structural findings. Your job is to rewrite the arc + volume outlines so every finding is resolved, while preserving as much of the user's original work as possible.+You are a senior story editor cleaning up a planned series so it passes verification. The user ran a continuity pass against their arc, per-character arcs, and volumes/seasons and got back a list of structural findings. Your job is to apply the smallest finding-specific corrections so every finding is resolved, while preserving as much of the user's original work as possible.Every series is published as both a graphic novel (issues → volumes) AND a TV series (episodes → seasons). One issue == one episode; one volume == one season. Your edits must work for both.@@ -56,6 +56,15 @@ The arc is grounded in this World Builder world: **{{worldName}}**. When you rew{{arc.summary}}```+## Current per-character arcs++These are canonical persisted records. Their character and transition IDs are+load-bearing: preserve them exactly and patch only the field(s) a finding names.++```json+{{characterArcsJson}}+```+## Story shape (Vonnegut){{{shapeGuidance}}}@@ -72,7 +81,7 @@ When rewriting the arc + volume synopses, preserve the picked shape — do not cThis is the pre-episode **arc-spine checkpoint**. The episode arrays areintentionally empty — no episode lineup exists yet, and the verification passthat produced the findings below judged this same episode-free plan. Resolve-every finding by editing the **arc and the volumes only**. Do **not** return an+every finding by editing the **arc, per-character arcs, and volumes only**. Do **not** return an`episodes[]` array: the server discards it here, so an episode rewrite spendsthe round without closing anything. Every instruction below about anchoring inper-episode synopses, or about correcting an episode whose own content caused a@@ -111,13 +120,13 @@ Resolve the findings above with edits that cannot re-create any of these. Concre1. **Anchor every edit in the per-episode `synopsis` entries.** Each volume's `episodes[]` array carries the planned episode lineup — those `synopsis` strings describe what actually happens in each issue. Prefer the **minimal** edit: most findings resolve by re-framing a volume's `synopsis` around what its child episodes already show. Don't invent beats no episode synopsis covers. When a finding cites an episode (e.g. `season:2 / episode:5`), first ask whether the volume synopsis can summarize what that episode shows without contradicting a neighbor. Empty/null episode synopses mean that issue hasn't been drafted yet; treat that volume as load-bearing on its own `synopsis` only.2. **Read each finding's `problem` + `suggestion`.** The suggestion is a hint, not gospel — feel free to take a different path if it cleans up the arc better, but the resulting arc MUST make the finding go away.3. **Volume-count-vs-weight mismatches** (the most common finding) — usually the right fix is to **trim or expand a volume's `synopsis`** so it matches its `episodeCountTarget`, OR adjust `episodeCountTarget` toward the structural recommendation. Don't split a volume into two unless the structural recommendation calls for more volumes than currently exist.-4. **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.+4. **Character contradictions** — edit the record where the contradiction actually lives. If a finding names `series.characterArcs`, a provisional character arc, or one of its transition milestones, return a sparse `characterArcs[]` patch for that exact existing character/transition ID. Do not paper over a stale character milestone by rewriting a volume or the top-level protagonist arc. Do not silently delete a 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 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.-10. **Within an edited record, return only the fields that must change.** A season may need a new `synopsis` without needing a new `logline`, `endingHook`, title, count, or themes. Omit every untouched key instead of paraphrasing the stored value "for completeness". The server preserves omitted fields. 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.+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 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.+10. **Within an edited record, return only the fields that must change.** A season may need a new `synopsis` without needing a new `logline`, `endingHook`, title, count, or themes. 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.11. **Stay safely inside persisted string limits and end every field cleanly.** Hard limits are: arc logline 500 characters; arc summary 8,000; protagonist arc 4,000; volume logline 500; volume synopsis 8,000; volume ending hook 1,000. Target at most 450 / 7,500 / 3,700 / 450 / 7,500 / 900 characters respectively so punctuation and later edits have headroom. Before returning, check every changed string: it must be below its target and end at a complete clause or sentence. Never rely on the server to truncate prose. Keep a volume synopsis near 200 words when that can carry the issue allocation; expand only as much as the finding genuinely requires.## Output contract@@ -133,6 +142,20 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c"themes": ["string", "..."],"protagonistArc": "string"},+ "characterArcs": [+ {+ "resolves": ["f2"],+ "characterId": "chr-... (repeat the existing ID; if absent, use exact characterName instead)",+ "transitions": [+ {+ "id": "trn-... (repeat the existing transition ID)",+ "atIssue": 12,+ "label": "only the corrected milestone text",+ "note": "only when this field also changes"+ }+ ]+ }+ ],"seasons": [{"resolves": ["f1", "f3"],@@ -160,6 +183,8 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no cThe `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 `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.Omit the `arc` block entirely when the arc itself needed no rewrite. Within every record you do return, omit fields that do not need to change. Every field you include must be complete and within the limits above — 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 edb611f350..510e0bea1a 100644--- a/scripts/migrations/005-shape-aware-arc-prompts.js+++ b/scripts/migrations/005-shape-aware-arc-prompts.js@@ -53,7 +53,7 @@ export const NEW_SHIPPED_MD5 = {'pipeline-arc-verify.md': '83347e7d923580a3062033ab39b3c14b', // post-250 arc spine checkpoint'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940', // post-019'pipeline-season-episodes.md': 'a88e8e78a949b7aaf500d03314e2ea0b', // post-172 (structure rules)- 'pipeline-arc-resolve.md': '0611db539437083621e19bb88b005e8d', // post-253 (spine-scoped rounds)+ 'pipeline-arc-resolve.md': '31eca76b68f40de1b93734fe9bc9f4bb', // post-254 (sparse character-arc repairs)};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 f2a26332a0..9773cc4a6a 100644--- a/scripts/migrations/019-arc-volume-prompts-canon-context.js+++ b/scripts/migrations/019-arc-volume-prompts-canon-context.js@@ -62,7 +62,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': '83347e7d923580a3062033ab39b3c14b', // post-250 arc spine checkpoint- 'pipeline-arc-resolve.md': '0611db539437083621e19bb88b005e8d', // post-253 (spine-scoped rounds)+ 'pipeline-arc-resolve.md': '31eca76b68f40de1b93734fe9bc9f4bb', // post-254 (sparse character-arc repairs)'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 7b32b9361e..d7fe4c52b1 100644--- a/scripts/migrations/023-resolve-prompt-episode-anchor.js+++ b/scripts/migrations/023-resolve-prompt-episode-anchor.js@@ -40,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': '0611db539437083621e19bb88b005e8d', // post-253 (spine-scoped rounds)+ 'pipeline-arc-resolve.md': '31eca76b68f40de1b93734fe9bc9f4bb', // post-254 (sparse character-arc repairs)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/245-arc-resolve-finding-keyed-patches.js b/scripts/migrations/245-arc-resolve-finding-keyed-patches.jsindex 436042b490..bb26554fd9 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': '0611db539437083621e19bb88b005e8d', // post-253 (spine-scoped rounds)+ 'pipeline-arc-resolve.md': '31eca76b68f40de1b93734fe9bc9f4bb', // post-254 (sparse character-arc repairs)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/251-arc-resolve-field-sparsity.js b/scripts/migrations/251-arc-resolve-field-sparsity.jsindex a8bb639e79..e95e0f5c93 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': '0611db539437083621e19bb88b005e8d', // post-253 (spine-scoped rounds)+ 'pipeline-arc-resolve.md': '31eca76b68f40de1b93734fe9bc9f4bb', // post-254 (sparse character-arc repairs)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/252-arc-resolve-avoid-list.js b/scripts/migrations/252-arc-resolve-avoid-list.jsindex deee0b1339..ce20d58f90 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': '0611db539437083621e19bb88b005e8d', // post-253 (spine-scoped rounds)+ 'pipeline-arc-resolve.md': '31eca76b68f40de1b93734fe9bc9f4bb', // post-254 (sparse character-arc repairs)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/253-arc-resolve-spine-scope.js b/scripts/migrations/253-arc-resolve-spine-scope.jsindex 75ed775dc5..d55d5da557 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': '0611db539437083621e19bb88b005e8d', // post-253 (spine-scoped rounds)+ 'pipeline-arc-resolve.md': '31eca76b68f40de1b93734fe9bc9f4bb', // post-254 (sparse character-arc repairs)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/253-arc-resolve-spine-scope.test.js b/scripts/migrations/253-arc-resolve-spine-scope.test.jsindex 8a6bc01cf1..64a826738b 100644--- a/scripts/migrations/253-arc-resolve-spine-scope.test.js+++ b/scripts/migrations/253-arc-resolve-spine-scope.test.js@@ -30,7 +30,7 @@ describe('migration 253 — arc-resolve spine-scoped rounds', () => {// The section has to say the episode arrays are empty BY DESIGN — a// resolver that reads them as missing data invents an episode lineup.expect(prompt).toMatch(/intentionally empty/);- expect(prompt).toMatch(/arc and the volumes only/);+ expect(prompt).toMatch(/arc, per-character arcs, and volumes only/);expect(prompt).toMatch(/Do \*\*not\*\* return an\s+`episodes\[\]` array/);// Rule 8 (episode corrections) still ships for the full gate.expect(prompt).toMatch(/Correct an episode synopsis when the contradiction/);diff --git a/scripts/migrations/254-arc-resolve-character-arcs.js b/scripts/migrations/254-arc-resolve-character-arcs.jsnew file mode 100644index 0000000000..b46a4c98f2--- /dev/null+++ b/scripts/migrations/254-arc-resolve-character-arcs.js@@ -0,0 +1,31 @@+/**+ * Let arc verification repair the per-character arcs it judges.+ *+ * The verifier reads `series.characterArcs`, but the resolver's output contract+ * previously exposed only the series arc, volumes, and episode synopses. A+ * finding against a provisional transition was therefore impossible to close;+ * repeated rounds rewrote neighboring records and regressed instead. The new+ * contract emits finding-keyed, ID-preserving sparse character-arc patches.+ */++import { makePromptReplaceMigration } from './_lib.js';++export const ACCEPTED_OLD_MD5 = {+ 'pipeline-arc-resolve.md': ['0611db539437083621e19bb88b005e8d'],+};++export const NEW_SHIPPED_MD5 = {+ 'pipeline-arc-resolve.md': '31eca76b68f40de1b93734fe9bc9f4bb',+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'arc-resolve sparse character-arc repairs',+ customizedHint: (filename) =>+ ` To upgrade it manually, diff data.reference/prompts/stages/${filename}\n` ++ ` against data/prompts/stages/${filename} and add the finding-keyed characterArcs[] patch contract.`,+});++export { applyMigration };+export default { up };diff --git a/scripts/migrations/254-arc-resolve-character-arcs.test.js b/scripts/migrations/254-arc-resolve-character-arcs.test.jsnew file mode 100644index 0000000000..d096779efa--- /dev/null+++ b/scripts/migrations/254-arc-resolve-character-arcs.test.js@@ -0,0 +1,31 @@+import { readFileSync } from 'fs';+import { describe, expect, it } from 'vitest';++import { repoRoot, runPromptMigrationTests } from './_testHelpers.js';+import migration, {+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ applyMigration,+} from './254-arc-resolve-character-arcs.js';++describe('migration 254 — arc-resolve sparse character-arc repairs', () => {+ runPromptMigrationTests({+ migration,+ applyMigration,+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ prefix: 'migration-254-arc-resolve-character-arcs-',+ });++ it('ships the ID-preserving sparse character-arc patch contract', () => {+ const prompt = readFileSync(+ `${repoRoot}/data.reference/prompts/stages/pipeline-arc-resolve.md`,+ 'utf8',+ );+ expect(prompt).toContain('{{characterArcsJson}}');+ expect(prompt).toContain('`characterArcs[]` patch');+ expect(prompt).toMatch(/repeat its existing `characterId`/);+ expect(prompt).toMatch(/transition patch must repeat its existing `id`/);+ expect(prompt).toMatch(/Unmatched\/new IDs are discarded rather than minted/);+ });+});diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.jsindex 650b4bba74..cc22419a96 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -969,6 +969,55 @@ describe('arcPlanner — resolveVerifyIssues', () => {expect(out.series.seasons[1].synopsis).toBe('v2 rewritten');});+ it('applies sparse character-arc and transition patches without replacing IDs or sibling arcs', async () => {+ const s = await setupSeries();+ await seriesSvc.updateSeries(s.id, {+ arc: { logline: 'L' },+ characterArcs: [+ {+ characterId: 'chr-lead', characterName: 'Lead', want: 'escape', need: 'trust',+ startState: 'guarded', endState: 'open', status: 'verified',+ transitions: [+ { id: 'trn-choice', kind: 'decision', atIssue: 5, label: 'withholds consent', note: 'old note' },+ { id: 'trn-sacrifice', kind: 'sacrifice', atIssue: 11, label: 'spends the reserve', note: '' },+ ],+ },+ {+ characterId: 'chr-sibling', characterName: 'Sibling', want: 'belong', need: 'choose',+ startState: 'adrift', endState: 'committed', transitions: [],+ },+ ],+ });++ stageRunnerSpy = vi.fn(async () => ({+ content: {+ characterArcs: [{+ resolves: ['f1'],+ characterId: 'chr-lead',+ transitions: [{ id: 'trn-sacrifice', atIssue: 12, label: 'freely authorizes the final opening' }],+ }],+ notes: '',+ },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ const out = await planner.resolveVerifyIssues(s.id, {+ findings: [{ severity: 'high', problem: 'The sacrifice is assigned to issue 11.', suggestion: 'Move it to 12.' }],+ spineOnly: true,+ });++ expect(out.series.characterArcs).toHaveLength(2);+ const [lead, sibling] = out.series.characterArcs;+ expect(lead).toMatchObject({ characterId: 'chr-lead', want: 'escape', need: 'trust', status: 'verified' });+ expect(lead.transitions).toEqual([+ expect.objectContaining({ id: 'trn-choice', atIssue: 5, label: 'withholds consent', note: 'old note' }),+ expect.objectContaining({ id: 'trn-sacrifice', atIssue: 12, label: 'freely authorizes the final opening', kind: 'sacrifice' }),+ ]);+ expect(sibling).toMatchObject({ characterId: 'chr-sibling', startState: 'adrift', endState: 'committed' });+ const ctx = stageRunnerSpy.mock.calls[0][1];+ expect(JSON.parse(ctx.characterArcsJson)[0].transitions[1].id).toBe('trn-sacrifice');+ });+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' } });@@ -1358,12 +1407,15 @@ describe('selectFindingKeyedEdits (pure resolve-edit filter, #3724)', () => {it('keeps edits naming an input finding and drops the rest', () => {const out = select({arc: { resolves: ['f2'], logline: 'x' },+ characterArcs: [{ resolves: ['f2'], characterId: 'chr-a' }, { resolves: ['f8'], characterId: 'chr-b' }],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.characterArcs).toHaveLength(1);+ expect(out.characterArcsDropped).toBe(1);expect(out.seasons).toHaveLength(1);expect(out.seasonsDropped).toBe(2);expect(out.episodes).toHaveLength(1);@@ -1418,7 +1470,7 @@ describe('selectFindingKeyedEdits (pure resolve-edit filter, #3724)', () => {});it('tolerates a missing/garbage response', () => {- expect(select(null)).toMatchObject({ legacy: true, arc: null, seasons: [], episodes: [] });+ expect(select(null)).toMatchObject({ legacy: true, arc: null, characterArcs: [], seasons: [], episodes: [] });expect(select({ arc: 'not an object', seasons: 'nope', episodes: [null, 3] })).toMatchObject({ arc: null, seasons: [], episodes: [] });});@@ -1435,7 +1487,14 @@ describe('arcPlanner — snapshotArcState / restoreArcState (resolve-round rollb// and an episode under each carrying a planning synopsis.async function seedArc() {const s = await setupSeries();- await seriesSvc.updateSeries(s.id, { arc: { logline: 'original logline', summary: 'original summary' } });+ await seriesSvc.updateSeries(s.id, {+ arc: { logline: 'original logline', summary: 'original summary' },+ characterArcs: [{+ characterId: 'chr-lead', characterName: 'Lead', want: 'escape', need: 'trust',+ startState: 'guarded', endState: 'open',+ transitions: [{ id: 'trn-sacrifice', kind: 'sacrifice', atIssue: 12, label: 'chooses the crew' }],+ }],+ });const v1 = await seasonsSvc.createSeason(s.id, { title: 'Volume 1', synopsis: 'v1 synopsis', episodeCountTarget: 2 });const v2 = await seasonsSvc.createSeason(s.id, { title: 'Volume 2', synopsis: 'v2 synopsis', episodeCountTarget: 2 });const e1 = await issuesSvc.createIssue({ seriesId: s.id, seasonId: v1.id, title: 'Ep 1' });@@ -1456,6 +1515,11 @@ describe('arcPlanner — snapshotArcState / restoreArcState (resolve-round rollbconst minted = await seasonsSvc.createSeason(s.id, { title: 'Volume 1', synopsis: 'duplicate', episodeCountTarget: 2 });await seriesSvc.updateSeries(s.id, {arc: { logline: 'rewritten logline', summary: 'rewritten summary' },+ characterArcs: [{+ characterId: 'chr-lead', characterName: 'Lead', want: 'escape', need: 'control',+ startState: 'guarded', endState: 'alone',+ transitions: [{ id: 'trn-sacrifice', kind: 'sacrifice', atIssue: 11, label: 'wrong milestone' }],+ }],seasons: [{ ...v1, synopsis: 'rewritten v1' }, v2, minted],});await issuesSvc.updateIssue(e2.id, { seasonId: minted.id });@@ -1466,6 +1530,8 @@ describe('arcPlanner — snapshotArcState / restoreArcState (resolve-round rollbconst series = await seriesSvc.getSeries(s.id);expect(series.arc.logline).toBe('original logline');+ expect(series.characterArcs[0]).toMatchObject({ need: 'trust', endState: 'open' });+ expect(series.characterArcs[0].transitions[0]).toMatchObject({ id: 'trn-sacrifice', atIssue: 12, label: 'chooses the crew' });expect(series.seasons.map((x) => x.id)).toEqual([v1.id, v2.id]);expect(series.seasons[0].synopsis).toBe('v1 synopsis');// The minted volume is gone, so the episode it took has to come back with@@ -1496,8 +1562,15 @@ describe('arcPlanner — snapshotArcState / restoreArcState (resolve-round rollbit('snapshots by value — a later write cannot mutate what was captured', async () => {const { s } = await seedArc();const snapshot = await planner.snapshotArcState(s.id);- await seriesSvc.updateSeries(s.id, { arc: { logline: 'mutated', summary: 'mutated' } });+ await seriesSvc.updateSeries(s.id, {+ arc: { logline: 'mutated', summary: 'mutated' },+ characterArcs: [{+ characterId: 'chr-lead', characterName: 'Lead', want: 'mutated', need: 'mutated',+ startState: 'mutated', endState: 'mutated', transitions: [],+ }],+ });expect(snapshot.arc.logline).toBe('original logline');+ expect(snapshot.characterArcs[0].want).toBe('escape');});});diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.jsindex 878e584b07..f26354bc6c 100644--- a/server/services/pipeline/arcPlanner/arcCore.js+++ b/server/services/pipeline/arcPlanner/arcCore.js@@ -15,6 +15,7 @@ import { listIssues, listIssuesForSeries, recomputeIssueNumbersForSeries, updateimport { emitRecordUpdated, withReexportSuppressed } from '../../sharing/recordEvents.js';import { getSeason } from '../seasons.js';import { READER_MAP_BEAT_KINDS, buildSeason, cleanThemes, renderArcShapeGuidance, renderArcShapePositionSummary, sanitizeArc, sanitizeReaderMap, sanitizeSeason, sanitizeSeasonList } from '../../../lib/storyArc.js';+import { sanitizeCharacterArcList } from '../../../lib/seriesCharacterArc.js';import { runPromptRefineRaw, trimChanges } from '../refineHelpers.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';@@ -359,11 +360,12 @@ export async function verifyVolume(seriesId, seasonId, options = {}) {* 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+ * Every entry in `arc` / `characterArcs[]` / `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, episodesOutOfScope }`.+ * benefit. Returns `{ legacy, arc, arcDropped, characterArcs,+ * characterArcsDropped, seasons, seasonsDropped, episodes, episodesDropped,+ * episodesOutOfScope }`.** `spineOnly` drops every episode edit regardless of what it names (#3789): a* spine round is judged against an episode-empty plan, so an episode rewrite@@ -386,17 +388,21 @@ export function selectFindingKeyedEdits(content, findings, { spineOnly = false }const validIds = findingIdSet(findings);const isEdit = (e) => !!e && typeof e === 'object';const arcEdit = isEdit(content?.arc) ? content.arc : null;+ const characterArcsRaw = (Array.isArray(content?.characterArcs) ? content.characterArcs : []).filter(isEdit);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]+ const legacy = ![arcEdit, ...characterArcsRaw, ...seasonsRaw, ...episodesRaw].some((e) => e && matchResolvedFindings(e, validIds).declared);const targeted = (raw) => legacy || matchResolvedFindings(raw, validIds).matched.length > 0;+ const characterArcs = characterArcsRaw.filter(targeted);const seasons = seasonsRaw.filter(targeted);const episodes = spineOnly ? [] : episodesRaw.filter(targeted);return {legacy,arc: arcEdit && targeted(arcEdit) ? arcEdit : null,arcDropped: !!arcEdit && !targeted(arcEdit),+ characterArcs,+ characterArcsDropped: characterArcsRaw.length - characterArcs.length,seasons,seasonsDropped: seasonsRaw.length - seasons.length,episodes,@@ -405,9 +411,61 @@ export function selectFindingKeyedEdits(content, findings, { spineOnly = false }};}-// 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+const characterArcKey = (arc) => {+ const characterId = typeof arc?.characterId === 'string' ? arc.characterId.trim() : '';+ if (characterId) return `id:${characterId}`;+ const characterName = typeof arc?.characterName === 'string' ? arc.characterName.trim().toLowerCase() : '';+ return characterName ? `name:${characterName}` : '';+};++const CHARACTER_ARC_PATCH_FIELDS = Object.freeze([+ 'want', 'need', 'startState', 'endState', 'status',+]);+const TRANSITION_PATCH_FIELDS = Object.freeze([+ 'kind', 'label', 'atIssue', 'atSceneAnchor', 'note',+]);++/**+ * Apply finding-keyed per-character arc edits as sparse patches. Existing+ * character and transition identifiers are required and preserved: an arc+ * verifier finding must never mint a new cast arc or replace every transition+ * merely because the model corrected one milestone.+ */+export function mergeCharacterArcPatches(existingArcs, patches) {+ const current = sanitizeCharacterArcList(existingArcs);+ if (!Array.isArray(patches) || patches.length === 0) return current;+ const patchByKey = new Map(patches.map((patch) => [characterArcKey(patch), patch]).filter(([key]) => key));+ const merged = current.map((arc) => {+ const patch = patchByKey.get(characterArcKey(arc));+ if (!patch) return arc;+ const next = { ...arc };+ for (const field of CHARACTER_ARC_PATCH_FIELDS) {+ if (field in patch) next[field] = patch[field];+ }+ if (Array.isArray(patch.transitions)) {+ const transitionPatches = new Map(patch.transitions+ .filter((transition) => transition && typeof transition === 'object' && typeof transition.id === 'string')+ .map((transition) => [transition.id, transition]));+ next.transitions = arc.transitions.flatMap((transition) => {+ const transitionPatch = transitionPatches.get(transition.id);+ if (!transitionPatch) return [transition];+ if (transitionPatch.delete === true) return [];+ const updated = { ...transition };+ for (const field of TRANSITION_PATCH_FIELDS) {+ if (field in transitionPatch) updated[field] = transitionPatch[field];+ }+ return [updated];+ });+ }+ return next;+ });+ return sanitizeCharacterArcList(merged);+}++// 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// 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@@ -415,8 +473,8 @@ export function selectFindingKeyedEdits(content, findings, { spineOnly = false }// these same findings authored THESE and was reverted" list (see// buildResolveContext) — set only by a corrective pass.// `options.spineOnly` mirrors verifyArc's pre-episode arc-spine mode: the-// resolver sees the same episode-empty plan and may only patch the arc +-// volumes (#3789). It is a PAIRING constraint, not an independent knob — it+// resolver sees the same episode-empty plan and may only patch the series arc,+// per-character arcs, and volumes (#3789). It is a PAIRING constraint, not an independent knob — it// must match the verify that produced `options.findings`, or the resolver// answers at an altitude the gate never judged. Episode-synopsis corrections// stay available for the later full arc gate, which runs after episodes exist@@ -484,14 +542,14 @@ export async function resolveVerifyIssues(seriesId, options = {}) {// Only worth saying when there is actually something to apply unkeyed — a// response that proposed NO edits reads as legacy too, and warning about a// stale prompt there would be a lie.- if (edits.legacy && (edits.arc || edits.seasons.length || edits.episodes.length)) {+ if (edits.legacy && (edits.arc || edits.characterArcs.length || edits.seasons.length || edits.episodes.length)) {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`);+ if (edits.characterArcsDropped || edits.seasonsDropped || edits.episodesDropped) {+ console.log(`⚠️ arc-resolve: dropped ${edits.characterArcsDropped} character arc + ${edits.seasonsDropped} volume + ${edits.episodesDropped} episode edit(s) naming no input finding`);}if (edits.episodesOutOfScope) {console.log(`⚠️ arc-resolve: discarded ${edits.episodesOutOfScope} episode edit(s) — the arc-spine gate resolves at arc/volume scope only`);@@ -580,6 +638,12 @@ export async function resolveVerifyIssues(seriesId, options = {}) {{ preserveDroppedSeasons: options.preserveDroppedSeasons === true },);+ const characterArcs = mergeCharacterArcPatches(updated.characterArcs, edits.characterArcs);+ const characterArcsChanged = JSON.stringify(characterArcs) !== JSON.stringify(updated.characterArcs || []);+ const resolvedSeries = characterArcsChanged+ ? await updateSeries(seriesId, { characterArcs })+ : updated;+// Apply any episode-level synopsis corrections the resolver returned. This is// the heal capability that lets episode-scoped findings converge: when a// contradiction originates inside one episode's planning synopsis (e.g. it@@ -588,13 +652,13 @@ export async function resolveVerifyIssues(seriesId, options = {}) {// here (after the arc+season commit) against the freshest issue set.const episodesResolved = await applyEpisodeResolutions(seriesId,- updated,+ resolvedSeries,shapeEpisodeResolutions(edits.episodes),);const notes = typeof content?.notes === 'string' ? content.notes.trim().slice(0, 2000) : '';return {- series: updated,+ series: resolvedSeries,applied: true,notes,findings,@@ -674,11 +738,11 @@ const ideaSnapshotOf = (stage) => ({const listEpisodesForSnapshot = (seriesId) => listIssuesForSeries(seriesId, { withHistory: false });/**- * Capture everything ONE auto-resolve round can rewrite — the arc, the volume- * records, and each episode's planning synopsis (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).+ * Capture everything ONE auto-resolve round can rewrite — the series arc,+ * per-character arcs, volume records, and each episode's planning synopsis+ * (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).** Deep-cloned: `getSeries` hands back the store record un-cloned, and a snapshot* that aliases the record it is meant to restore is no snapshot at all.@@ -688,6 +752,7 @@ export async function snapshotArcState(seriesId) {return {seriesId,arc: structuredClone(series.arc ?? null),+ characterArcs: structuredClone(series.characterArcs || []),seasons: structuredClone(series.seasons || []),episodes: issues.map((iss) => ({id: iss.id,@@ -699,8 +764,9 @@ export async function snapshotArcState(seriesId) {/*** Put a `snapshotArcState` capture back, restoring only what actually differs:- * the arc + volume list, any episode whose volume the round re-pointed, and any- * episode synopsis the round rewrote. Returns what it touched.+ * the series arc, per-character arcs, volume list, any episode whose volume the+ * round re-pointed, and any episode synopsis the round rewrote. Returns what it+ * touched.** Deliberately NOT routed through `commitSeasonsWithRemap`: that path merges,* preserves and re-mints, which is right for applying a rewrite and wrong for@@ -746,7 +812,11 @@ export async function restoreArcState(seriesId, snapshot) {// between writes can't leave an issue pointing at a volume that isn't in// `series.seasons[]`.await withReexportSuppressed('series', seriesId, async () => {- await updateSeries(seriesId, { arc: snapshot.arc, seasons: snapshot.seasons });+ await updateSeries(seriesId, {+ arc: snapshot.arc,+ seasons: snapshot.seasons,+ ...(Array.isArray(snapshot.characterArcs) ? { characterArcs: snapshot.characterArcs } : {}),+ });for (const snap of reassign) {await updateIssue(snap.id, { seasonId: snap.seasonId }, { skipRenumber: true });}diff --git a/server/services/pipeline/arcPlanner/context.js b/server/services/pipeline/arcPlanner/context.jsindex 9e0f36ff34..7b5afeb3b7 100644--- a/server/services/pipeline/arcPlanner/context.js+++ b/server/services/pipeline/arcPlanner/context.js@@ -727,6 +727,7 @@ export async function buildResolveContext(series, findings, preloadedWorld, opticonst avoid = shapeFindings(options.avoid);return {...ctx,+ characterArcsJson: JSON.stringify(series.characterArcs || [], null, 2),findingsJson: JSON.stringify(stampFindingIds(findings), null, 2),hasAvoid: avoid.length > 0,avoidJson: JSON.stringify(avoid, null, 2),