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
revert an arc auto-resolve round that adds blocking findings instead of committing it
[._.]/ Adam Eivy10da2e7c76ab
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex db74616000..2e82f4130f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -26,6 +26,8 @@## Fixed+- **An arc auto-resolve round that makes the draft worse is now undone instead of kept.** Autonomous mode's arc-verification gate hands the resolver the blocking findings it must clear and re-verifies afterwards — but whatever the resolver wrote was committed unconditionally, including a rewrite that cleared nothing and broke more than it touched. One run went 1 blocking finding → 3 → 5 that way: the loop noticed it had stopped converging and paused (correctly), but by then it had paused *on its own damage*, handing back an arc four findings further from the gate than the one the round started with. A round is now snapshotted before it runs — the arc, the volume list, each episode's planning synopsis and the volume it sits under — and if the next verification comes back with more blocking findings while the ones it was given are still standing, the round's edits are reverted and the run pauses on the original residual, labelled **round reverted**. The rollback is deliberately narrow: a round that genuinely closed everything it targeted is kept even when it surfaces findings that were latent underneath, since that's progress, and a round that merely stalls is still the existing non-convergence guard's business. Findings are matched by a normalized fingerprint rather than raw prose, so the verifier re-wording itself between calls can't disguise a finding as newly fixed. Volume ids, locked episodes, and the never-delete-a-volume guarantee survive the rollback, and no extra AI call is spent to detect it.+- **A CoS agent that commits to the primary checkout instead of its own worktree is now reported instead of recorded as a success.** A worktree-isolated agent running `/do:pr` applied its commits onto the primary checkout's local `main`, where they sat unpushed and unreviewed — on an unprotected branch, so any later push would have landed them without a PR — while PortOS recorded the run as completed. Every worktree run now stamps the primary checkout's branch and HEAD at spawn and re-reads them in the shared finalize path (so all three spawn modes are covered, not just TUI). A checkout that moved fails the run as `primary-checkout-mutated`, naming the drifted branch, the commit count, and the exact recovery command — and noting the commits are almost certainly on the agent's branch too. PortOS deliberately does not repair it: the repair is `git reset --hard`, which discards commits, and that stays your call. Runs that leave the primary alone are unaffected.- **Universe Canon — "AI: differentiate cast" and per-character "AI: differentiate" now run.** Both threw `Stage pipeline-character-differentiate-cast not found` / `Stage pipeline-character-refine not found` on every install since they shipped: the prompt templates landed in `data.reference/prompts/stages/` but their `stage-config.json` entries were never authored, and `buildPrompt()` resolves the config entry first. Arc-verification **auto-resolve** (`pipeline-arc-resolve`) was dead the same way. All three entries now ship, migration 232 seeds them onto existing installs, and a new catalog-parity guard fails the build if a prompt template ever ships without its config entry again (or the reverse). The inverse gap on the Digital Twin side — ten stages whose config entry ships with no template, so each soul/twin AI pass silently runs its fallback — is tracked in #3644.diff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsxindex dd17cd0a3c..2dc32be68a 100644--- a/client/src/components/pipeline/AutopilotPanel.jsx+++ b/client/src/components/pipeline/AutopilotPanel.jsx@@ -20,6 +20,7 @@ import {patchSettingsSlice,} from '../../services/api';import { providerDisplayName, providerModelLabel, assignmentModelOptions, resolveSeriesRunLlm, resolveCliEffort } from '../../utils/providers';+import Pill from '../ui/Pill';import ProviderModelSelector from '../ProviderModelSelector';import SeriesAutopilotSchedule from './SeriesAutopilotSchedule';@@ -265,6 +266,10 @@ function frameLabel(f) {case 'step:complete': return `${stepLabel(f.kind)} done`;case 'step:skip': return `Skipped ${stepLabel(f.kind)}${f.reason ? ` — ${f.reason}` : ''}`;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.+ 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'}`;// #2176 — foundation-gate telemetry.case 'foundation:round': return `Foundation round ${f.round} — weighted ${f.weightedScore}/${f.threshold}${f.weakest ? ` · weakest: ${f.weakest}` : ''}`;case 'foundation:fix': return `Foundation fix — ${f.dimension}${f.applied ? ' applied' : ` skipped${f.reason ? ` (${f.reason})` : ''}`}`;@@ -317,6 +322,24 @@ function frameLabel(f) {const RUN_ENDED = new Set(['complete', 'canceled', 'error', 'paused']);+// Pause kinds worth calling out beside the status line — the ones where "Paused"+// alone doesn't tell the user what state the draft is in. A kind with no entry+// (maxRounds, childFailed) is fully explained by the reason text below it.+const PAUSE_BADGES = {+ divergence: {+ label: 'not converging',+ title: 'Auto-resolve stopped reducing blocking findings — needs a human edit, not more rounds',+ },+ regression: {+ label: 'round reverted',+ title: 'An auto-resolve round left more blocking findings than it was given — its edits were reverted and the draft is back to its pre-round state',+ },+ checkFindings: {+ label: 'high findings',+ title: 'Editorial checks surfaced too many High findings — address them (or raise the threshold) and resume',+ },+};+// #1572 — shared caution tail for a `done` run that filed blocking script-craft// gaps, so the completion toast and the persisted-status banner can't drift.const craftGapCaution = (n) => `${n} filed script-craft gap${n === 1 ? '' : 's'} — resolve before rendering`;@@ -977,21 +1000,10 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate: doneWithCheckErrors ? `Completed — ${editorialCheckCaution(ap.editorialCheckErrors)}`: ap.status === 'done' ? 'Last run completed — draft is production-ready' : 'Last run errored'}</span>- {ap.status === 'paused' && ap.pauseKind === 'divergence' ? (- <span- className="px-1.5 py-0.5 rounded text-[10px] bg-port-warning/15 text-port-warning border border-port-warning/30"- title="Auto-resolve stopped reducing blocking findings — needs a human edit, not more rounds"- >- not converging- </span>- ) : null}- {ap.status === 'paused' && ap.pauseKind === 'checkFindings' ? (- <span- className="px-1.5 py-0.5 rounded text-[10px] bg-port-warning/15 text-port-warning border border-port-warning/30"- title="Editorial checks surfaced too many High findings — address them (or raise the threshold) and resume"- >- high findings- </span>+ {ap.status === 'paused' && PAUSE_BADGES[ap.pauseKind] ? (+ <Pill tone="warning" size="xs" title={PAUSE_BADGES[ap.pauseKind].title}>+ {PAUSE_BADGES[ap.pauseKind].label}+ </Pill>) : null}</div>{ap.lastError && ap.status !== 'done' ? <p className="text-[11px] text-gray-400 mt-1">{ap.lastError}</p> : null}diff --git a/client/src/components/pipeline/AutopilotPanel.test.jsx b/client/src/components/pipeline/AutopilotPanel.test.jsxindex da36791043..b52cb85835 100644--- a/client/src/components/pipeline/AutopilotPanel.test.jsx+++ b/client/src/components/pipeline/AutopilotPanel.test.jsx@@ -395,6 +395,19 @@ describe('AutopilotPanel', () => {expect(screen.queryByText(/not converging/i)).not.toBeInTheDocument();});+ it('flags a reverted auto-resolve round with a "round reverted" badge', async () => {+ // The draft is back to its pre-round state — say so, or the user has no way+ // to tell this pause apart from one that left the round's edits in place.+ renderPanel({+ id: 's1',+ targetFormat: 'comic',+ autopilot: { status: 'paused', currentStep: 'verifyArc', pauseKind: 'regression' },+ });+ await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());+ expect(screen.getByText(/round reverted/i)).toBeInTheDocument();+ expect(screen.queryByText(/not converging/i)).not.toBeInTheDocument();+ });+it('flags an editorial-checks pause with a "high findings" badge (#1613)', async () => {renderPanel({id: 's1',diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.jsindex 58c1a6523f..6a9770558a 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -1032,6 +1032,83 @@ describe('arcPlanner — resolveVerifyIssues', () => {});});+describe('arcPlanner — snapshotArcState / restoreArcState (resolve-round rollback)', () => {+ beforeEach(() => {+ fileStore.clear();+ uuidCounter = 0;+ stageRunnerSpy = undefined;+ });++ // Stand up the shape one auto-resolve round can touch: an arc, two volumes,+ // and an episode under each carrying a planning synopsis.+ async function seedArc() {+ const s = await setupSeries();+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'original logline', summary: 'original summary' } });+ const v1 = await seasonsSvc.createSeason(s.id, { title: 'Volume 1', synopsis: 'v1 synopsis', episodeCountTarget: 2 });+ const v2 = await seasonsSvc.createSeason(s.id, { title: 'Volume 2', synopsis: 'v2 synopsis', episodeCountTarget: 2 });+ const e1 = await issuesSvc.createIssue({ seriesId: s.id, seasonId: v1.id, title: 'Ep 1' });+ const e2 = await issuesSvc.createIssue({ seriesId: s.id, seasonId: v2.id, title: 'Ep 2' });+ await issuesSvc.updateStage(e1.id, 'idea', { input: 'e1 planning synopsis' });+ await issuesSvc.updateStage(e2.id, 'idea', { input: 'e2 planning synopsis' });+ return { s, v1, v2, e1, e2 };+ }++ it('puts back the arc, the volume list and the episode synopses a round rewrote', async () => {+ const { s, v1, v2, e1, e2 } = await seedArc();+ const snapshot = await planner.snapshotArcState(s.id);++ // Simulate the damage a regressive resolve round does: rewrite the arc,+ // rewrite a volume, mint a third one, move an episode onto it, and rewrite+ // the other episode's synopsis (clearing its beats the way+ // applyEpisodeResolutions does).+ const minted = await seasonsSvc.createSeason(s.id, { title: 'Volume 1', synopsis: 'duplicate', episodeCountTarget: 2 });+ await seriesSvc.updateSeries(s.id, {+ arc: { logline: 'rewritten logline', summary: 'rewritten summary' },+ seasons: [{ ...v1, synopsis: 'rewritten v1' }, v2, minted],+ });+ await issuesSvc.updateIssue(e2.id, { seasonId: minted.id });+ await issuesSvc.updateStage(e1.id, 'idea', { input: 'rewritten e1 synopsis', output: '', status: 'empty' });++ const result = await planner.restoreArcState(s.id, snapshot);+ expect(result).toMatchObject({ restored: true, episodesRestored: 1, reassignedIssueCount: 1 });++ const series = await seriesSvc.getSeries(s.id);+ expect(series.arc.logline).toBe('original logline');+ expect(series.seasons.map((x) => x.id)).toEqual([v1.id, v2.id]);+ expect(series.seasons[0].synopsis).toBe('v1 synopsis');+ // The minted volume is gone, so the episode it took has to come back with+ // it — otherwise the rollback strands it in the ungrouped bucket.+ expect((await issuesSvc.getIssue(e2.id)).seasonId).toBe(v2.id);+ expect((await issuesSvc.getIssue(e1.id)).stages.idea.input).toBe('e1 planning synopsis');+ });++ it('leaves a locked idea stage alone (the resolve pass never touched it)', async () => {+ const { s, e1 } = await seedArc();+ const snapshot = await planner.snapshotArcState(s.id);+ await issuesSvc.updateStage(e1.id, 'idea', { input: 'user edit after the snapshot', locked: true });++ const result = await planner.restoreArcState(s.id, snapshot);+ expect(result.episodesRestored).toBe(0);+ expect((await issuesSvc.getIssue(e1.id)).stages.idea.input).toBe('user edit after the snapshot');+ });++ it('refuses a snapshot that belongs to another series, and a missing one', async () => {+ const { s } = await seedArc();+ const other = await planner.snapshotArcState((await seedArc()).s.id);+ expect(await planner.restoreArcState(s.id, other)).toMatchObject({ restored: false });+ expect(await planner.restoreArcState(s.id, null)).toMatchObject({ restored: false });+ // Untouched by the refused restores.+ expect((await seriesSvc.getSeries(s.id)).arc.logline).toBe('original logline');+ });++ it('snapshots by value — a later write cannot mutate what was captured', async () => {+ const { s } = await seedArc();+ const snapshot = await planner.snapshotArcState(s.id);+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'mutated', summary: 'mutated' } });+ expect(snapshot.arc.logline).toBe('original logline');+ });+});+describe('arcPlanner — shapeEpisodeResolutions', () => {it('keeps well-formed entries and drops malformed ones', () => {const out = planner.shapeEpisodeResolutions([diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.jsindex 15838e4029..7abd362a2d 100644--- a/server/services/pipeline/arcPlanner/arcCore.js+++ b/server/services/pipeline/arcPlanner/arcCore.js@@ -11,7 +11,7 @@ import { runStagedLLM } from '../../../lib/stageRunner.js';import { ServerError } from '../../../lib/errorHandler.js';import { stripAnsi } from '../../../lib/ansiStrip.js';import { ARC_LOCKABLE_FIELDS, getSeries, updateSeries } from '../series.js';-import { listIssues, recomputeIssueNumbersForSeries, updateIssue, updateStageWithLatest } from '../issues.js';+import { listIssues, listIssuesForSeries, recomputeIssueNumbersForSeries, updateIssue, updateStageWithLatest, updateStagesWithLatest } from '../issues.js';import { emitRecordUpdated, withReexportSuppressed } from '../../sharing/recordEvents.js';import { getSeason } from '../seasons.js';import { READER_MAP_BEAT_KINDS, buildSeason, cleanThemes, renderArcShapeGuidance, renderArcShapePositionSummary, sanitizeArc, sanitizeReaderMap, sanitizeSeason, sanitizeSeasonList } from '../../../lib/storyArc.js';@@ -552,6 +552,107 @@ export async function applyEpisodeResolutions(seriesId, series, episodes) {return applied;}+// The three `idea`-stage fields an auto-resolve round can rewrite, normalized so+// the snapshot and the restore's dirty-check read the record the same way — a+// fourth field would otherwise have to be added to two hand-rolled default lists+// kept in lockstep.+const ideaSnapshotOf = (stage) => ({+ input: stage?.input ?? '',+ output: stage?.output ?? '',+ status: stage?.status ?? 'empty',+});++// Every issue in the series, without per-stage run history: `listIssues` caps at+// 1000 (a longer series would lose its tail from the snapshot, making those+// episodes unrestorable) and carries history payloads this projection throws+// away. Shared by the snapshot and the restore.+const listEpisodesForSnapshot = (seriesId) => listIssuesForSeries(seriesId, { withHistory: false });++/**+ * Capture everything ONE auto-resolve round can rewrite — the arc, the volume+ * records, and each episode's planning synopsis (plus which volume it sits+ * under) — so a round that leaves verification WORSE can be reverted instead of+ * committed. Read-only; the caller holds the snapshot for the duration of the+ * round (see `runArcVerify`'s regression guard).+ *+ * Deep-cloned: `getSeries` hands back the store record un-cloned, and a snapshot+ * that aliases the record it is meant to restore is no snapshot at all.+ */+export async function snapshotArcState(seriesId) {+ const [series, issues] = await Promise.all([getSeries(seriesId), listEpisodesForSnapshot(seriesId)]);+ return {+ seriesId,+ arc: structuredClone(series.arc ?? null),+ seasons: structuredClone(series.seasons || []),+ episodes: issues.map((iss) => ({+ id: iss.id,+ seasonId: iss.seasonId ?? null,+ idea: ideaSnapshotOf(iss.stages?.idea),+ })),+ };+}++/**+ * Put a `snapshotArcState` capture back, restoring only what actually differs:+ * the arc + volume list, any episode whose volume the round re-pointed, and any+ * episode synopsis the round rewrote. Returns what it touched.+ *+ * Deliberately NOT routed through `commitSeasonsWithRemap`: that path merges,+ * preserves and re-mints, which is right for applying a rewrite and wrong for+ * undoing one — a rollback wants the exact prior record back, and it restores+ * the child issues' `seasonId` itself so a volume the round minted can't strand+ * the episodes it took. For the same reason it doesn't re-check `locked.arc`:+ * the arc was writable when the round ran, and refusing to undo that round's+ * damage because a lock flipped mid-run would strand the user with the damage.+ * A locked `idea` stage IS skipped — the resolve pass never touched it.+ *+ * Only the autopilot's convergence loop calls this: it is the one caller that+ * re-verifies after every resolve, so it is the only one that can tell a+ * regressive round from a good one without paying for an extra verify. The+ * manual `/arc/resolve` route and the foundation gate's structure fix run the+ * same resolver with no rollback, deliberately.+ */+export async function restoreArcState(seriesId, snapshot) {+ if (!snapshot || snapshot.seriesId !== seriesId || !Array.isArray(snapshot.episodes)) {+ return { restored: false, episodesRestored: 0, reassignedIssueCount: 0 };+ }+ const issues = await listEpisodesForSnapshot(seriesId);+ const byId = new Map(issues.map((iss) => [iss.id, iss]));+ const stageUpdates = [];+ const reassign = [];+ for (const snap of snapshot.episodes) {+ const cur = byId.get(snap.id);+ // Gone since the snapshot — nothing to restore onto (auto-resolve never+ // deletes issues, so this is a concurrent user edit, not the round).+ if (!cur) continue;+ if ((cur.seasonId ?? null) !== snap.seasonId) reassign.push(snap);+ if (cur.stages?.idea?.locked === true) continue;+ const idea = ideaSnapshotOf(cur.stages?.idea);+ if (idea.input === snap.idea.input+ && idea.output === snap.idea.output+ && idea.status === snap.idea.status) continue;+ stageUpdates.push({+ issueId: snap.id,+ stageId: 'idea',+ computeFn: () => ({ ...snap.idea, errorMessage: '' }),+ });+ }+ // Same write ordering as `commitSeasonsWithRemap`: seasons first, so a crash+ // between writes can't leave an issue pointing at a volume that isn't in+ // `series.seasons[]`.+ await withReexportSuppressed('series', seriesId, async () => {+ await updateSeries(seriesId, { arc: snapshot.arc, seasons: snapshot.seasons });+ for (const snap of reassign) {+ await updateIssue(snap.id, { seasonId: snap.seasonId }, { skipRenumber: true });+ }+ if (reassign.length) await recomputeIssueNumbersForSeries(seriesId);+ await updateStagesWithLatest(seriesId, stageUpdates);+ });+ emitRecordUpdated('series', seriesId);+ console.log(`↩️ arc-resolve: reverted a regressive round for series ${seriesId.slice(0, 12)} — ${stageUpdates.length} episode synopsis(es), ${reassign.length} reassignment(s)`);+ return { restored: true, episodesRestored: stageUpdates.length, reassignedIssueCount: reassign.length };+}+// Preserve per-field arc locks. When `currentSeries.locked.arcFields[k]` is// true, the incoming arc's value for `k` is replaced with the existing one so// auto-resolve / regenerate flows can rewrite unlocked fields withoutdiff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex 48e9b91184..eb6f46f5f0 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -127,7 +127,10 @@ const AUTOPILOT_FINDING_SEVERITIES = ['high', 'medium', 'low'];// reason text. Any other pause (budget, error, a capability gap) leaves this null.// Editorial checks (#1613): `checkFindings` (the editorial-checks pass surfaced ≥// the armed high-finding threshold, so the run paused for human review).-export const AUTOPILOT_PAUSE_KINDS = Object.freeze(['maxRounds', 'divergence', 'childFailed', 'checkFindings']);+// Resolve rollback: `regression` (an auto-resolve round came back with MORE+// blocking findings than it was handed while leaving those standing, so its+// edits were reverted and the run paused on the pre-round residual).+export const AUTOPILOT_PAUSE_KINDS = Object.freeze(['maxRounds', 'divergence', 'regression', 'childFailed', 'checkFindings']);export const sanitizeAutopilot = (raw) => {if (!raw || typeof raw !== 'object') return null;diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex 0d150cbfdb..b5a7732a04 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -48,6 +48,11 @@ const arcSpies = {verifyArc: vi.fn(async () => ({ issues: verifyFindings })),verifyVolume: vi.fn(async () => ({ issues: volumeVerifyFindings })),resolveVerifyIssues: vi.fn(async () => ({ applied: true })),+ // Resolve-round rollback. The real snapshot/restore pair is covered+ // against the store in arcPlanner.test.js; here they're stubbed so the+ // conductor tests assert the LOOP's decision — when a round gets reverted.+ snapshotArcState: vi.fn(async (sId) => ({ seriesId: sId, arc: null, seasons: [], episodes: [] })),+ restoreArcState: vi.fn(async () => ({ restored: true, episodesRestored: 0, reassignedIssueCount: 0 })),analyzeBeatContinuity: vi.fn(async () => ({ issues: beatContinuityFindings })),resolveBeatContinuity: vi.fn(async () => ({ applied: true, episodesResolved: [] })),analyzeManuscriptCompleteness: vi.fn(async () => ({ issues: editorialFindings, runId: 'run-comp' })),@@ -1291,6 +1296,51 @@ describe('trackConvergence (pure divergence/oscillation guard — #1571)', () =>});});+describe('isResolveRegression (pure resolve-round damage check)', () => {+ const { isResolveRegression, findingFingerprint } = autopilot;+ const f = (problem, location = 'V1', severity = 'high') => ({ severity, location, problem });++ it('flags a round that grew the blocking set while leaving what it targeted standing', () => {+ // The observed shape: one finding in, three out, the original still there.+ expect(isResolveRegression([f('both volumes stage the first eclipse')], [+ f('both volumes stage the first eclipse'),+ f('volume 3 drops the mentor subplot', 'V3'),+ f('finale hook never pays off', 'V4'),+ ])).toBe(true);+ });++ it('lets a round stand when it closed everything it targeted, even if latent findings surfaced', () => {+ // Growth alone is not damage — this round did its job and exposed work that+ // was already there. The divergence guard picks it up if the loop stalls.+ expect(isResolveRegression([f('both volumes stage the first eclipse')], [+ f('volume 3 drops the mentor subplot', 'V3'),+ f('finale hook never pays off', 'V4'),+ ])).toBe(false);+ });++ it('never flags a round that held the line or improved', () => {+ const before = [f('a'), f('b', 'V2')];+ expect(isResolveRegression(before, before)).toBe(false); // stalled → divergence guard's job+ expect(isResolveRegression(before, [f('a')])).toBe(false); // improved+ expect(isResolveRegression(before, [])).toBe(false); // cleared+ });++ it('tolerates missing/garbage inputs', () => {+ expect(isResolveRegression(undefined, undefined)).toBe(false);+ expect(isResolveRegression(null, [f('a')])).toBe(false);+ });++ it('fingerprints through the verifier re-wording its prose', () => {+ // Same finding, re-punctuated and re-cased between two verify calls — a raw+ // string match would read the second as brand new and miss the regression.+ expect(findingFingerprint({ severity: 'high', location: 'V1', problem: 'Both volumes stage the first eclipse.' }))+ .toBe(findingFingerprint({ severity: 'HIGH', location: 'v1', problem: 'both volumes stage the first eclipse' }));+ // Different location is a different finding.+ expect(findingFingerprint({ severity: 'high', location: 'V1', problem: 'x' }))+ .not.toBe(findingFingerprint({ severity: 'high', location: 'V2', problem: 'x' }));+ });+});+describe('autopilot conductor', () => {it('rejects start when the cos domain is off (no run created)', async () => {cosMode = 'off';@@ -1615,6 +1665,71 @@ describe('autopilot conductor', () => {expect(series.autopilot?.pauseKind).toBe('divergence');});+ it('reverts an arc-resolve round that introduced blocking findings and pauses on the pre-round residual', async () => {+ // 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.+ 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))] });+ arcSpies.verifyArc+ .mockImplementationOnce(async () => round(1))+ .mockImplementationOnce(async () => round(3))+ .mockImplementationOnce(async () => round(5));+ const { seriesId } = await seedComplete();+ 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.+ expect(arcSpies.snapshotArcState).toHaveBeenCalledTimes(1);+ expect(arcSpies.restoreArcState).toHaveBeenCalledWith(+ seriesId,+ await arcSpies.snapshotArcState.mock.results[0].value,+ );++ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;+ expect(last?.type).toBe('paused');+ expect(last?.scope).toBe('verifyArc');+ expect(last?.pauseKind).toBe('regression');+ expect(last?.reason).toMatch(/reverted/);+ // Residual is what the user had BEFORE the round, not the 3 it manufactured.+ expect(last?.residualFindings).toEqual([original]);+ const series = await seriesSvc.getSeries(seriesId);+ expect(series.autopilot?.status).toBe('paused');+ expect(series.autopilot?.pauseKind).toBe('regression');+ expect(series.autopilot?.residualFindings).toHaveLength(1);+ });++ it('keeps a round that closed what it targeted, even when new findings surface', async () => {+ // Guard against the over-strict rollback: this round DID clear the finding+ // it was handed, and the two that follow were latent underneath. Reverting+ // it would throw away real progress, so the loop keeps the edits and falls+ // through to the existing divergence guard when it stops improving.+ const first = { severity: 'high', problem: 'first eclipse staged twice', location: 'V1' };+ const latent = [+ { severity: 'high', problem: 'mentor subplot never pays off', location: 'V3' },+ { severity: 'high', problem: 'finale hook is unresolved', location: 'V4' },+ ];+ arcSpies.verifyArc+ .mockImplementationOnce(async () => ({ issues: [first] }))+ .mockImplementationOnce(async () => ({ issues: latent }))+ .mockImplementationOnce(async () => ({ issues: latent }));+ const { seriesId } = await seedComplete();+ await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 6 });+ await waitFor(runFinished(seriesId));++ expect(arcSpies.restoreArcState).not.toHaveBeenCalled();+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;+ expect(last?.pauseKind).toBe('divergence');+ expect(last?.residualFindings).toEqual(latent);+ });+it('a default-cap arc run is unaffected by the divergence guard (maxRounds still wins)', async () => {// Default arc cap is 3; the divergence streak can't reach patience (2) before// the loop hits maxRounds at round 3, so a stalled default run still reportsdiff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.jsindex 853879d947..f73f0dd5f9 100644--- a/server/services/pipeline/seriesAutopilot/childRuns.js+++ b/server/services/pipeline/seriesAutopilot/childRuns.js@@ -8,7 +8,10 @@ import { sleep } from '../../../lib/fileUtils.js';import { recordDomainUsage } from '../../domainUsage.js';import { getSeries } from '../series.js';import { listIssues, getIssue, isStageReady } from '../issues.js';-import { verifyArc, verifyVolume, resolveVerifyIssues, analyzeBeatContinuity, resolveBeatContinuity } from '../arcPlanner.js';+import {+ verifyArc, verifyVolume, resolveVerifyIssues, analyzeBeatContinuity, resolveBeatContinuity,+ snapshotArcState, restoreArcState,+} from '../arcPlanner.js';import {judgeFoundation, applyFoundationFix, foundationGateStatus, foundationFixTarget,residualFindings, DEFAULT_FOUNDATION_THRESHOLD,@@ -19,6 +22,7 @@ import { MAX_ARC_VERIFY_ROUNDS, MAX_BEAT_CONTINUITY_ROUNDS, MAX_FOUNDATION_ROUNDimport {CHILD_POLL_MS, DIVERGENCE_PATIENCE, trackConvergence, convergencePauseReason,divergencePauseReason, foundationPauseReason, foundationDivergenceReason,+ isResolveRegression, regressionPauseReason,} from './convergence.js';import { broadcast, budgetPause, providerOverrideOpts, providerIdOpts, seasonPreserveOpts } from './session.js';import { requiredScriptStages, textReady } from './stepResolver.js';@@ -53,6 +57,10 @@ export async function runArcVerify(seriesId, record) {}let convergence = { best: null, sinceBest: 0 };let changed = false;+ // The findings the previous round's auto-resolve was handed, plus the state of+ // 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;for (let round = 1; round <= maxRounds; round += 1) {if (record.cancelRequested) return { canceled: true };const beforeVerify = await budgetPause();@@ -98,6 +106,29 @@ export async function runArcVerify(seriesId, record) {}return {};}+ // Regression guard: the previous round's resolve came back with MORE+ // blocking findings than it was handed and still hadn't closed them — its+ // rewrite damaged the arc. Put the pre-resolve state back and pause on the+ // residual the user actually had, rather than committing the worse arc and+ // pausing on that (the shape observed on the 2026-08-09 divergence pause,+ // where 1 blocking finding became 3 and then 5). Checked BEFORE the+ // maxRounds/divergence exits so the rollback happens whichever pause the+ // round would otherwise land on.+ if (lastResolve && isResolveRegression(lastResolve.blocking, blocking)) {+ const rollback = await restoreArcState(seriesId, lastResolve.snapshot);+ broadcast(seriesId, {+ type: 'resolve:rollback', scope: 'arc', round,+ before: lastResolve.blocking.length, after: blocking.length,+ reverted: rollback.restored,+ episodesReverted: rollback.episodesRestored,+ });+ return {+ pause: true,+ pauseKind: 'regression',+ reason: regressionPauseReason('arc', lastResolve.blocking.length, blocking.length),+ residual: lastResolve.blocking,+ };+ }if (round === maxRounds) {return { pause: true, pauseKind: 'maxRounds', reason: convergencePauseReason('arc', maxRounds, blocking.length), residual: blocking };}@@ -112,12 +143,16 @@ export async function runArcVerify(seriesId, record) {// step can't overspend the daily cap mid-loop.const beforeResolve = await budgetPause();if (beforeResolve) return beforeResolve;+ // Snapshot before the rewrite lands (two record reads, no LLM spend) so the+ // regression guard at the top of the next round can undo it.+ const snapshot = await snapshotArcState(seriesId);const resolved = await resolveVerifyIssues(seriesId, {findings: blocking,...providerOverrideOpts(record),...seasonPreserveOpts(record),});if (resolved?.applied !== false) changed = true;+ lastResolve = { blocking, snapshot };await recordDomainUsage('cos', { actions: 1 });broadcast(seriesId, {type: 'resolve:round', scope: 'arc', round,diff --git a/server/services/pipeline/seriesAutopilot/convergence.js b/server/services/pipeline/seriesAutopilot/convergence.jsindex e3bd4c3756..54a6b94334 100644--- a/server/services/pipeline/seriesAutopilot/convergence.js+++ b/server/services/pipeline/seriesAutopilot/convergence.js@@ -62,6 +62,66 @@ export function divergencePauseReason(gate, blockingCount, rounds) {+ `${rounds} consecutive ${plural} of auto-resolve. Paused for review. ${fix}, then resume.`;}+// ---------------------------------------------------------------------------+// Auto-resolve REGRESSION guard — one altitude tighter than the divergence+// guard above. Divergence asks "is the loop still making progress?" over several+// rounds and pauses on the state it finds; this asks "did THIS round's edits+// make the draft worse?" so the caller can put the pre-resolve state back before+// pausing. Without it, a resolve pass that rewrites the arc into MORE blocking+// findings than it was handed is committed permanently, and the run pauses on+// damage it caused itself.+// ---------------------------------------------------------------------------++// Normalizer behind `findingFingerprint`, hoisted so the regexes aren't rebuilt+// per finding per round.+const normFindingText = (v) => String(v ?? '')+ .toLowerCase()+ .replace(/[^a-z0-9 ]+/g, ' ')+ .replace(/\s+/g, ' ')+ .trim();++// Deliberately COARSE identity for a verify finding: the verifier re-words its+// prose between calls, so a raw-string match would read every round's findings+// as brand new. Severity + location carry the stable identity; a short prefix of+// the normalized problem separates two findings filed at the same location.+// Coarse is the safe direction here — collapsing two similar findings into one+// print only makes the regression check MORE forgiving (it is a "did anything I+// targeted survive?" set test, not a diff).+export function findingFingerprint(finding) {+ return `${normFindingText(finding?.severity)}|${normFindingText(finding?.location)}`+ + `|${normFindingText(finding?.problem).slice(0, 60)}`;+}++/**+ * True when the round that produced `after` REGRESSED: it left more blocking+ * findings than the `before` set it was asked to close, AND at least one of+ * those targeted findings is still standing. Pure.+ *+ * That second half is what keeps this from rejecting good work: a round that+ * closed everything it targeted and merely exposed findings that were latent+ * underneath is progress, even when the raw count went up, so it is allowed to+ * stand (the divergence guard still catches it if the loop stalls from there).+ * A round that closed nothing and added more is damage.+ */+export function isResolveRegression(before, after) {+ const targeted = Array.isArray(before) ? before : [];+ const current = Array.isArray(after) ? after : [];+ if (current.length <= targeted.length) return false;+ const currentPrints = new Set(current.map(findingFingerprint));+ return targeted.some((f) => currentPrints.has(findingFingerprint(f)));+}++// Pause reason for a gate whose auto-resolve round was reverted — distinct from+// both "ran out of rounds" and "stopped converging": the state the user is being+// handed is the one from BEFORE the round, and saying so is the difference+// between a trustworthy pause and an unexplained rewind.+export function regressionPauseReason(gate, beforeCount, afterCount) {+ const { label, fix } = PAUSE_GATES[gate];+ return `${label} auto-resolve made the draft worse — the round it ran on ${beforeCount} blocking finding(s) `+ + `came back with ${afterCount} and still hadn't closed what it was given, so its edits were reverted. `+ + `Paused for review with the original ${beforeCount} finding(s). ${fix}, then resume.`;+}+// Foundation gate pause reasons (#2176) — the gate converges on a WEIGHTED// SCORE, not a finding count, so it needs its own wording (score vs. threshold)// rather than the finding-count phrasing of convergencePauseReason. Sharesdiff --git a/server/services/pipeline/seriesAutopilot/state.js b/server/services/pipeline/seriesAutopilot/state.jsindex 0147d96755..8201e6a0f6 100644--- a/server/services/pipeline/seriesAutopilot/state.js+++ b/server/services/pipeline/seriesAutopilot/state.js@@ -52,7 +52,7 @@ export const AUTOPILOT_TERMINAL_TYPES = new Set(['complete', 'paused', 'canceled// diagnosis runs BEFORE them, and their content reaches it as the `outcome` +// `reason` arguments instead.export const SIGNAL_FRAME_TYPES = Object.freeze(new Set([- 'note', 'step:skip', 'verify:round', 'resolve:round', 'check:complete',+ 'note', 'step:skip', 'verify:round', 'resolve:round', 'resolve:rollback', 'check:complete','foundation:round', 'foundation:fix', 'child:retry', 'child:escalate','revision:cycle', 'revision:converged', 'gap:filed',]));