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: retry a reverted arc auto-resolve round instead of stalling the run
[._.]/ Adam Eivyfe2d851053dd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ca4c9acf4c..eec160a0a6 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -22,6 +22,8 @@## Fixed+- **A reverted arc auto-resolve round no longer ends the whole run on its first bad attempt.** Arc verification correctly refuses to keep a resolver rewrite that raises the blocking-finding count — but it then stopped the run and asked you to fix the arc by hand, and resuming just re-ran the identical prompt against the identical restored plan, so the gate could regress the same way forever. (Observed on a spine check that went in with 3 blockers, came back with 6, and paused on round 2 of 3.) The revert still happens exactly as before; what follows it is now one bounded corrective pass. The resolver is re-run from the restored best plan, handed the findings that plan actually has, plus — this is the new information — the problems its own discarded attempt just authored, named explicitly as the failure mode to avoid rather than as more work to close. Only when that second attempt also regresses does the gate pause for review, with the same best-state residual and discarded set it reported before. A retry is never spent on the final round (nothing would verify it), it is budget-checked and billed like any other resolve, and `maxArcResolveRetries: 0` restores the previous stop-on-first-regression behavior per run. The live status line now distinguishes a rollback that is retrying from one that is about to pause.+- **A provider outage no longer hands a CoS task's model pin to a provider that can't run it.** A task pinned to Antigravity with `gemini-3.6-flash` hit an auth outage on that provider; the fallback chain correctly swapped it onto the Claude CLI but carried the Antigravity model id along, so every retry spawned `claude --model gemini-3.6-flash` and died in ~1.5s ("There's an issue with the selected model") until the task exhausted its retries and blocked. The pass-through exemption that let it through is deliberate — it exists so an explicit pin isn't silently downgraded to the provider's heaviest default just because the provider's `models` list spells an alias differently — but it only makes sense on the provider the pin was chosen *for*. A `metadata.model` pin is provider-scoped (the task form picks a provider, then a model from that provider's catalog), so a fallback swap now drops it back to the new provider's own default unless that provider actually lists it, logging the substitution rather than doing it silently. A swap between siblings that both serve the pinned id (claude-code ↔ claude-code-tui) still keeps it, and a run with no swap at all is untouched. The check also covers a fallback provider that enumerates no models, which the existing model-list validation could not inspect at all.- **The Claude CLI's own model rejection is now a recognized, actionable failure.** "There's an issue with the selected model (…)" is printed by the CLI at startup, before any API call, so it carries no `API Error: 4NN` token and matched none of the model-error patterns. It landed in the `unknown` bucket with "Error did not match known patterns" — which autoFixer maps to Tier 4 (escalate), so a task with a bad model id burned all three retries against an id that could never work and then spent an agent run on an investigation task. It now classifies as `model-not-found` with the rejected id extracted from the message, putting it in Tier 1 (config/env) where a model correction belongs. Promoted to a structured `provider`-origin signal, since the full banner with the parenthesised id and the `--model` hint is CLI text rather than something a task's own output prints in passing.- **Stopping the CoS Runner no longer burns through queued agent tasks.** `portos-cos` is a separate PM2 app you can stop from the Apps page, and while runner mode is active it owns every agent process — but the spawn path dispatched into it regardless and recorded the resulting rejection as a task failure. The CLI arm charged a retry each time (a runner left off overnight walked every queued task through its retry budget and into `blocked`), and the TUI arm reported an *actionable* spawn error, parking the task for a human over an app you had simply turned off. Tasks now hold instead, gated in two places: the queue stops dequeuing entirely while the runner is down — before the priority tiers drain on-demand requests, advance review cooldowns, or bind an app's "in review" marker — and dispatch itself holds anything that still reaches it, releasing that marker and freeing the scheduler's spawn reservation so an autonomous job re-registers instead of sitting wedged for five minutes. A held task keeps its exact queued record: pending, unclaimed, no agent, no retry charged. It spawns for real the moment the runner is back, because the runner socket's reconnect re-runs the dequeue. That reconnect is also now unbounded: the socket gave up after ten attempts (~10 seconds), so a runner that came back a minute later left the server connected to nothing while still routing every spawn at it. Backoff is capped at 10s and the resulting dequeue is debounced, so neither a long outage nor a crash-looping runner is expensive. You get one log line when the runner drops and one when it returns, not one per task. "Run now" is never held — it answers with the real reason (runner unreachable, or the daemon stopped, which was never checked at all) instead of toasting "Spawning" at a task that would sit pending.diff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsxindex b7906cd019..5f612c1f88 100644--- a/client/src/components/pipeline/AutopilotPanel.jsx+++ b/client/src/components/pipeline/AutopilotPanel.jsx@@ -271,8 +271,12 @@ function frameLabel(f) {case 'verify:round': return `${f.scope} check — ${f.blocking} blocking of ${f.findings} finding(s)${f.errored > 0 ? ` · ⚠️ ${f.errored} errored` : ''}`;// An auto-resolve round that left the draft worse was undone — say so live,// or the round's edits appear to still be in place while the run pauses.+ // A revert is not necessarily the end of the gate: when a corrective pass is+ // left, the run retries from the restored state, so say which one happened+ // or the user reads every rollback as "this run is about to stop".case 'resolve:rollback': return `${f.scope} auto-resolve went from ${f.before} to ${f.after} blocking finding(s) — `- + `${f.reverted ? 'reverted that round' : 'could not revert that round'}`;+ + `${f.reverted ? 'reverted that round' : 'could not revert that round'}`+ + `${f.retrying ? ', retrying from the best state' : ''}`;// #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 6e1eb87ef1..acb40cef18 100644--- a/data.reference/prompts/stages/pipeline-arc-resolve.md+++ b/data.reference/prompts/stages/pipeline-arc-resolve.md@@ -80,6 +80,20 @@ The verification pass flagged these problems. Resolve **every** one of them in y{{findingsJson}}```+{{#hasAvoid}}+## Problems a discarded earlier attempt introduced — do not author these++An earlier pass over the exact findings above was **reverted**: its rewrite closed some of what it was handed but left the plan carrying more blocking problems than it started with, so every edit it made was thrown away. The plan shown above is the restored pre-attempt state.++These are the problems that discarded attempt created. They are **not** in the plan right now, so there is nothing here to fix — this is the failure mode to avoid:++```json+{{avoidJson}}+```++Resolve the findings above with edits that cannot re-create any of these. Concretely: the discarded attempt over-reached, so make the smallest edit that closes each finding, touch fewer records than it did, and re-read every volume you edit against this list before returning it. If a finding could only be closed by authoring one of these problems, leave that finding open and explain the trade in `notes` — a plan with one honest open finding is better than one that swaps it for two new ones.+{{/hasAvoid}}+## How to resolve1. **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.diff --git a/scripts/migrations/005-shape-aware-arc-prompts.js b/scripts/migrations/005-shape-aware-arc-prompts.jsindex c4ee00e169..b9dba2aeab 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': '96f73a7e90526d65ef2bb100fb1cd4bf', // post-251 (field-sparse bounded patches)+ 'pipeline-arc-resolve.md': '0787128babf3c4c50e2f2cdb60214030', // post-252 (corrective-pass avoid list)};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 133688b7f4..6d45d5e062 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': '96f73a7e90526d65ef2bb100fb1cd4bf', // post-251 (field-sparse bounded patches)+ 'pipeline-arc-resolve.md': '0787128babf3c4c50e2f2cdb60214030', // post-252 (corrective-pass avoid list)'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 fdeae1255d..f47c82c7ed 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': '96f73a7e90526d65ef2bb100fb1cd4bf', // post-251 (field-sparse bounded patches)+ 'pipeline-arc-resolve.md': '0787128babf3c4c50e2f2cdb60214030', // post-252 (corrective-pass avoid list)};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 6e2b69505d..45d59c9045 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': '96f73a7e90526d65ef2bb100fb1cd4bf', // post-251 (field-sparse bounded patches)+ 'pipeline-arc-resolve.md': '0787128babf3c4c50e2f2cdb60214030', // post-252 (corrective-pass avoid list)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/251-arc-resolve-field-sparsity.js b/scripts/migrations/251-arc-resolve-field-sparsity.jsindex 1e9ae10b75..8a792cf022 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': '96f73a7e90526d65ef2bb100fb1cd4bf',+ 'pipeline-arc-resolve.md': '0787128babf3c4c50e2f2cdb60214030', // post-252 (corrective-pass avoid list)};const { applyMigration, up } = makePromptReplaceMigration({diff --git a/scripts/migrations/252-arc-resolve-avoid-list.js b/scripts/migrations/252-arc-resolve-avoid-list.jsnew file mode 100644index 0000000000..843f3cd3e7--- /dev/null+++ b/scripts/migrations/252-arc-resolve-avoid-list.js@@ -0,0 +1,30 @@+/**+ * Teach the arc auto-resolve prompt to accept a "do not author these" list.+ *+ * When the autopilot's arc-verify gate reverts a resolve round for growing the+ * blocking-finding count, it now re-runs the resolver from the restored state+ * with the rejected attempt's own findings attached. Without this section the+ * retry renders the identical prompt and can regress identically.+ */++import { makePromptReplaceMigration } from './_lib.js';++export const ACCEPTED_OLD_MD5 = {+ 'pipeline-arc-resolve.md': ['96f73a7e90526d65ef2bb100fb1cd4bf'],+};++export const NEW_SHIPPED_MD5 = {+ 'pipeline-arc-resolve.md': '0787128babf3c4c50e2f2cdb60214030',+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'arc-resolve corrective-pass avoid list',+ customizedHint: (filename) =>+ ` To upgrade it manually, diff data.reference/prompts/stages/${filename}\n` ++ ` against data/prompts/stages/${filename} and add the {{#hasAvoid}} section that names the problems a discarded earlier attempt introduced.`,+});++export { applyMigration };+export default { up };diff --git a/scripts/migrations/252-arc-resolve-avoid-list.test.js b/scripts/migrations/252-arc-resolve-avoid-list.test.jsnew file mode 100644index 0000000000..4abdf394c4--- /dev/null+++ b/scripts/migrations/252-arc-resolve-avoid-list.test.js@@ -0,0 +1,35 @@+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 './252-arc-resolve-avoid-list.js';++describe('migration 252 — arc-resolve corrective-pass avoid list', () => {+ runPromptMigrationTests({+ migration,+ applyMigration,+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ prefix: 'migration-252-arc-resolve-avoid-',+ });++ it('renders the avoid list only when the corrective pass supplies one', () => {+ const prompt = readFileSync(+ `${repoRoot}/data.reference/prompts/stages/pipeline-arc-resolve.md`,+ 'utf8',+ );+ // Section-gated on `hasAvoid`, so a first attempt renders no avoid block at+ // all rather than an empty "do not author these: []" the model must ignore.+ expect(prompt).toContain('{{#hasAvoid}}');+ expect(prompt).toContain('{{avoidJson}}');+ expect(prompt).toContain('{{/hasAvoid}}');+ // The section has to say these problems are ABSENT from the plan — a list of+ // findings under a resolve prompt otherwise reads as more work to close.+ expect(prompt).toContain('do not author these');+ expect(prompt).toMatch(/\*\*not\*\* in the plan right now/);+ });+});diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.jsindex da360aea3a..98a738ba1d 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': ['5b340885c6e8f8afc63424d6b5bc7eb7', '87bc5c01f1a8a97b681727a38b05edc6', '8bb134554c122d1583c479ab3010e53d', '8e348f3d1894382889f9f0ee7d5c6792', 'a8677bbe1eb38f871fb152a5b0fec7c6', 'cc27b4da1d1a13c35e35d1c2d6183815'],+ 'pipeline-arc-resolve.md': ['5b340885c6e8f8afc63424d6b5bc7eb7', '87bc5c01f1a8a97b681727a38b05edc6', '8bb134554c122d1583c479ab3010e53d', '8e348f3d1894382889f9f0ee7d5c6792', '96f73a7e90526d65ef2bb100fb1cd4bf', 'a8677bbe1eb38f871fb152a5b0fec7c6', 'cc27b4da1d1a13c35e35d1c2d6183815'],'pipeline-script-verify.md': ['ed6c8101644cfe56a100eb6bfe3587f3'],'pipeline-extract-scenes.md': ['59fa5ee305ce53d91eb15224d8b546d3', 'c51fb208568d0d903eb43b437478b0ba'],'writers-room-places.md': ['24a33628cc94d80fa5ca60831d973daf', '7f1f80eb63d67a21161994cde115045e'],@@ -63,7 +63,7 @@ const EXPECTED_STAGE_NEW = {'pipeline-arc-overview.md': '5ed760caaf3cf88916ec28b220e2f590','pipeline-arc-verify.md': '83347e7d923580a3062033ab39b3c14b','pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940',- 'pipeline-arc-resolve.md': '96f73a7e90526d65ef2bb100fb1cd4bf',+ 'pipeline-arc-resolve.md': '0787128babf3c4c50e2f2cdb60214030','pipeline-script-verify.md': '722c62462d05462603cf67ca0ed1dee8','pipeline-extract-scenes.md': '9f404b0c4721b23932a6d2dcfc1fba43','writers-room-places.md': 'a7f68e51dd6b4421d20f5bd9d855d9b4',diff --git a/server/routes/pipeline/autopilot.js b/server/routes/pipeline/autopilot.jsindex c91509243e..b8e0de8ef5 100644--- a/server/routes/pipeline/autopilot.js+++ b/server/routes/pipeline/autopilot.js@@ -88,6 +88,12 @@ const autopilotStartSchema = z.object({// Per-run only (no persisted default); falls back to MAX_CHILD_RETRIES. Shares// the convergence ceiling so a direct API call can't request an absurd budget.maxChildRetries: z.number().int().min(0).max(MAX_CONVERGENCE_ROUNDS).optional(),+ // Per-run corrective-pass budget for the arc-verify regression guard (#3781):+ // how many times a reverted resolve round may be re-attempted from the restored+ // best state before the gate pauses for a human. 0 = revert and pause on the+ // first regression. Per-run only (no persisted default); falls back to+ // MAX_ARC_RESOLVE_RETRIES. Shares the convergence ceiling.+ maxArcResolveRetries: z.number().int().min(0).max(MAX_CONVERGENCE_ROUNDS).optional(),// Per-run editorial-check subset (#1575). When present, the editorial-checks// pass runs ONLY these check ids instead of all enabled checks — pilot one new// check, or skip an expensive one, without toggling the global enabled set.diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.jsindex b6abe655b8..3e82bf647d 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -1050,6 +1050,63 @@ describe('arcPlanner — resolveVerifyIssues', () => {expect(JSON.parse(findingsJson).map((f) => f.findingId)).toEqual(['f1', 'f2']);});+ it('leaves the avoid section out of a first-attempt resolve', async () => {+ const s = await setupSeries();+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L' } });+ stageRunnerSpy = vi.fn(async () => ({+ content: { arc: { resolves: ['f1'], logline: 'L2', summary: 'S' }, seasons: [], notes: '' },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ await planner.resolveVerifyIssues(s.id, {+ findings: [{ severity: 'high', problem: 'first defect', suggestion: '' }],+ });++ const ctx = stageRunnerSpy.mock.calls[0][1];+ // False, not "an empty array" — the prompt section is gated on this flag, so+ // a first attempt must render no avoid block rather than an empty one the+ // model has to decide to ignore.+ expect(ctx.hasAvoid).toBe(false);+ expect(JSON.parse(ctx.avoidJson)).toEqual([]);+ });++ it('renders a corrective pass\'s avoid list separately from the findings to close', async () => {+ // The autopilot's arc-verify gate reverts a resolve round that grew the+ // blocking count, then re-runs the resolver from the restored state with the+ // rejected attempt's findings as `avoid`. Those problems are NOT in the plan+ // any more, so they must never leak into `findingsJson` — asking the+ // resolver to close a problem the plan doesn't have is how a corrective pass+ // authors a fresh contradiction.+ const s = await setupSeries();+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L' } });+ stageRunnerSpy = vi.fn(async () => ({+ content: { arc: { resolves: ['f1'], logline: 'L2', summary: 'S' }, seasons: [], notes: '' },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ await planner.resolveVerifyIssues(s.id, {+ findings: [{ severity: 'high', problem: 'first defect', suggestion: 'fix it' }],+ avoid: [+ { severity: 'high', problem: 'the reverted rewrite dropped the mentor payoff', suggestion: '' },+ { problem: 'and split volume 2 in half', location: 'V2' },+ ],+ });++ const ctx = stageRunnerSpy.mock.calls[0][1];+ expect(ctx.hasAvoid).toBe(true);+ const avoid = JSON.parse(ctx.avoidJson);+ expect(avoid.map((f) => f.problem)).toEqual([+ 'the reverted rewrite dropped the mentor payoff',+ 'and split volume 2 in half',+ ]);+ // Normalized through the same shaper as the findings — a severity-less entry+ // gets the default rather than riding through as undefined.+ expect(avoid[1]).toMatchObject({ severity: 'medium', location: 'V2' });+ // The avoid entries carry no findingId and never appear as work to close.+ expect(ctx.avoidJson).not.toMatch(/findingId/);+ expect(JSON.parse(ctx.findingsJson).map((f) => f.problem)).toEqual(['first defect']);+ });+it('preserves series.arc.readerMap when the resolve LLM does not author one', async () => {// Regression for the drift between generateArcOverview (which preserves// readerMap) and resolveVerifyIssues (which silently wiped it pre-fix).diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.jsindex e65d607cf6..4a9e2cf96b 100644--- a/server/services/pipeline/arcPlanner/arcCore.js+++ b/server/services/pipeline/arcPlanner/arcCore.js@@ -401,7 +401,9 @@ export function selectFindingKeyedEdits(content, findings) {// 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-// everything it returns.+// everything it returns. `options.avoid` is the optional "a previous attempt at+// these same findings authored THESE and was reverted" list (see+// buildResolveContext) — set only by a corrective pass.export async function resolveVerifyIssues(seriesId, options = {}) {const series = await getSeries(seriesId);if (!series.arc) {@@ -433,7 +435,10 @@ export async function resolveVerifyIssues(seriesId, options = {}) {}}- const ctx = await buildResolveContext(series, findings, world);+ // `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 });const { content, runId, providerId, model } = await runStagedLLM('pipeline-arc-resolve',ctx,diff --git a/server/services/pipeline/arcPlanner/context.js b/server/services/pipeline/arcPlanner/context.jsindex c909b42621..c4dc84d880 100644--- a/server/services/pipeline/arcPlanner/context.js+++ b/server/services/pipeline/arcPlanner/context.js@@ -704,12 +704,24 @@ export function matchResolvedFindings(raw, validIds) {return { declared: true, matched };}-export async function buildResolveContext(series, findings, preloadedWorld) {+/**+ * `options.avoid` — findings that a PREVIOUS attempt at this same round+ * authored, and that got that attempt reverted. They are not in the plan the+ * context describes (the caller restored the pre-attempt state first), so they+ * are rendered as a separate "do not author these" list rather than mixed into+ * `findingsJson`: asking the resolver to close a problem the plan no longer has+ * is how a corrective pass invents a fresh contradiction. Absent/empty on a+ * first attempt, which leaves the prompt section out entirely.+ */+export async function buildResolveContext(series, findings, preloadedWorld, options = {}) {const ctx = await buildVerifyContext(series, preloadedWorld);const structure = recommendStructure(series.issueCountTarget);+ const avoid = shapeFindings(options.avoid);return {...ctx,findingsJson: JSON.stringify(stampFindingIds(findings), null, 2),+ hasAvoid: avoid.length > 0,+ avoidJson: JSON.stringify(avoid, null, 2),recommendedStructure: structure? describeStructure(structure): '(no target episode count set)',diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex 62ec8efbe8..d3838d5d49 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -2045,8 +2045,10 @@ describe('autopilot conductor', () => {// The 2026-08-09 non-convergence, replayed: the loop hands the resolver ONE// blocking finding and gets 3 back, then 5 — with the original still// standing every round. Before this guard all of that damage was committed- // and the run paused on 5 findings the user never had. Now round 2's verify sees the- // regression, puts the pre-resolve arc back, and pauses on the original 1.+ // and the run paused on 5 findings the user never had. Now round 2's verify+ // sees the regression and puts the pre-resolve arc back; it spends its one+ // corrective pass from there, and when round 3 regresses again the gate is+ // out of retries and pauses on the original 1.const original = { severity: 'high', problem: 'volume 1 and volume 2 both stage the first eclipse', location: 'V1' };const extra = (i) => ({ severity: 'high', problem: `collateral break ${i}`, location: `V${i + 2}` });const round = (n) => ({ issues: [original, ...Array.from({ length: n - 1 }, (_, i) => extra(i))] });@@ -2058,23 +2060,31 @@ describe('autopilot conductor', () => {await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 6 });await waitFor(runFinished(seriesId));- // Bailed at round 2 — the 5-finding third round never runs, so neither the- // verify nor another resolve is billed against the budget.- expect(arcSpies.verifyArc).toHaveBeenCalledTimes(2);- expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(1);- // The snapshot taken before that resolve is what gets handed back.+ // Bailed at round 3 — the loop never runs on past the second regression, so+ // rounds 4-6 cost nothing.+ expect(arcSpies.verifyArc).toHaveBeenCalledTimes(3);+ expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(2);+ // Only the first-attempt resolve snapshots; the corrective pass reuses the+ // checkpoint it was just rewound to rather than pinning the reverted draft.expect(arcSpies.snapshotArcState).toHaveBeenCalledTimes(1);expect(arcSpies.restoreArcState).toHaveBeenCalledWith(seriesId,await arcSpies.snapshotArcState.mock.results[0].value,);+ // The corrective pass is handed the CHECKPOINT's findings (what the restored+ // plan actually has) plus the rejected attempt's own findings to steer away+ // from — not the 3-finding set, which is no longer in the plan at all.+ expect(arcSpies.resolveVerifyIssues.mock.calls[1][1]).toMatchObject({+ findings: [original],+ avoid: round(3).issues,+ });const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;expect(last?.type).toBe('paused');expect(last?.scope).toBe('verifyArcSpine');expect(last?.pauseKind).toBe('regression');expect(last?.reason).toMatch(/reverted/);- // Residual is what the user had BEFORE the round, not the 3 it manufactured.+ // Residual is what the user had BEFORE the round, not the 5 it manufactured.expect(last?.residualFindings).toEqual([original]);const series = await seriesSvc.getSeries(seriesId);expect(series.autopilot?.status).toBe('paused');@@ -2082,6 +2092,66 @@ describe('autopilot conductor', () => {expect(series.autopilot?.residualFindings).toHaveLength(1);});+ it('spends one corrective pass on a reverted resolve round and converges from it (#3781)', async () => {+ // The 2026-08-11 verifyArcSpine stall: 3 blockers in, 6 back, reverted —+ // and the run STOPPED there. A resume re-ran the same prompt over the same+ // restored state, so the gate could never clear itself unattended. Now the+ // revert is followed by one more resolve from the checkpoint that names the+ // rejected attempt's own findings as the failure mode to avoid.+ const holes = (n, prefix) => Array.from({ length: n }, (_, i) => ({+ severity: 'high', problem: `${prefix} ${i}`, location: `V${i + 1}`,+ }));+ arcSpies.verifyArc.mockReset();+ arcSpies.verifyArc+ .mockImplementationOnce(async () => ({ issues: holes(3, 'initial') }))+ .mockImplementationOnce(async () => ({ issues: holes(6, 'regressed') }))+ .mockImplementationOnce(async () => ({ issues: [] }));+ const { seriesId } = await seedComplete();+ const frames = [];+ const handler = (p) => frames.push(p);+ autopilot.autopilotEvents.on(seriesId, handler);+ await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 3 });+ await waitFor(runFinished(seriesId));+ autopilot.autopilotEvents.off(seriesId, handler);++ // The damaged draft is still reverted — the retry is a second attempt from+ // the checkpoint, never an acceptance of the worse state.+ expect(arcSpies.restoreArcState).toHaveBeenCalledTimes(1);+ expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(2);+ expect(arcSpies.resolveVerifyIssues.mock.calls[1][1]).toMatchObject({+ findings: holes(3, 'initial'),+ avoid: holes(6, 'regressed'),+ });+ // …and the gate clears, so the run advances instead of pausing for a human.+ const rollback = frames.find((f) => f.type === 'resolve:rollback');+ expect(rollback).toMatchObject({ before: 3, after: 6, best: 3, retrying: true });+ expect(frames.some((f) => f.type === 'resolve:round' && f.retry === true)).toBe(true);+ expect(frames.some((f) => f.type === 'paused' && f.pauseKind === 'regression')).toBe(false);+ const series = await seriesSvc.getSeries(seriesId);+ expect(series.autopilot?.pauseKind).not.toBe('regression');+ });++ it('honors maxArcResolveRetries: 0 by pausing on the first regression', async () => {+ // The pre-#3781 behavior stays reachable per run: no corrective pass, so the+ // first reverted candidate ends the gate without spending a second resolve.+ const holes = (n, prefix) => Array.from({ length: n }, (_, i) => ({+ severity: 'high', problem: `${prefix} ${i}`, location: `V${i + 1}`,+ }));+ arcSpies.verifyArc.mockReset();+ arcSpies.verifyArc+ .mockImplementationOnce(async () => ({ issues: holes(3, 'initial') }))+ .mockImplementationOnce(async () => ({ issues: holes(6, 'regressed') }));+ const { seriesId } = await seedComplete();+ await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 6, maxArcResolveRetries: 0 });+ await waitFor(runFinished(seriesId));++ expect(arcSpies.verifyArc).toHaveBeenCalledTimes(2);+ expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(1);+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;+ expect(last?.pauseKind).toBe('regression');+ expect(last?.residualFindings).toEqual(holes(3, 'initial'));+ });+it('reverts the same 1 → 3 → 5 divergence when each verify call re-words the finding', async () => {// Same incident as the test above, but replayed the way the verifier// actually behaves: round 2 restates the standing defect in fresh prose at a@@ -2118,16 +2188,17 @@ describe('autopilot conductor', () => {await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 6 });await waitFor(runFinished(seriesId));- // Round 3 (the 5-finding verify) and its resolve are never billed.- expect(arcSpies.verifyArc).toHaveBeenCalledTimes(2);- expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(1);+ // Round 2's regression is reverted and retried once; round 3 regresses+ // again with no retries left, so rounds 4-6 are never billed.+ expect(arcSpies.verifyArc).toHaveBeenCalledTimes(3);+ expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(2);expect(arcSpies.restoreArcState).toHaveBeenCalledWith(seriesId,await arcSpies.snapshotArcState.mock.results[0].value,);const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;expect(last?.pauseKind).toBe('regression');- // Paused on the ONE finding the user actually had, not the 3 it manufactured.+ // Paused on the ONE finding the user actually had, not the 5 it manufactured.expect(last?.residualFindings).toEqual([restatements[0]]);});@@ -2150,8 +2221,10 @@ describe('autopilot conductor', () => {await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 6 });await waitFor(runFinished(seriesId));- expect(arcSpies.verifyArc).toHaveBeenCalledTimes(2);- expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(1);+ // The corrective pass gets the same two latent blockers back, so the gate+ // runs out of retries and pauses on the demonstrated single-blocker state.+ expect(arcSpies.verifyArc).toHaveBeenCalledTimes(3);+ expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(2);expect(arcSpies.restoreArcState).toHaveBeenCalledWith(seriesId,await arcSpies.snapshotArcState.mock.results[0].value,@@ -2165,7 +2238,7 @@ describe('autopilot conductor', () => {const holes = (n, prefix) => Array.from({ length: n }, (_, i) => ({severity: 'high', problem: `${prefix} ${i}`, location: `V${i + 1}`,}));- const rounds = [holes(4, 'initial'), holes(2, 'best'), holes(4, 'regressed'), holes(5, 'never reached')];+ const rounds = [holes(4, 'initial'), holes(2, 'best'), holes(4, 'regressed'), holes(5, 'retry regressed')];arcSpies.verifyArc.mockReset();rounds.forEach((result) => arcSpies.verifyArc.mockImplementationOnce(async () => ({ issues: result })));const initialSnapshot = { marker: 'initial', arc: null, seasons: [], episodes: [] };@@ -2178,9 +2251,12 @@ describe('autopilot conductor', () => {await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 12 });await waitFor(runFinished(seriesId));- // The first increase stops the loop; the 5-blocker round is never spent.- expect(arcSpies.verifyArc).toHaveBeenCalledTimes(3);- expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(2);+ // Round 3's increase rewinds to the 2-blocker checkpoint and spends the one+ // corrective pass; round 4 regresses again, so the loop stops there.+ expect(arcSpies.verifyArc).toHaveBeenCalledTimes(4);+ expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(3);+ // Two snapshots, three resolves: the corrective pass rewinds to the+ // checkpoint it already holds instead of pinning the reverted draft.expect(arcSpies.snapshotArcState).toHaveBeenCalledTimes(2);expect(arcSpies.restoreArcState).toHaveBeenCalledWith(seriesId, bestSnapshot);const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;@@ -2190,12 +2266,12 @@ describe('autopilot conductor', () => {// Both sides of the trade are reported: the count guard is deliberately// blind to finding identity, so the rejected candidate's own findings ride// along for the human deciding whether the pause was worth it.- expect(last?.discardedFindings).toEqual(rounds[2]);+ expect(last?.discardedFindings).toEqual(rounds[3]);// The persisted marker must agree with the broadcast frame. These are two// separate writes off one payload, and a field that reaches only the live// stream vanishes on reload — which is when the user actually reviews it.const series = await seriesSvc.getSeries(seriesId);- expect(series.autopilot?.discardedFindings).toEqual(rounds[2]);+ expect(series.autopilot?.discardedFindings).toEqual(rounds[3]);});it('a blocker increase reaches the regression guard even when it lands on the round cap', async () => {diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.jsindex 4cf91700f1..67989a7412 100644--- a/server/services/pipeline/seriesAutopilot/childRuns.js+++ b/server/services/pipeline/seriesAutopilot/childRuns.js@@ -18,7 +18,10 @@ import {} from '../foundationJudge.js';import * as volumeBeatsRunner from '../volumeBeatsRunner.js';import * as autoRunner from '../autoRunner.js';-import { MAX_ARC_VERIFY_ROUNDS, MAX_BEAT_CONTINUITY_ROUNDS, MAX_FOUNDATION_ROUNDS, MAX_CHILD_RETRIES } from './config.js';+import {+ MAX_ARC_VERIFY_ROUNDS, MAX_BEAT_CONTINUITY_ROUNDS, MAX_FOUNDATION_ROUNDS, MAX_CHILD_RETRIES,+ MAX_ARC_RESOLVE_RETRIES,+} from './config.js';import {CHILD_POLL_MS, DIVERGENCE_PATIENCE, trackConvergence, convergencePauseReason,divergencePauseReason, foundationPauseReason, foundationDivergenceReason,@@ -38,6 +41,15 @@ const MAX_PLANNING_GATE_HANDOFFS = 6;// record keeps rather than every finding a many-volume verify produced.const discardedSet = (blocking) => blocking.slice(0, AUTOPILOT_DISCARDED_MAX);+// Effective corrective-pass budget for the arc-verify gate this run: a per-run+// `maxArcResolveRetries` option wins, else the module default. Negative values+// clamp to 0 (revert and pause on the first regression). Mirrors+// `childRetryBudget` further down.+function arcResolveRetryBudget(record) {+ const v = record.options.maxArcResolveRetries;+ return Number.isInteger(v) ? Math.max(0, v) : MAX_ARC_RESOLVE_RETRIES;+}+function finishPlanningMutation(record, peerLatch) {record.runState[peerLatch] = false;record.runState.planningGateHandoffs = (record.runState.planningGateHandoffs || 0) + 1;@@ -76,6 +88,14 @@ export async function runArcVerify(seriesId, record, { spineOnly = false } = {})// the arc just before it ran — the two halves the regression guard below needs// to decide whether that round earned its edits.let lastResolve = null;+ // How many corrective passes the regression guard may still spend (#3781).+ // Reverting a bad candidate is not the same as being unable to try again: on a+ // regression the gate restores the best state and re-runs the resolver from+ // there with the rejected attempt's own findings attached as "do not author+ // these", and only pauses once that budget is gone. Without it the first bad+ // candidate ends the run, and resuming re-runs the identical prompt against+ // the identical state — so the gate could never clear itself unattended.+ let retriesLeft = arcResolveRetryBudget(record);for (let round = 1; round <= maxRounds; round += 1) {if (record.cancelRequested) return { canceled: true };const beforeVerify = await budgetPause();@@ -130,16 +150,55 @@ export async function runArcVerify(seriesId, record, { spineOnly = false } = {})// best verified state, not merely the immediately previous state; otherwise// a 4 → 2 → 4 → 5 run pauses on 4 and discards the demonstrated 2-blocker// draft. Checked before maxRounds/divergence so no worse baseline survives.+ // Reverting is unconditional; PAUSING is not — see the corrective pass below.if (lastResolve && blocking.length > lastResolve.blocking.length) {const rollbackTarget = bestVerified || lastResolve;const rollback = await restoreArcState(seriesId, rollbackTarget.snapshot);+ const discarded = discardedSet(blocking);+ // A retry is only worth its LLM call when a round remains to VERIFY it —+ // spending one on the final round would bill a rewrite nothing ever+ // checks, and would fall out of the loop past every `return` below.+ const canRetry = retriesLeft > 0 && round < maxRounds;broadcast(seriesId, {type: 'resolve:rollback', scope: 'arc', round,before: lastResolve.blocking.length, after: blocking.length,best: rollbackTarget.blocking.length,reverted: rollback.restored,episodesReverted: rollback.episodesRestored,+ retrying: canRetry,});+ // Corrective pass (#3781): the revert above put the best verified state+ // back, so re-run the resolver against exactly the findings that state+ // has — this time carrying the rejected attempt's own findings as an+ // explicit "do not author these" list, which is the only new information+ // the gate has. Pausing here instead (the pre-#3781 behavior) hands the+ // user a run that a resume cannot advance: the same prompt over the same+ // state can regress the same way. Budget-gated and billed like any other+ // resolve, and bounded, so a resolver that keeps trading blockers still+ // reaches the pause below.+ if (canRetry) {+ retriesLeft -= 1;+ if (record.cancelRequested) return { canceled: true };+ const beforeRetry = await budgetPause();+ if (beforeRetry) return beforeRetry;+ const retried = await resolveVerifyIssues(seriesId, {+ findings: rollbackTarget.blocking,+ avoid: discarded,+ ...providerOverrideOpts(record),+ ...seasonPreserveOpts(record),+ });+ if (retried?.applied !== false) changed = true;+ // The restored state is what the retry has to beat, so the next round+ // compares against ITS count — not the rejected candidate's, which+ // would let the retry regress back to the discarded draft for free.+ lastResolve = rollbackTarget;+ await recordDomainUsage('cos', { actions: 1 });+ broadcast(seriesId, {+ type: 'resolve:round', scope: 'arc', round, retry: true,+ episodesEdited: Array.isArray(retried?.episodesResolved) ? retried.episodesResolved.length : 0,+ });+ continue;+ }return {pause: true,pauseKind: 'regression',@@ -150,7 +209,7 @@ export async function runArcVerify(seriesId, record, { spineOnly = false } = {})rollbackTarget.blocking.length,),residual: rollbackTarget.blocking,- discarded: discardedSet(blocking),+ discarded,};}// Equal-count drafts may still represent real causal progress: a resolverdiff --git a/server/services/pipeline/seriesAutopilot/config.js b/server/services/pipeline/seriesAutopilot/config.jsindex 7b91cc030d..c0e63d2448 100644--- a/server/services/pipeline/seriesAutopilot/config.js+++ b/server/services/pipeline/seriesAutopilot/config.js@@ -42,6 +42,21 @@ export const DEFAULT_FOUNDATION_GATE_ENABLED = true;// `maxChildRetries` option overrides it (plumbed through runOptions).export const MAX_CHILD_RETRIES = 1;+// Corrective-pass budget for the arc-verify gate's regression guard (#3781). A+// resolver round that GREW the blocking count is reverted either way; this is+// how many times the gate may then re-run the resolver from the restored best+// state — with the rejected attempt's own findings attached as an explicit "do+// not author these" list — before it gives up and pauses for a human. Without+// it the very first bad candidate stops the whole run, and a resume just re-runs+// the identical prompt from the identical state and can regress identically, so+// the gate could never clear itself unattended (the 2026-08-11 verifyArcSpine+// stall: 3 blockers in, 6 back, paused on round 2 of 3). 0 = revert-and-pause on+// the first regression (the pre-#3781 behavior). A per-run `maxArcResolveRetries`+// option overrides it, like `maxChildRetries` above; there is deliberately no+// persisted setting for it — one extra resolve call on a path that otherwise+// ends the run is not a spend knob worth a UI.+export const MAX_ARC_RESOLVE_RETRIES = 1;+// The one precedence rule every gate below follows for a BOOLEAN knob: an// explicit per-run option wins, then the persisted pipelineEditorialChecks// setting, then the module default. Hoisted so the file states it once — it was