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: bound an isolated arc repair to one record and one field
[._.]/ Adam Eivy4d325dbd6432
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex df6f085041..87a1dde3b3 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -105,3 +105,4 @@- **An arc verification no longer forgets a rejected rewrite one round after it reverted it.** The gate already carried a reverted candidate's own blockers into the corrective retry that follows the rollback, as "do not author these" evidence — but only that one call. If the retry landed on a state that was no better than the checkpoint yet still blocked, the next ordinary resolve rebuilt its avoid list from scratch, so the resolver was free to re-author the exact rewrite the gate had just thrown away. That is what a paused run showed: 2 blockers resolved down to 1, a rewrite back up to 5 (reverted), the retry back to 1, then straight back to 2 with no retries left and a pause for review. Every blocker set discarded during a run is now accumulated and passed to every later resolve in that gate — ordinary, corrective, and per-finding isolated alike — bounded by the same limit the persisted marker uses, newest evidence first so it is never the part that gets trimmed. Anything that has since become an active repair target is filtered out, so the resolver is never told to both fix and avoid the same finding, and the cross-Resume evidence from a previous run still layers in underneath.- **That rejected-rewrite evidence now survives the pause, and the isolation pass banks its own.** Accumulating a run's discarded blocker sets fixed the gate mid-run, but two boundaries still threw the evidence away — both the same failure one level out. A run that reverted two *different* rewrites before pausing persisted only the newest set, so a Resume inherited the last rollback alone and its resolver could re-author the first; the whole history now rides a separate `runDiscardedFindings` on the paused marker, which leaves the panel's "Discarded — what the reverted round produced" copy true of the field it renders and hands the resumed gate everything. And the per-finding isolation pass — the escalation that resolves a residual one finding at a time once the whole-set retries are spent — computed its avoid list once for the whole pass and never recorded its own rejected patches, so a rewrite rejected on target 1 could be re-proposed verbatim on target 3, and nothing it learned reached the ordinary resolve that follows a successful isolation. Each rejected patch's verified consequence is now banked like a whole-set rollback's, and the avoid list is rebuilt per target. It is still filtered against everything the pass is currently repairing, so no attempt is told to both fix and avoid the same finding, and a marker written before the new field exists resumes on what it has.- **The foundation gate now remembers every repair it rejected for a dimension, not just the last one.** Two rollback-evidence models were living side by side in one file: the arc gate accumulates every discarded set for its whole lifetime and carries it across a pause, while the foundation gate kept a single most-recent rejection per dimension — so a dimension that rejected two different repairs handed the third evidence of only the second, and the editor was free to re-author the first. Same evidence loss, one level down, and a reader had every reason to assume the two behaved alike. Both gates now ride one shared per-key bank: the arc gate banks a flat history as before, the foundation gate banks one per dimension, and each rejected set is recorded at the moment it is thrown away rather than when the next attempt happens to read it — so an unverified restore, which pauses without ever reaching a retry, still contributes its evidence. An accepted repair no longer wipes the dimension's history (a candidate the gate rejected is still a candidate it rejected; only the stale "this failed, try another angle" strategy note is cleared), and the evidence is filtered against the gap the call is actually being asked to close, so no editor is told to both fix and avoid the same thing. It survives the pause too, as a per-dimension `foundationDiscardedFindings` on the paused marker that a resume seeds its bank from — a marker written before the field existed simply resumes with an empty bank, exactly as it does today.+- **An "isolated" arc repair now has to actually be one small edit.** When arc verification's auto-resolve regresses twice on the same residual, the gate escalates to fixing one finding at a time — snapshot, resolve that finding alone, re-verify, keep the patch only if it closed its own target without growing the set. Isolating the *finding* never isolated the *edit*, though: every entry in a single-finding response trivially names that one finding, so the finding-keyed filter passed a whole-arc rewrite plus every volume, and each "isolated" attempt regressed exactly like the whole-set pass it had escalated from. On the run that surfaced this, both attempts started from the same verified 2-blocker checkpoint and came back with 4 and then 7, so the gate paused having retained nothing after four resolves and three verifications. The resolver now has an explicit isolated mode: the prompt is told the contract, and the server discards the candidate *before persistence* unless it is one causal patch — one owner record, one changed field (one exact-text replacement, one short scalar, or one existing character-transition patch). Echoed identity fields that match what is stored don't count as changes, and neither do edits the appliers would have dropped anyway. A rejected candidate costs its own resolve call and nothing else: there is no rewrite to roll back and no verification round billed to discover that it was worse. Coordinated cross-record repairs stay with the whole-set and corrective passes, and every existing guard — spine-only scope, the blocker-count rollback, the round limits, restoring the best verified snapshot — is untouched.diff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsxindex 32edb83996..20b22d44c4 100644--- a/client/src/components/pipeline/AutopilotPanel.jsx+++ b/client/src/components/pipeline/AutopilotPanel.jsx@@ -308,8 +308,13 @@ function frameLabel(f) {// Per-finding isolation: each attempt is its own kept-or-reverted decision,// so name the finding it was spent on — a bare "attempt 2 reverted" reads as// the whole gate rolling back again rather than one candidate being dropped.+ // A candidate too broad to BE an isolated repair is dropped before it is+ // applied, so it never edited the plan and its blocker counts never moved —+ // reporting that as "reverted" would describe an undo that never happened.case 'resolve:isolate': return `${f.scope} isolated fix ${f.attempt}${f.target ? ` (${f.target})` : ''} — `- + `${f.before} → ${f.after} blocking finding(s), ${f.kept ? 'kept' : 'reverted'}`;+ + (f.reason+ ? `discarded before it was applied: ${f.reason}`+ : `${f.before} → ${f.after} blocking finding(s), ${f.kept ? 'kept' : 'reverted'}`);// #2176 — foundation-gate telemetry.case 'foundation:round': return `Foundation round ${f.round} — weighted ${f.weightedScore}/${f.threshold}${f.weakest ? ` · next target: ${f.weakest}` : ''}`;case 'foundation:fix': return `${f.phase === 'pre-arc' ? 'Pre-arc foundation' : 'Foundation fix'} — ${f.dimension}${f.applied ? ' applied' : ` skipped${f.reason ? ` (${f.reason})` : ''}`}`;diff --git a/data.reference/prompts/stages/pipeline-arc-resolve.md b/data.reference/prompts/stages/pipeline-arc-resolve.mdindex 552163748f..fd40a5de60 100644--- a/data.reference/prompts/stages/pipeline-arc-resolve.md+++ b/data.reference/prompts/stages/pipeline-arc-resolve.md@@ -113,6 +113,34 @@ exceed `max`.{{textBudgetsJson}}```+{{#isolatedRepair}}+## Isolated repair — one record, one change++This is a **bounded single-finding repair**. Two earlier passes over the whole+residual were both reverted for leaving the plan with MORE blocking problems+than it started with, so this attempt is deliberately tiny: exactly **one**+finding, and the server will persist your response only if it is **one causal+patch**.++Hard contract for this response:++- Edit **exactly one record** — either the `arc` block, or one `characterArcs[]`+ 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 patch.+- 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.+- Pick the change that most directly removes the single finding above. If the+ finding genuinely cannot be closed by one change, return `notes` explaining+ what a coordinated repair would need and edit nothing — an honest open finding+ is better than a rewrite that trades it for two new ones.++A response that touches more than one record, or changes more than one field, is+discarded whole: it closes nothing, and the finding stays open.+{{/isolatedRepair}}+{{#hasAvoid}}## Problems a discarded earlier attempt introduced — do not author thesediff --git a/scripts/migrations/005-shape-aware-arc-prompts.js b/scripts/migrations/005-shape-aware-arc-prompts.jsindex e8bfc4afe1..cd9249e05f 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': 'ebd85d3a0b5949f16877c25ca498cce9', // post-259 (measured text budgets)+ 'pipeline-arc-resolve.md': '2349bce80e9df8caafa391a6106327b6', // post-259 (measured text budgets)};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 41a8dcd9f5..8ca78f1c3c 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': 'ebd85d3a0b5949f16877c25ca498cce9', // post-259 (measured text budgets)+ 'pipeline-arc-resolve.md': '2349bce80e9df8caafa391a6106327b6', // post-259 (measured text budgets)'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 29c0881afb..5227a09bba 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': 'ebd85d3a0b5949f16877c25ca498cce9', // post-259 (measured text budgets)+ 'pipeline-arc-resolve.md': '2349bce80e9df8caafa391a6106327b6', // post-259 (measured text budgets)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/123-arc-resolve-episode-corrections.js b/scripts/migrations/123-arc-resolve-episode-corrections.jsindex 81386be249..1c82982f1a 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': '31eca76b68f40de1b93734fe9bc9f4bb', // post-254 (character arcs)+ 'pipeline-arc-resolve.md': '2349bce80e9df8caafa391a6106327b6', // post-260 (isolated one-patch 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 0e8ef0e004..28bebcb26a 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': 'ebd85d3a0b5949f16877c25ca498cce9', // post-259 (measured text budgets)+ 'pipeline-arc-resolve.md': '2349bce80e9df8caafa391a6106327b6', // post-259 (measured text budgets)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/251-arc-resolve-field-sparsity.js b/scripts/migrations/251-arc-resolve-field-sparsity.jsindex 7213be4f38..8ecd400470 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': 'ebd85d3a0b5949f16877c25ca498cce9', // post-259 (measured text budgets)+ 'pipeline-arc-resolve.md': '2349bce80e9df8caafa391a6106327b6', // post-259 (measured text budgets)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/252-arc-resolve-avoid-list.js b/scripts/migrations/252-arc-resolve-avoid-list.jsindex 8bff61aed9..5735c74f36 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': 'ebd85d3a0b5949f16877c25ca498cce9', // post-259 (measured text budgets)+ 'pipeline-arc-resolve.md': '2349bce80e9df8caafa391a6106327b6', // post-259 (measured text budgets)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/253-arc-resolve-spine-scope.js b/scripts/migrations/253-arc-resolve-spine-scope.jsindex 76ac56ce14..c064852dfa 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': 'ebd85d3a0b5949f16877c25ca498cce9', // post-259 (measured text budgets)+ 'pipeline-arc-resolve.md': '2349bce80e9df8caafa391a6106327b6', // post-259 (measured text budgets)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/254-arc-resolve-character-arcs.js b/scripts/migrations/254-arc-resolve-character-arcs.jsindex 6864f8b886..07919f914d 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': 'ebd85d3a0b5949f16877c25ca498cce9',+ 'pipeline-arc-resolve.md': '2349bce80e9df8caafa391a6106327b6',};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.jsindex 635097d0bb..359b757a85 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': 'ebd85d3a0b5949f16877c25ca498cce9',+ 'pipeline-arc-resolve.md': '2349bce80e9df8caafa391a6106327b6',};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/259-arc-resolve-text-budgets.js b/scripts/migrations/259-arc-resolve-text-budgets.jsindex 492522b669..002da8c51c 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': 'ebd85d3a0b5949f16877c25ca498cce9',+ 'pipeline-arc-resolve.md': '2349bce80e9df8caafa391a6106327b6',};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/260-arc-resolve-isolated-repairs.js b/scripts/migrations/260-arc-resolve-isolated-repairs.jsnew file mode 100644index 0000000000..1078bf878b--- /dev/null+++ b/scripts/migrations/260-arc-resolve-isolated-repairs.js@@ -0,0 +1,33 @@+/**+ * Teach the arc-resolve prompt the bounded single-finding repair contract.+ *+ * When the arc gate's whole-set passes regress twice it falls back to resolving+ * one finding at a time. Isolating the finding never isolated the EDIT: every+ * entry in a single-finding response trivially names that finding, so the+ * resolver could still rewrite the arc and several volumes and grow the blocking+ * set exactly like the pass it was escalated from. The server now discards a+ * candidate that spans records or fields; this prompt section tells the model+ * the contract up front so the attempt has a chance of closing its finding.+ */++import { makePromptReplaceMigration } from './_lib.js';++export const ACCEPTED_OLD_MD5 = {+ 'pipeline-arc-resolve.md': ['ebd85d3a0b5949f16877c25ca498cce9'],+};++export const NEW_SHIPPED_MD5 = {+ 'pipeline-arc-resolve.md': '2349bce80e9df8caafa391a6106327b6',+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'arc-resolve isolated one-patch repairs',+ customizedHint: (filename) =>+ ` To upgrade it manually, diff data.reference/prompts/stages/${filename}\n` ++ ` against data/prompts/stages/${filename} and add the {{#isolatedRepair}} section.`,+});++export { applyMigration };+export default { up };diff --git a/scripts/migrations/260-arc-resolve-isolated-repairs.test.js b/scripts/migrations/260-arc-resolve-isolated-repairs.test.jsnew file mode 100644index 0000000000..2eb4dac5ac--- /dev/null+++ b/scripts/migrations/260-arc-resolve-isolated-repairs.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 './260-arc-resolve-isolated-repairs.js';++describe('migration 260 — arc-resolve isolated one-patch repairs', () => {+ runPromptMigrationTests({+ migration,+ applyMigration,+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ prefix: 'migration-260-arc-resolve-isolated-repairs-',+ });++ it('ships the isolated single-patch contract behind the isolatedRepair flag', () => {+ const prompt = readFileSync(+ `${repoRoot}/data.reference/prompts/stages/pipeline-arc-resolve.md`,+ 'utf8',+ );+ expect(prompt).toContain('{{#isolatedRepair}}');+ expect(prompt).toContain('{{/isolatedRepair}}');+ expect(prompt).toContain('Edit **exactly one record**');+ expect(prompt).toMatch(/make \*\*exactly one change\*\*/);+ expect(prompt).toMatch(/discarded whole/);+ });+});diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.jsindex 5d069e2eb8..aa7e07de89 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', '74d6c26548660d85fc345b2099c63b6c', '648e11352cd1565aee490de1f662bef0'],'pipeline-arc-verify.md': ['52e31abc93e3105176236fcaa5d1575a', 'ff56d8387162017e08d5d0491060ddd6', '36aa70cdfc25d7549573a4d556e7702c'],'pipeline-volume-verify.md': ['03f3c874cb80e1c98abcf03168fa7a92', 'c6ea28e972ad6e229bafb2d602b4dda3'],- 'pipeline-arc-resolve.md': ['0611db539437083621e19bb88b005e8d', '0787128babf3c4c50e2f2cdb60214030', '5b340885c6e8f8afc63424d6b5bc7eb7', '87bc5c01f1a8a97b681727a38b05edc6', '8bb134554c122d1583c479ab3010e53d', '8e348f3d1894382889f9f0ee7d5c6792', '96f73a7e90526d65ef2bb100fb1cd4bf', 'a8677bbe1eb38f871fb152a5b0fec7c6', 'cc27b4da1d1a13c35e35d1c2d6183815', '31eca76b68f40de1b93734fe9bc9f4bb', '17fbb066d7957dc2e345df1795bb0d9d'],+ 'pipeline-arc-resolve.md': ['0611db539437083621e19bb88b005e8d', '0787128babf3c4c50e2f2cdb60214030', '5b340885c6e8f8afc63424d6b5bc7eb7', '87bc5c01f1a8a97b681727a38b05edc6', '8bb134554c122d1583c479ab3010e53d', '8e348f3d1894382889f9f0ee7d5c6792', '96f73a7e90526d65ef2bb100fb1cd4bf', 'a8677bbe1eb38f871fb152a5b0fec7c6', 'cc27b4da1d1a13c35e35d1c2d6183815', '31eca76b68f40de1b93734fe9bc9f4bb', '17fbb066d7957dc2e345df1795bb0d9d', 'ebd85d3a0b5949f16877c25ca498cce9'],'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': '5ed760caaf3cf88916ec28b220e2f590','pipeline-arc-verify.md': '83347e7d923580a3062033ab39b3c14b','pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940',- 'pipeline-arc-resolve.md': 'ebd85d3a0b5949f16877c25ca498cce9',+ 'pipeline-arc-resolve.md': '2349bce80e9df8caafa391a6106327b6','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 ab96b56a51..116406210a 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -1545,6 +1545,291 @@ describe('arcPlanner — resolveVerifyIssues', () => {});});+// The arc gate's per-finding fallback (#3780) sends ONE finding, but that alone+// never bounded the EDIT: every entry in a single-finding response trivially+// names that finding, so `selectFindingKeyedEdits` passed whole-arc rewrites and+// each "isolated" attempt regressed the blocker set exactly like the whole-set+// pass it escalated from. `isolated` mode requires the response to BE one causal+// patch and discards it before persistence otherwise.+describe('arcPlanner — resolveVerifyIssues (isolated single-finding repairs)', () => {+ const finding = [{ severity: 'high', location: 'volume 1', problem: 'volume 1 promises a payoff it never lands', suggestion: 'name the payoff' }];++ beforeEach(() => {+ fileStore.clear();+ uuidCounter = 0;+ stageRunnerSpy = undefined;+ });++ async function setupTwoVolumeSeries() {+ const s = await setupSeries();+ await seriesSvc.updateSeries(s.id, {+ arc: { logline: 'L', summary: 'The choir wakes. The city answers.', themes: ['legacy'], protagonistArc: 'From surveyor to founder.' },+ });+ const v1 = await seasonsSvc.createSeason(s.id, { title: 'Vol 1', episodeCountTarget: 8, synopsis: 'The foundry falls silent. Nobody says why.' });+ const v2 = await seasonsSvc.createSeason(s.id, { title: 'Vol 2', episodeCountTarget: 8, synopsis: 'The diaspora scatters. A signal follows them.' });+ return { s, v1, v2 };+ }++ it('discards an isolated candidate that edits more than one record, persisting nothing', async () => {+ const { s, v1, v2 } = await setupTwoVolumeSeries();+ stageRunnerSpy = vi.fn(async () => ({+ content: {+ patchMode: 'exact-text-v1',+ arc: { resolves: ['f1'], summaryEdits: [{ find: 'The city answers.', replace: 'The city answers in kind.' }] },+ seasons: [+ { resolves: ['f1'], id: v1.id, number: v1.number, title: 'Vol 1', synopsisEdits: [{ find: 'Nobody says why.', replace: 'Nobody says why until the ledger surfaces.' }] },+ { resolves: ['f1'], id: v2.id, number: v2.number, title: 'Vol 2', synopsisEdits: [{ find: 'A signal follows them.', replace: 'A signal follows them home.' }] },+ ],+ notes: '',+ },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ const out = await planner.resolveVerifyIssues(s.id, { findings: finding, isolated: true });++ expect(out.applied).toBe(false);+ expect(out.reason).toMatch(/edits 3 records/);+ // Nothing reached the store — the gate has no rewrite to roll back and no+ // reason to spend a verification round discovering that.+ const after = await seriesSvc.getSeries(s.id);+ expect(after.arc.summary).toBe('The choir wakes. The city answers.');+ expect(after.seasons.map((v) => v.synopsis)).toEqual([+ 'The foundry falls silent. Nobody says why.',+ 'The diaspora scatters. A signal follows them.',+ ]);+ });++ it('discards an isolated candidate that changes two fields on one record', async () => {+ const { s, v1 } = await setupTwoVolumeSeries();+ stageRunnerSpy = vi.fn(async () => ({+ content: {+ patchMode: 'exact-text-v1',+ seasons: [{+ resolves: ['f1'],+ id: v1.id,+ number: v1.number,+ title: 'Vol 1',+ logline: 'a brand new logline',+ synopsisEdits: [{ find: 'Nobody says why.', replace: 'Nobody says why until the ledger surfaces.' }],+ }],+ notes: '',+ },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ const out = await planner.resolveVerifyIssues(s.id, { findings: finding, isolated: true });++ expect(out.applied).toBe(false);+ expect(out.reason).toMatch(/changes 2 fields on volume 1/);+ const after = await seriesSvc.getSeries(s.id);+ expect(after.seasons[0].synopsis).toBe('The foundry falls silent. Nobody says why.');+ expect(after.seasons[0].logline).toBe('');+ });++ it('discards an isolated candidate that would add a volume', async () => {+ const { s } = await setupTwoVolumeSeries();+ stageRunnerSpy = vi.fn(async () => ({+ content: {+ patchMode: 'exact-text-v1',+ seasons: [{ resolves: ['f1'], number: 3, title: 'Vol 3', synopsis: 'The payoff gets its own volume.' }],+ notes: '',+ },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ const out = await planner.resolveVerifyIssues(s.id, { findings: finding, isolated: true });++ expect(out.applied).toBe(false);+ expect(out.reason).toMatch(/add a new volume/);+ expect((await seriesSvc.getSeries(s.id)).seasons).toHaveLength(2);+ });++ it('keeps a one-patch candidate, ignoring echoed identity fields that change nothing', async () => {+ const { s, v1 } = await setupTwoVolumeSeries();+ stageRunnerSpy = vi.fn(async () => ({+ content: {+ patchMode: 'exact-text-v1',+ seasons: [{+ // id / number / title / episodeCountTarget are echoed exactly as+ // stored — the prompt asks for them, so "present" must not read as+ // "changed" or every real one-patch response would be discarded.+ resolves: ['f1'],+ id: v1.id,+ number: v1.number,+ title: 'Vol 1',+ episodeCountTarget: 8,+ synopsisEdits: [{ find: 'Nobody says why.', replace: 'Nobody says why until the ledger surfaces.' }],+ }],+ notes: '',+ },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ const out = await planner.resolveVerifyIssues(s.id, { findings: finding, isolated: true });++ expect(out.applied).toBe(true);+ expect(out.reason).toBeUndefined();+ const after = await seriesSvc.getSeries(s.id);+ expect(after.seasons[0].synopsis).toBe('The foundry falls silent. Nobody says why until the ledger surfaces.');+ expect(after.seasons[1].synopsis).toBe('The diaspora scatters. A signal follows them.');+ });++ it('discards a candidate that only echoes stored values back', async () => {+ const { s, v1 } = await setupTwoVolumeSeries();+ stageRunnerSpy = vi.fn(async () => ({+ content: {+ patchMode: 'exact-text-v1',+ seasons: [{ resolves: ['f1'], id: v1.id, number: v1.number, title: 'Vol 1', episodeCountTarget: 8 }],+ notes: 'nothing to change here',+ },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ const out = await planner.resolveVerifyIssues(s.id, { findings: finding, isolated: true });++ expect(out.applied).toBe(false);+ expect(out.reason).toMatch(/changed nothing/);+ expect(out.notes).toBe('nothing to change here');+ });++ it('tells the prompt it is an isolated repair, and does not on a whole-set pass', async () => {+ const { s, v1 } = await setupTwoVolumeSeries();+ stageRunnerSpy = vi.fn(async () => ({+ content: {+ patchMode: 'exact-text-v1',+ seasons: [{ resolves: ['f1'], id: v1.id, synopsisEdits: [{ find: 'Nobody says why.', replace: 'Nobody says why yet.' }] }],+ notes: '',+ },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ await planner.resolveVerifyIssues(s.id, { findings: finding, isolated: true });+ expect(stageRunnerSpy.mock.calls[0][1].isolatedRepair).toBe(true);++ await planner.resolveVerifyIssues(s.id, { findings: finding });+ expect(stageRunnerSpy.mock.calls[1][1].isolatedRepair).toBe(false);+ });++ // The constrained mode is the bounded FALLBACK only: coordinated cross-record+ // repairs stay available to the whole-set and corrective passes, which is+ // where a genuine multi-record continuity finding gets fixed.+ it('leaves the whole-set pass free to edit several records', async () => {+ const { s, v1, v2 } = await setupTwoVolumeSeries();+ stageRunnerSpy = vi.fn(async () => ({+ content: {+ patchMode: 'exact-text-v1',+ arc: { resolves: ['f1'], summaryEdits: [{ find: 'The city answers.', replace: 'The city answers in kind.' }] },+ seasons: [+ { resolves: ['f1'], id: v1.id, synopsisEdits: [{ find: 'Nobody says why.', replace: 'Nobody says why until the ledger surfaces.' }] },+ { resolves: ['f1'], id: v2.id, synopsisEdits: [{ find: 'A signal follows them.', replace: 'A signal follows them home.' }] },+ ],+ notes: '',+ },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ const out = await planner.resolveVerifyIssues(s.id, { findings: finding });++ expect(out.applied).toBe(true);+ const after = await seriesSvc.getSeries(s.id);+ expect(after.arc.summary).toBe('The choir wakes. The city answers in kind.');+ expect(after.seasons[0].synopsis).toContain('until the ledger surfaces');+ expect(after.seasons[1].synopsis).toContain('follows them home');+ });+});++describe('isolatedCandidateRejection (pure one-patch bound)', () => {+ const series = {+ arc: { logline: 'L', summary: 'One. Two.', themes: ['a'], protagonistArc: 'P' },+ seasons: [{ id: 'sea-1', number: 1, title: 'Vol 1', synopsis: 'Alpha. Beta.', endingHook: 'hook', episodeCountTarget: 8, themes: [] }],+ characterArcs: [{+ characterId: 'chr-11111111-1111-4111-8111-111111111111',+ characterName: 'Wren',+ want: 'the ledger',+ need: 'to be believed',+ startState: 'alone',+ endState: 'trusted',+ transitions: [{ id: 'trn-1', kind: 'decision', label: 'burns the ledger', atIssue: 4, atSceneAnchor: '', note: '' }],+ }],+ };+ // Only the four edit lists — the checker reads the selected edits, never the+ // drop counters `selectFindingKeyedEdits` reports alongside them.+ const noEdits = { arc: null, characterArcs: [], seasons: [], episodes: [] };+ const rejection = (edits, exactTextMode = true) => planner.isolatedCandidateRejection(+ { ...noEdits, ...edits },+ { exactTextMode, series },+ );++ it('accepts one exact-text replacement on one volume', () => {+ expect(rejection({ seasons: [{ id: 'sea-1', synopsisEdits: [{ find: 'Beta.', replace: 'Beta rewritten.' }] }] })).toBeNull();+ });++ it('accepts one short scalar change', () => {+ expect(rejection({ seasons: [{ id: 'sea-1', episodeCountTarget: 9 }] })).toBeNull();+ });++ it('accepts one existing character-transition patch, however many of its fields move', () => {+ expect(rejection({+ characterArcs: [{+ characterId: 'chr-11111111-1111-4111-8111-111111111111',+ transitions: [{ id: 'trn-1', label: 'spares the ledger', atIssue: 5 }],+ }],+ })).toBeNull();+ });++ it('rejects two replacements even inside one field', () => {+ expect(rejection({+ seasons: [{ id: 'sea-1', synopsisEdits: [{ find: 'Alpha.', replace: 'Alpha!' }, { find: 'Beta.', replace: 'Beta!' }] }],+ })).toMatch(/changes 2 fields/);+ });++ it('does not count the long-prose spelling the applier ignores', () => {+ // Under exact-text mode a directly-returned `synopsis` is never persisted,+ // so counting it would reject a candidate over an edit that was a no-op.+ expect(rejection({+ seasons: [{ id: 'sea-1', synopsis: 'wholesale rewrite', synopsisEdits: [{ find: 'Beta.', replace: 'Beta rewritten.' }] }],+ })).toBeNull();+ // Outside exact-text mode the same field IS the change.+ expect(rejection({ seasons: [{ id: 'sea-1', synopsis: 'wholesale rewrite' }] }, false)).toBeNull();+ });++ it('counts what the exact-text applier would land, not what was asked for', () => {+ // A replacement whose anchor isn't in the stored text is skipped by+ // applyExactTextEdits, so it changes nothing — counting it would discard a+ // candidate whose persisted effect was exactly one change.+ expect(rejection({+ seasons: [{+ id: 'sea-1',+ synopsisEdits: [+ { find: 'Beta.', replace: 'Beta rewritten.' },+ { find: 'text that is not in the synopsis', replace: 'never lands' },+ ],+ }],+ })).toBeNull();+ // …and a candidate whose every replacement is unanchored lands nothing at all.+ expect(rejection({+ seasons: [{ id: 'sea-1', synopsisEdits: [{ find: 'not present either', replace: 'x' }] }],+ })).toMatch(/changed nothing/);+ });++ it('does not count edits the appliers would discard anyway', () => {+ expect(rejection({+ characterArcs: [+ { characterName: 'Nobody', want: 'invented' }, // unmatched arc — never minted+ {+ characterId: 'chr-11111111-1111-4111-8111-111111111111',+ transitions: [+ { label: 'no id, dropped by the merge' },+ { id: 'trn-missing', label: 'unmatched id, dropped by the merge' },+ { id: 'trn-1', label: 'burns the ledger' }, // identical to stored+ ],+ want: 'the ledger archive',+ },+ ],+ })).toBeNull();+ });+});+describe('selectFindingKeyedEdits (pure resolve-edit filter, #3724)', () => {const findings = [{ problem: 'a' }, { problem: 'b' }];const select = (content) => planner.selectFindingKeyedEdits(content, findings);diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.jsindex 3158fc0322..6944569291 100644--- a/server/services/pipeline/arcPlanner/arcCore.js+++ b/server/services/pipeline/arcPlanner/arcCore.js@@ -508,6 +508,147 @@ export function applyExactTextEdits(current, rawEdits, maxLength) {return { value, applied, rejected };}+// Two stored values are the same edit-wise. `undefined` and `null` are one+// value here: an omitted field and an explicit null both mean "no change I can+// count", and the appliers treat them identically.+const sameStored = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);++// The fields a resolve response can change on the arc / on a volume — the same+// surface the two appliers below spread (`sanitizeArc` at the arc, the season+// patch inside `resolveVerifyIssues`), restated here because those do per-field+// coercion rather than list iteration. THEY MOVE TOGETHER: a newly patchable+// field the appliers accept but this list omits is a change the isolated bound+// cannot see. Long prose is paired `[direct, editsKey, limit]` because under+// `exact-text-v1` it lands ONLY through the `*Edits` array and a+// directly-returned string is ignored (and vice versa) — counting the ignored+// spelling would reject a candidate over an edit that was never going to be+// persisted.+const ARC_SHORT_FIELDS = Object.freeze(['logline', 'themes', 'shape', 'foreshadowing']);+const ARC_LONG_FIELDS = Object.freeze([+ ['summary', 'summaryEdits', ARC_LIMITS.SUMMARY_MAX],+ ['protagonistArc', 'protagonistArcEdits', ARC_LIMITS.PROTAGONIST_ARC_MAX],+]);+const SEASON_SHORT_FIELDS = Object.freeze(['title', 'number', 'logline', 'episodeCountTarget', 'themes']);+const SEASON_LONG_FIELDS = Object.freeze([+ ['synopsis', 'synopsisEdits', ARC_LIMITS.SEASON_SYNOPSIS_MAX],+ ['endingHook', 'endingHookEdits', ARC_LIMITS.SEASON_ENDING_HOOK_MAX],+]);++// How many stored values a patch would actually change. Echoed fields that+// already match the record do not count: the resolve prompt asks for `id` and+// `number` to be repeated, so "field present" is not "field changed". Exact-text+// replacements are counted by running the real applier — one `{find, replace}`+// pair is one causal change, and an anchor `applyExactTextEdits` would reject+// (missing, ambiguous, over-limit) is none, so the count is the patch's+// persisted effect rather than the size of what the model asked for.+function countFieldChanges(patch, current, { shortFields, longFields = [], exactTextMode = false }) {+ let changes = 0;+ for (const field of shortFields) {+ if (patch?.[field] === undefined) continue;+ if (!sameStored(patch[field], current?.[field])) changes += 1;+ }+ for (const [direct, editsKey, limit] of longFields) {+ if (exactTextMode) {+ changes += applyExactTextEdits(current?.[direct] || '', patch?.[editsKey], limit).applied;+ } else if (typeof patch?.[direct] === 'string' && !sameStored(patch[direct], current?.[direct] ?? '')) {+ changes += 1;+ }+ }+ return changes;+}++// Same accounting one altitude down, for a per-character arc patch: changed+// top-level fields plus ONE per patched existing transition (a transition is the+// causal unit — correcting its label and its issue anchor together is one+// milestone repair). Transitions the merge would discard anyway (no `id`, or an+// id no stored transition carries) are not changes.+function countCharacterArcChanges(patch, current) {+ let changes = countFieldChanges(patch, current, { shortFields: CHARACTER_ARC_PATCH_FIELDS });+ const byId = new Map((current?.transitions || []).map((t) => [t.id, t]));+ for (const raw of (Array.isArray(patch?.transitions) ? patch.transitions : [])) {+ if (!raw || typeof raw !== 'object' || typeof raw.id !== 'string') continue;+ const existing = byId.get(raw.id);+ if (!existing) continue;+ if (raw.delete === true) { changes += 1; continue; }+ if (TRANSITION_PATCH_FIELDS.some((f) => raw[f] !== undefined && !sameStored(raw[f], existing[f]))) changes += 1;+ }+ return changes;+}++/**+ * Decide whether an isolated (single-finding) resolve candidate is bounded+ * enough to persist. Pure. Returns a short rejection reason, or null when the+ * candidate is exactly ONE causal patch: one owner record, one changed field on+ * it — one exact-text replacement, one short scalar, or one existing+ * character-transition patch.+ *+ * This is what makes the arc gate's per-finding fallback (#3780) bounded.+ * Isolating the FINDING never isolated the EDIT: every entry in a single-finding+ * response trivially names that finding, so `selectFindingKeyedEdits` passed+ * whole-arc rewrites and each "isolated" attempt regressed the blocking set+ * exactly like the whole-set pass it escalated from.+ *+ * Checked BEFORE anything is written, so an over-reaching candidate costs its+ * own resolve call and nothing else: no rewrite to undo, and no verification+ * round billed to discover that the rewrite was worse. The post-apply verifier+ * and rollback in the gate stay exactly as they are — this is a narrower net in+ * front of them, not a replacement for them.+ *+ * Counting is against the STORED record, not the response's shape: an echoed+ * `id`/`number`/title is not a change, and an edit the appliers would discard+ * (an unmatched character arc, a transition with no id, an unanchored exact-text+ * 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 } = {}) {+ const touched = [];+ if (edits.arc) {+ const changes = countFieldChanges(edits.arc, series.arc || {}, {+ shortFields: ARC_SHORT_FIELDS, longFields: ARC_LONG_FIELDS, exactTextMode,+ });+ if (changes) touched.push({ label: 'the arc', changes });+ }+ if (edits.characterArcs.length) {+ const arcByKey = new Map(sanitizeCharacterArcList(series.characterArcs).map((a) => [characterArcKey(a), a]));+ for (const patch of edits.characterArcs) {+ // An unmatched key mints nothing (mergeCharacterArcPatches drops it), so+ // it is not a record this candidate touches.+ const existing = arcByKey.get(characterArcKey(patch));+ if (!existing) continue;+ const changes = countCharacterArcChanges(patch, existing);+ if (changes) touched.push({ label: `character arc ${existing.characterId || 'unkeyed'}`, changes });+ }+ }+ const matched = matchedSeasons || matchProposedSeasons(series.seasons, edits.seasons);+ for (let idx = 0; idx < edits.seasons.length; idx += 1) {+ const existing = matched[idx];+ // An unmatched volume proposal MINTS one. A new volume is never the minimal+ // causal patch for a single finding, and it is the one edit here that can't+ // be undone by putting a field back.+ if (!existing) return 'it would add a new volume instead of patching one';+ const changes = countFieldChanges(edits.seasons[idx], existing, {+ shortFields: SEASON_SHORT_FIELDS, longFields: SEASON_LONG_FIELDS, exactTextMode,+ });+ if (changes) touched.push({ label: `volume ${existing.number ?? '?'}`, changes });+ }+ // Shaped by the applier's own admission rule, so an entry `applyEpisodeResolutions`+ // 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 });+ }+ if (touched.length === 0) return 'it changed nothing this gate would persist';+ if (touched.length > 1) {+ return `it edits ${touched.length} records (${touched.map((t) => t.label).join(', ')}) — an isolated repair may change only one`;+ }+ const [only] = touched;+ if (only.changes > 1) {+ return `it changes ${only.changes} fields on ${only.label} — an isolated repair may change only one`;+ }+ return null;+}++// 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@@ -527,6 +668,7 @@ export function applyExactTextEdits(current, rawEdits, maxLength) {// and actually judges them.export async function resolveVerifyIssues(seriesId, options = {}) {const spineOnly = options.spineOnly === true;+ const isolated = options.isolated === true;const series = await getSeries(seriesId);if (!series.arc) {throw new ServerError(@@ -563,7 +705,7 @@ export async function resolveVerifyIssues(seriesId, options = {}) {// `options.avoid` carries the findings a reverted earlier attempt at these// same findings authored, so a corrective pass is told what NOT to re-create// instead of re-running the identical prompt and regressing identically.- const ctx = await buildResolveContext(series, findings, world, { avoid: options.avoid, spineOnly });+ const ctx = await buildResolveContext(series, findings, world, { avoid: options.avoid, spineOnly, isolated });const { content, runId, providerId, model } = await runStagedLLM('pipeline-arc-resolve',ctx,@@ -602,6 +744,44 @@ export async function resolveVerifyIssues(seriesId, options = {}) {console.log(`⚠️ arc-resolve: discarded ${edits.episodesOutOfScope} episode edit(s) — the arc-spine gate resolves at arc/volume scope only`);}+ // What every return below carries regardless of whether the candidate landed.+ const runMeta = {+ notes: typeof content?.notes === 'string' ? content.notes.trim().slice(0, 2000) : '',+ findings,+ runId,+ providerId,+ model,+ };++ // Which existing volume each proposal rewrites. Resolved once: the isolated+ // check needs it to tell a patch from a mint, and the season merge below needs+ // the same answer.+ const matchedExisting = matchProposedSeasons(series.seasons, edits.seasons);++ // The isolated fallback's candidate is judged BEFORE anything is written: a+ // candidate that spans records or fields is discarded whole, so it costs its+ // own resolve call and neither a rewrite to undo nor a verification round to+ // discover the damage. Reported as a plain unapplied result — the shape the+ // gate already reads for "nothing was written" — with the bound it broke as+ // the reason. The post-apply verifier and rollback still judge everything that+ // DOES get through.+ const isolationRejected = isolated+ ? isolatedCandidateRejection(edits, { exactTextMode, series, matchedSeasons: matchedExisting })+ : null;+ if (isolationRejected) {+ console.log(`⚠️ arc-resolve: discarded an isolated repair candidate — ${isolationRejected}`);+ return {+ series,+ applied: false,+ reason: isolationRejected,+ patchMode: exactTextMode ? 'exact-text-v1' : null,+ rejectedExactEdits: 0,+ episodesResolved: [],+ ...runMeta,+ };+ }++const arcSummary = exactTextMode? applyExactTextEdits(series.arc.summary || '', edits.arc?.summaryEdits, ARC_LIMITS.SUMMARY_MAX): { value: edits.arc?.summary || series.arc.summary || '', applied: 0, rejected: 0 };@@ -638,14 +818,14 @@ export async function resolveVerifyIssues(seriesId, options = {}) {// 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- // `preserveDroppedSeasons` on (the autopilot's unlock-for-run mode) the- // original was then re-inserted alongside the mint — so every auto-resolve- // 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);+ // `matchedExisting` (resolved above) pairs each proposal with the existing+ // record it rewrites 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 `preserveDroppedSeasons` on (the+ // autopilot's unlock-for-run mode) the original was then re-inserted alongside+ // the mint — so every auto-resolve 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.// 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();@@ -707,7 +887,7 @@ export async function resolveVerifyIssues(seriesId, options = {}) {: { series };const characterArcs = mergeCharacterArcPatches(updated.characterArcs, edits.characterArcs);- const characterArcsChanged = JSON.stringify(characterArcs) !== JSON.stringify(updated.characterArcs || []);+ const characterArcsChanged = !sameStored(characterArcs, updated.characterArcs || []);const resolvedSeries = characterArcsChanged? await updateSeries(seriesId, { characterArcs }): updated;@@ -730,18 +910,13 @@ export async function resolveVerifyIssues(seriesId, options = {}) {console.log(`⚠️ arc-resolve: response made no applicable change after ${rejectedExactEdits} exact text edit(s) were rejected`);}- const notes = typeof content?.notes === 'string' ? content.notes.trim().slice(0, 2000) : '';return {series: resolvedSeries,applied,patchMode: exactTextMode ? 'exact-text-v1' : null,rejectedExactEdits,- notes,- findings,episodesResolved,- runId,- providerId,- model,+ ...runMeta,};}diff --git a/server/services/pipeline/arcPlanner/context.js b/server/services/pipeline/arcPlanner/context.jsindex d113c8f022..250b4635a1 100644--- a/server/services/pipeline/arcPlanner/context.js+++ b/server/services/pipeline/arcPlanner/context.js@@ -736,6 +736,11 @@ export async function buildResolveContext(series, findings, preloadedWorld, opti...ctx,characterArcsJson: JSON.stringify(series.characterArcs || [], null, 2),findingsJson: JSON.stringify(stampFindingIds(findings), null, 2),+ // The bounded per-finding fallback: the prompt is told the one-record,+ // one-field contract the server will enforce on this response, so an+ // over-reaching candidate is discouraged rather than only discarded after+ // the provider call is already paid for.+ isolatedRepair: options.isolated === true,hasAvoid: avoid.length > 0,avoidJson: JSON.stringify(avoid, null, 2),textBudgetsJson: JSON.stringify({diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex de5e8e2842..c3f9793ea9 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -3047,9 +3047,12 @@ describe('autopilot conductor', () => {// and tries its two findings one at a time — both are rejected, so it stops.expect(arcSpies.verifyArc).toHaveBeenCalledTimes(6);expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(5);- // Each isolated attempt snapshots so it can be undone on its own; the- // corrective pass still rewinds to the checkpoint it already holds.- expect(arcSpies.snapshotArcState).toHaveBeenCalledTimes(4);+ // The isolation pass snapshots ONCE and holds it: a rejected attempt is+ // restored to exactly that state, so re-reading the series + every episode+ // to capture an identical snapshot would be pure I/O. Only an accepted patch+ // (none here) moves the store on and forces a fresh one. The corrective pass+ // still rewinds to the checkpoint it already holds.+ expect(arcSpies.snapshotArcState).toHaveBeenCalledTimes(3);expect(arcSpies.restoreArcState).toHaveBeenCalledWith(seriesId, bestSnapshot);const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;expect(last?.pauseKind).toBe('regression');@@ -3188,6 +3191,52 @@ describe('autopilot conductor', () => {});});+ it('spends no verification on an isolated candidate the resolver discarded before persistence', async () => {+ // Isolating the FINDING never isolated the EDIT: a single-finding response's+ // entries all name that finding, so the resolver could still rewrite the arc+ // and every volume — which is how each "isolated" attempt on 2026-08-12 grew+ // the blocker set from 2 to 4 and then to 7. The resolver now rejects an+ // over-broad candidate before writing anything, and this gate must read that+ // as a spent attempt with nothing to undo and nothing new to verify.+ const holes = (n, prefix) => Array.from({ length: n }, (_, i) => ({+ severity: 'high', problem: `${prefix} ${i}`, location: `V${i + 1}`,+ }));+ arcSpies.verifyArc.mockReset();+ [holes(2, 'best'), holes(4, 'regressed'), holes(4, 'regressed again')]+ .forEach((issues) => arcSpies.verifyArc.mockImplementationOnce(async () => ({ issues })));+ arcSpies.resolveVerifyIssues.mockReset();+ arcSpies.resolveVerifyIssues.mockImplementation(async (_seriesId, opts) => (opts?.isolated+ ? { applied: false, reason: 'it edits 3 records (the arc, volume 1, volume 2) — an isolated repair may change only one', runId: 'arc-isolated-reject' }+ : { applied: true, runId: 'arc-whole-set' }));++ const { seriesId } = await seedComplete();+ const frames = [];+ const handler = (p) => frames.push(p);+ autopilot.autopilotEvents.on(seriesId, handler);+ await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 6, maxArcIsolationAttempts: 2 });+ await waitFor(runFinished(seriesId));+ autopilot.autopilotEvents.off(seriesId, handler);++ // Both isolated attempts ran in the constrained mode and were discarded+ // before persistence, so the gate bought no verification for either — three+ // verifies total, one per whole-set round.+ const isolatedCalls = arcSpies.resolveVerifyIssues.mock.calls.filter(([, o]) => o?.isolated);+ expect(isolatedCalls).toHaveLength(2);+ expect(isolatedCalls[0][1].findings).toHaveLength(1);+ expect(arcSpies.verifyArc).toHaveBeenCalledTimes(3);+ // Two whole-round rollbacks only — a candidate that never landed has nothing+ // to restore.+ expect(arcSpies.restoreArcState).toHaveBeenCalledTimes(2);+ const isolated = frames.filter((f) => f.type === 'resolve:isolate');+ expect(isolated).toHaveLength(2);+ expect(isolated[0]).toMatchObject({ kept: false, before: 2, after: 2, episodesEdited: 0 });+ expect(isolated[0].reason).toMatch(/edits 3 records/);+ // Nothing was retained, so the gate still pauses on the best verified state.+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;+ expect(last?.pauseKind).toBe('regression');+ expect(last?.residualFindings).toEqual(holes(2, 'best'));+ });+it('does not isolate a single-finding residual (that is the corrective pass again)', async () => {// Isolating a one-finding residual re-issues the exact call the corrective// pass just made — same finding, same avoid list — so the gate pauses ratherdiff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.jsindex 3b2734e5c2..c68250d107 100644--- a/server/services/pipeline/seriesAutopilot/childRuns.js+++ b/server/services/pipeline/seriesAutopilot/childRuns.js@@ -72,11 +72,12 @@ function arcResolveRetryBudget(record) {// accounting, at all three call sites (the round's resolve, the corrective// retry, and each isolated single-finding attempt). Open-coding it a third time// is how `spineOnly` (#3789) came to need patching into every copy.-async function resolveArcFindings(seriesId, record, { findings, avoid, spineOnly }) {+async function resolveArcFindings(seriesId, record, { findings, avoid, spineOnly, isolated = false }) {const resolved = await resolveVerifyIssues(seriesId, {findings,avoid,spineOnly,+ isolated,...providerOverrideOpts(record),...seasonPreserveOpts(record),});@@ -200,6 +201,12 @@ async function verifyArcBlocking(seriesId, record, { spineOnly }) {* without growing or worsening the set, and a poisoned finding costs only its* own attempt instead of its neighbours' repairs.*+ * Each resolve runs in the resolver's `isolated` mode, because isolating the+ * FINDING was never enough to isolate the EDIT — see `isolatedCandidateRejection`+ * in arcPlanner/arcCore.js. A candidate it discards comes back unapplied, which+ * this loop reads as an attempt needing neither a rollback (nothing was written)+ * nor a verification round (the blocking set cannot have moved).+ ** Bounded by `attemptsLeft` and budget-gated per attempt like every other* resolve. Returns `{ accepted, attempts, verified }` — `verified` being the* full verification of the state now standing in the store, which the caller@@ -222,6 +229,12 @@ async function isolateArcFindings(seriesId, record, { scope, round, spineOnly, blet standing = null;let accepted = 0;let attempts = 0;+ // The store's state as of the last attempt that could have changed it, held+ // across attempts: a rejected candidate either never reached the store or was+ // restored to exactly this, so re-reading the series + every episode to+ // capture an identical snapshot is pure I/O. Dropped after an accepted patch,+ // which is the only thing that moves the store on.+ let snapshot = null;const blocking = () => standing?.blocking ?? baseline;for (const target of baseline) {if (attempts >= attemptsLeft) break;@@ -233,14 +246,44 @@ async function isolateArcFindings(seriesId, record, { scope, round, spineOnly, bif (beforeResolve) return { accepted, attempts, verified: standing, outcome: beforeResolve };attempts += 1;const before = blocking().length;- const snapshot = await snapshotArcState(seriesId);+ // The finding this attempt is spent on, as the telemetry names it: the+ // frame reports it verbatim (blank when the verifier gave no location), the+ // model-outcome record falls back to the gate's scope so a per-target+ // performance history is never keyed on an empty string.+ const targetLabel = typeof target.location === 'string' ? target.location : null;+ if (!snapshot) snapshot = await snapshotArcState(seriesId);// Recomputed per target: earlier attempts in this same pass have banked// their rejections by now. Everything still standing is an active repair// target for this pass, so the whole set — not just `target` — is what the// avoid list is filtered against; the resolver is never told to both fix// and avoid the same finding.const avoid = bank.avoid([], blocking());- const resolved = await resolveArcFindings(seriesId, record, { findings: [target], avoid, spineOnly });+ const resolved = await resolveArcFindings(seriesId, record, {+ findings: [target], avoid, spineOnly, isolated: true,+ });+ // The resolver applied nothing — for an isolated attempt that means the+ // candidate was too broad to BE one (see `isolatedCandidateRejection`) and+ // was discarded before it touched the store. Nothing was written, so there+ // is nothing to restore and — more to the point — nothing to verify:+ // billing a full verification round here would buy back the blocking set+ // this attempt already holds. Nothing to bank as discarded evidence either:+ // no rewrite was ever verified, so there are no authored problems to warn+ // the next attempt about.+ if (resolved?.applied === false) {+ await recordArcResolveOutcome(+ { blocking: blocking(), runIds: arcResolveRunIds(resolved) },+ record,+ { outcome: 'rejected', after: blocking(), target: targetLabel ?? scope },+ );+ broadcast(seriesId, {+ type: 'resolve:isolate', scope, round, attempt: attempts,+ target: targetLabel ?? '',+ before, after: before, kept: false, episodesEdited: 0,+ reason: resolved.reason || 'the resolver applied nothing',+ rejectedExactEdits: resolved.rejectedExactEdits || 0,+ });+ continue;+ }const verified = await verifyArcBlocking(seriesId, record, { spineOnly });if (verified.outcome) {// The run is ending mid-attempt, so this patch can never be judged. Put@@ -256,12 +299,15 @@ async function isolateArcFindings(seriesId, record, { scope, round, spineOnly, b{outcome: kept ? 'accepted' : 'rejected',after: verified.blocking,- target: typeof target.location === 'string' ? target.location : scope,+ target: targetLabel ?? scope,},);if (kept) {accepted += 1;standing = verified;+ // The store has moved past the held snapshot — the next attempt has to+ // capture the state this patch left behind, not the one before it.+ snapshot = null;} else {await restoreArcState(seriesId, snapshot);// The verified consequence of a rewrite the gate just threw away — the@@ -272,7 +318,7 @@ async function isolateArcFindings(seriesId, record, { scope, round, spineOnly, b}broadcast(seriesId, {type: 'resolve:isolate', scope, round, attempt: attempts,- target: typeof target.location === 'string' ? target.location : '',+ target: targetLabel ?? '',before, after: verified.blocking.length, kept, episodesEdited: editedCount(resolved),});}