Skip to content

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

resolve arc-spine blockers one at a time when a whole-set rewrite keeps regressing

[._.]/ Adam Eivy85ec0b1d1c7e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f5c891535f..c387de14e2 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -36,3 +36,5 @@
- **The Antigravity account-eligibility banner no longer kills an agy run before it can start.** "We're finishing verifying your account eligibility. This usually takes a moment. Please try again shortly." is the front of agy's sign-in handshake, not its verdict — the CLI's own log shows the session authenticating fine (OAuth succeeds, the keyring token refreshes for another hour) and then retrying `loadCodeAssist` while the composer shows that notice. PortOS was treating the banner as an immediate fatal signal and killing the terminal 0.85–1.5s after the prompt was pasted, so the model was never asked for a token. Every agy CoS agent run from 2026-08-07 onward died this way in 3–5s, while the same account and model answered instantly over `--print` and over a PTY whose eligibility was already warm. The signal is now marked self-clearing: both TUI paths hold the session for up to 60s and let the run continue the moment agy starts generating, and only fail over to a fallback provider if the banner outlasts that window with no sign of life. The grace window also suppresses the idle reaper while it's armed, so a waiting run can't be finalized as a bogus `idle-complete` success that scrapes the banner as its answer. Other fallback signals (usage limits, rejected model ids) still fail immediately.
- **A foundation repair that was correctly rolled back no longer reports the rollback as corrupted.** When Series Autopilot reverted a character repair that failed to improve its target dimension, the pause said "checkpoint verification failed after rollback: restored foundation fields did not match the checkpoint" — implying the cast had been left in a half-repaired state. Nothing was actually wrong: undoing a repair is itself a content change, so the universe write path re-stamped `updatedAt` on every canon entry it restored (it has to — that timestamp is the clock the canon→catalog projection uses to carry the revert), and the verification compared those server-owned stamps byte-for-byte along with the authored prose. Every faithful character rollback therefore failed its own check. The comparison now ignores exactly the per-entry fields the write path owns and deliberately does not revert — the LWW timestamp, plus the reference-sheet and render pointers, which are preserved from the live record so a render that finished mid-repair isn't thrown away by the undo — while still comparing all authored content byte-for-byte. When a restore genuinely doesn't come back, the pause now names the fields that failed instead of stating only that something didn't match.
+
+- **Arc verification now banks the fixes that worked instead of discarding a whole round for one bad edit.** The gate resolved its blocking findings as a single rewrite: every finding went to the resolver in one call, and the next check kept or reverted that candidate as a unit. So a rewrite that cleanly closed two problems and broke a third was thrown away in full, and the gate ended up holding nothing — on the observed run it reached a verified best of 2 blockers, watched the next pass come back with 5 and the corrective retry with 3, correctly preserved the 2-blocker draft both times, and then paused for review with seven of its twelve permitted rounds unspent. The rollback guard is unchanged and still refuses any candidate that grows the blocking set or worsens its severity mix. What is new is what happens after the corrective retry is spent: when the residual has more than one finding, the gate now takes it apart and tries the findings one at a time from the best verified plan. Each attempt is its own transaction — snapshot, resolve that one finding, re-run the same verification the gate uses, and keep the edit only when the finding it targeted is actually gone and what it left behind is not a regression by the same count-then-severity rule the whole-round guard applies — so which trades survive no longer depends on which tier judged them. Anything else is restored on the spot, so a poisoned finding now costs only its own attempt instead of its neighbours' repairs, and the surviving fixes are re-verified together before the gate is allowed to clear. Closure is judged the same way the rollback guard judges identity, so a verifier that merely restates a standing problem in fresh words can't pass as a fix. The pass is bounded by a spend budget counted in provider calls — so a wide series, whose every check costs one call per volume, gets fewer attempts rather than a proportionally larger bill — skipped when only one finding is left (that is the corrective retry again, at twice the price), never run without a round left to verify what it kept, capped per run by `maxArcIsolationAttempts`, and switched off entirely by that or by `maxArcResolveRetries: 0`. The dry-run plan now includes its worst case, so the estimate you approve a run from still bounds the gate. The live status line reports each isolated attempt and whether it was kept.
diff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsx
index 5f612c1f88..9196011fce 100644
--- a/client/src/components/pipeline/AutopilotPanel.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.jsx
@@ -277,6 +277,11 @@ function frameLabel(f) {
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.retrying ? ', retrying from the best state' : ''}`;
+ // 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.
+ 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'}`;
// #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/server/routes/pipeline/autopilot.js b/server/routes/pipeline/autopilot.js
index b8e0de8ef5..fdfd1b9a83 100644
--- a/server/routes/pipeline/autopilot.js
+++ b/server/routes/pipeline/autopilot.js
@@ -94,6 +94,15 @@ const autopilotStartSchema = z.object({
// 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 cap on the arc-verify gate's per-finding isolation attempts (#3780):
+ // once the corrective passes above are spent, how many residual findings the
+ // gate may try ONE AT A TIME from the restored best state, keeping each patch
+ // only if it closes its own target without worsening the set. 0 = no isolation
+ // (revert and pause as before). Per-run only; when omitted the gate derives its
+ // own budget from MAX_ARC_ISOLATION_CALLS and what a verification costs on this
+ // series, and `maxArcResolveRetries: 0` opts out of isolation with it. Shares
+ // the convergence ceiling so a direct API call can't request an absurd budget.
+ maxArcIsolationAttempts: 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/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index 6bed4d58c4..312910efc9 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -539,8 +539,10 @@ describe('resolveNextStep (pure)', () => {
expect(plan.every((p) => Number.isFinite(p.estActions))).toBe(true);
const byKind = Object.fromEntries(plan.map((p) => [p.kind, p]));
// verifyArc: each round checks the whole arc + one volume, then resolves
- // between rounds → 3*(1+1)+2 = 8 actions.
- expect(byKind.verifyArc.estActions).toBe(8);
+ // between rounds → 3*(1+1)+2 = 8 — plus the per-finding isolation pass the
+ // gate can escalate to inside a round (#3780): an attempt costs a resolve +
+ // an arc verify + one volume verify = 3, so the 8-call budget buys 2 → +6.
+ expect(byKind.verifyArc.estActions).toBe(14);
// textStages: one child action per not-yet-text-ready issue (2 here).
expect(byKind.textStages.estActions).toBe(2);
// Pure-gate steps that bill nothing against the cap are zero-cost.
@@ -554,10 +556,15 @@ describe('resolveNextStep (pure)', () => {
.find((p) => p.kind === kind)?.estActions;
// 0 rounds → the loop is skipped → 0 actions.
expect(actionsFor({ maxArcVerifyRounds: 0 }, 'verifyArc')).toBe(0);
- // 1 round → whole-arc + one-volume verify, no resolve → 2 actions.
+ // 1 round → whole-arc + one-volume verify, no resolve → 2 actions. Isolation
+ // needs a second round to verify what it kept, so it projects nothing here.
expect(actionsFor({ maxArcVerifyRounds: 1 }, 'verifyArc')).toBe(2);
- // 4 rounds → 4 arc verifies + 4 volume verifies + 3 resolves → 11 actions.
- expect(actionsFor({ maxArcVerifyRounds: 4 }, 'verifyArc')).toBe(11);
+ // 4 rounds → 4 arc verifies + 4 volume verifies + 3 resolves → 11, plus the
+ // isolation pass's 2 attempts × 3 calls (#3780) → 17.
+ expect(actionsFor({ maxArcVerifyRounds: 4 }, 'verifyArc')).toBe(17);
+ // …and a run that declined it gets the round-based estimate back.
+ expect(actionsFor({ maxArcVerifyRounds: 4, maxArcIsolationAttempts: 0 }, 'verifyArc')).toBe(11);
+ expect(actionsFor({ maxArcVerifyRounds: 4, maxArcResolveRetries: 0 }, 'verifyArc')).toBe(11);
// Editorial review follows the same convergence shape.
expect(actionsFor({ maxEditorialRounds: 2 }, 'editorialReview')).toBe(3);
});
@@ -1401,6 +1408,65 @@ describe('trackConvergence (pure divergence/oscillation guard — #1571)', () =>
});
});
+describe('isIsolatedFixSafe (pure per-finding patch acceptance, #3780)', () => {
+ const { isIsolatedFixSafe } = autopilot;
+ const f = (problem, location = 'V1', severity = 'high') => ({ severity, location, problem });
+ const target = f('volume 1 and volume 2 both stage the first eclipse');
+ const other = f('mentor subplot never pays off', 'V3');
+
+ it('keeps a patch that closed its target and left the rest alone', () => {
+ expect(isIsolatedFixSafe(target, [target, other], [other])).toBe(true);
+ });
+
+ it('keeps an even trade — the target gone, one equally-severe finding in its place', () => {
+ // Same shape the round loop's checkpoint already accepts: a tie can be real
+ // causal progress, and the divergence guard catches a gate that only trades.
+ expect(isIsolatedFixSafe(target, [target, other], [other, f('finale hook is unresolved', 'V4')])).toBe(true);
+ });
+
+ it('rejects a patch that only RE-WORDED its target', () => {
+ // The verifier restates a standing defect freely; treating fresh prose as
+ // closure would bank a patch that fixed nothing and keep its collateral.
+ expect(isIsolatedFixSafe(target, [target, other], [
+ f('the first eclipse is staged twice — once in each opening volume', 'Volume 2 opening'),
+ ])).toBe(false);
+ });
+
+ it('rejects a patch that grew the blocking set', () => {
+ expect(isIsolatedFixSafe(target, [target, other], [
+ other, f('finale hook is unresolved', 'V4'), f('timeline of the siege runs backwards', 'V6'),
+ ])).toBe(false);
+ });
+
+ it('rejects a same-size swap that made the set MORE severe', () => {
+ // Count alone can't see this one: a `medium` traded for a `high` is a worse
+ // draft at the same size. Judged by the SAME `isBlockingSetRegression` the
+ // whole-round rollback guard uses, so a trade the round tier would revert is
+ // never banked by the isolation tier instead.
+ const mediumTarget = f('volume 1 and volume 2 both stage the first eclipse', 'V1', 'medium');
+ expect(isIsolatedFixSafe(
+ mediumTarget,
+ [mediumTarget, f('pacing sags mid-volume', 'V2', 'medium')],
+ [f('pacing sags mid-volume', 'V2', 'medium'), f('protagonist goal vanishes', 'V5', 'high')],
+ )).toBe(false);
+ });
+
+ it('keeps a same-size swap that made the set LESS severe', () => {
+ // The mirror of the case above — trading a `high` down to a `medium` at an
+ // unchanged count is progress, not a regression.
+ expect(isIsolatedFixSafe(
+ target,
+ [target, other],
+ [other, f('pacing sags mid-volume', 'V2', 'medium')],
+ )).toBe(true);
+ });
+
+ it('tolerates missing/garbage inputs', () => {
+ expect(isIsolatedFixSafe(target, undefined, undefined)).toBe(true);
+ expect(isIsolatedFixSafe(target, null, [target])).toBe(false);
+ });
+});
+
describe('isResolveRegression (pure resolve-round damage check)', () => {
const { isResolveRegression, sameFinding, findingTextOverlap } = autopilot;
const f = (problem, location = 'V1', severity = 'high') => ({ severity, location, problem });
@@ -2329,6 +2395,11 @@ describe('autopilot conductor', () => {
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 })));
+ // Both isolation attempts come back worse than the 2-blocker checkpoint too,
+ // so nothing is retained and the gate still pauses on the checkpoint (#3780).
+ arcSpies.verifyArc
+ .mockImplementationOnce(async () => ({ issues: holes(4, 'isolated 1') }))
+ .mockImplementationOnce(async () => ({ issues: holes(4, 'isolated 2') }));
const initialSnapshot = { marker: 'initial', arc: null, seasons: [], episodes: [] };
const bestSnapshot = { marker: 'best', arc: null, seasons: [], episodes: [] };
arcSpies.snapshotArcState
@@ -2340,12 +2411,13 @@ describe('autopilot conductor', () => {
await waitFor(runFinished(seriesId));
// 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);
+ // corrective pass; round 4 regresses again, so the gate splits the residual
+ // 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);
expect(arcSpies.restoreArcState).toHaveBeenCalledWith(seriesId, bestSnapshot);
const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
expect(last?.pauseKind).toBe('regression');
@@ -2362,6 +2434,126 @@ describe('autopilot conductor', () => {
expect(series.autopilot?.discardedFindings).toEqual(rounds[3]);
});
+ it('keeps an independently safe fix by isolating the residual one finding at a time (#3780)', async () => {
+ // The 2026-08-11 verifyArcSpine stall: the gate reached a verified best of 2
+ // blockers, then a normal resolve came back with 5 and the corrective retry
+ // with 3. Both were rewrites of the WHOLE residual, so both were reverted
+ // whole — and the run paused on 2 after 5 of 12 permitted rounds without
+ // retaining a single fix. Now the spent corrective budget escalates to
+ // per-finding isolation: each finding is resolved alone and kept only if it
+ // closes itself without growing the set.
+ const eclipse = { severity: 'high', problem: 'volume 1 and volume 2 both stage the first eclipse', location: 'V1' };
+ const mentor = { severity: 'high', problem: 'mentor subplot never pays off', location: 'V3' };
+ const finale = { severity: 'high', problem: 'finale hook contradicts prologue promise', location: 'V4' };
+ const motive = { severity: 'high', problem: 'antagonist motive changes without cause', location: 'V5' };
+ const siege = { severity: 'high', problem: 'timeline of the siege runs backwards', location: 'V6' };
+ // Ordered log of what the gate actually billed, so the assertions below can
+ // see that the round after the isolation pass skips its verify.
+ const billed = [];
+ arcSpies.verifyArc.mockReset();
+ [
+ [eclipse, mentor], // round 1 — the checkpoint
+ [eclipse, mentor, finale], // round 2 — regressed, reverted + retried
+ [eclipse, mentor, finale, motive], // round 3 — regressed again, retries spent
+ [mentor], // isolate #1 (eclipse) — closed it, kept
+ [mentor, siege], // isolate #2 (mentor) — still standing, reverted
+ // Round 4 bills NO verify: nothing edited the plan between isolate #2's
+ // revert and it, so the round reuses isolate #1's verification.
+ [mentor], // round 5 — after round 4's resolve
+ [], // round 6 — clean
+ ].forEach((issues) => arcSpies.verifyArc.mockImplementationOnce(async () => {
+ billed.push('verify');
+ return { issues };
+ }));
+ for (let i = 0; i < 6; i += 1) {
+ arcSpies.resolveVerifyIssues.mockImplementationOnce(async () => {
+ billed.push('resolve');
+ return { applied: true };
+ });
+ }
+
+ const { seriesId } = await seedComplete();
+ const frames = [];
+ const handler = (p) => frames.push(p);
+ autopilot.autopilotEvents.on(seriesId, handler);
+ await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 6 });
+ await waitFor(runFinished(seriesId));
+ autopilot.autopilotEvents.off(seriesId, handler);
+
+ // Each isolated attempt resolves exactly one finding, and carries the
+ // rejected whole-set candidate's findings as the failure mode to avoid.
+ expect(arcSpies.resolveVerifyIssues.mock.calls[2][1]).toMatchObject({
+ findings: [eclipse],
+ avoid: [eclipse, mentor, finale, motive],
+ });
+ expect(arcSpies.resolveVerifyIssues.mock.calls[3][1]).toMatchObject({ findings: [mentor] });
+ // The rejected attempt is reverted on its own — the kept one is not.
+ const isolated = frames.filter((f) => f.type === 'resolve:isolate');
+ expect(isolated).toHaveLength(2);
+ expect(isolated[0]).toMatchObject({ scope: 'arcSpine', attempt: 1, before: 2, after: 1, kept: true });
+ expect(isolated[1]).toMatchObject({ attempt: 2, before: 1, after: 2, kept: false });
+ // Two whole-round rollbacks plus the one rejected isolated patch.
+ expect(arcSpies.restoreArcState).toHaveBeenCalledTimes(3);
+ // Round 3's verify, then the two isolated attempts (resolve→verify each),
+ // then round 4's resolve with NO verify in front of it: nothing edited the
+ // plan between isolate #2's revert and that round, so it re-uses the
+ // verification isolate #1 already billed rather than buying the same answer
+ // for another arc + per-volume call.
+ expect(billed.slice(4, 11)).toEqual([
+ 'verify', 'resolve', 'verify', 'resolve', 'verify', 'resolve', 'verify',
+ ]);
+ // The rollback frame promises the retry the isolation pass is about to make,
+ // so the user isn't told the gate is done when it has another move left.
+ expect(frames.filter((f) => f.type === 'resolve:rollback').at(-1)).toMatchObject({ best: 2, retrying: true });
+ // …and the gate clears from the isolated state instead of pausing on 2.
+ 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('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 rather
+ // than billing a resolve + a verify for it.
+ const hole = { 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}` });
+ arcSpies.verifyArc.mockReset();
+ [1, 3, 5].forEach((n) => arcSpies.verifyArc.mockImplementationOnce(async () => ({
+ issues: [hole, ...Array.from({ length: n - 1 }, (_, i) => extra(i))],
+ })));
+
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 6 });
+ await waitFor(runFinished(seriesId));
+
+ // Three verifies, two resolves — the initial pass and the corrective retry.
+ expect(arcSpies.verifyArc).toHaveBeenCalledTimes(3);
+ expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(2);
+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.pauseKind).toBe('regression');
+ });
+
+ it('honors maxArcResolveRetries: 0 as a full opt-out of isolation too', async () => {
+ // The knob means "no corrective spend on a reverted round" — a run that set
+ // it must not get the (larger) per-finding fan-out instead.
+ 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(2, 'initial') }))
+ .mockImplementationOnce(async () => ({ issues: holes(4, '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(2, 'initial'));
+ });
+
it('a blocker increase reaches the regression guard even when it lands on the round cap', async () => {
// Guard-ordering check: the regression branch is evaluated before the
// maxRounds exit, so growth ON the final round still rolls back and reports
diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.js
index e3c0cbcba7..c1cb23b094 100644
--- a/server/services/pipeline/seriesAutopilot/childRuns.js
+++ b/server/services/pipeline/seriesAutopilot/childRuns.js
@@ -20,12 +20,12 @@ 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,
- MAX_ARC_RESOLVE_RETRIES,
+ MAX_ARC_RESOLVE_RETRIES, resolveArcIsolationAttempts,
} from './config.js';
import {
CHILD_POLL_MS, DIVERGENCE_PATIENCE, trackConvergence, convergencePauseReason,
divergencePauseReason, foundationPauseReason, foundationDivergenceReason,
- regressionPauseReason, sameFinding, isBlockingSetRegression,
+ regressionPauseReason, sameFinding, isBlockingSetRegression, isIsolatedFixSafe,
} from './convergence.js';
import { broadcast, budgetPause, providerOverrideOpts, providerIdOpts, roleLlm, seasonPreserveOpts } from './session.js';
import { requiredScriptStages, textReady } from './stepResolver.js';
@@ -50,6 +50,25 @@ function arcResolveRetryBudget(record) {
return Number.isInteger(v) ? Math.max(0, v) : MAX_ARC_RESOLVE_RETRIES;
}
+// The gate's one way to bill a resolve pass: same options, same usage
+// 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 }) {
+ const resolved = await resolveVerifyIssues(seriesId, {
+ findings,
+ avoid,
+ spineOnly,
+ ...providerOverrideOpts(record),
+ ...seasonPreserveOpts(record),
+ });
+ await recordDomainUsage('cos', { actions: 1 });
+ return resolved;
+}
+
+// Episode synopses one resolve pass actually rewrote, for the telemetry frames.
+const editedCount = (resolved) => (Array.isArray(resolved?.episodesResolved) ? resolved.episodesResolved.length : 0);
+
function finishPlanningMutation(record, peerLatch) {
record.runState[peerLatch] = false;
record.runState.planningGateHandoffs = (record.runState.planningGateHandoffs || 0) + 1;
@@ -67,6 +86,122 @@ async function waitForChild(isActive, record) {
}
}
+/**
+ * One full pass of the arc gate's verifier at the altitude the gate runs at: the
+ * arc spine alone in `spineOnly` mode, else the arc plus every volume synopsis.
+ * Returns `{ findings, blocking, volumesChecked }`, or `{ outcome }` carrying the
+ * run-ending result (a cancel or a budget pause) it hit partway through.
+ *
+ * Extracted so the per-finding isolation pass re-verifies EXACTLY the way the
+ * round loop does. A second hand-rolled verify would be free to drift to a
+ * different altitude, and an isolated patch accepted on a verification this gate
+ * never runs is a patch nothing actually judged.
+ */
+async function verifyArcBlocking(seriesId, record, { spineOnly }) {
+ const beforeVerify = await budgetPause();
+ if (beforeVerify) return { outcome: beforeVerify };
+ const { issues: arcFindings } = await verifyArc(seriesId, {
+ ...providerOverrideOpts(record, 'judge'),
+ spineOnly,
+ });
+ await recordDomainUsage('cos', { actions: 1 });
+ // The spine round judges an episode-empty plan and checks no volumes, so it
+ // has no use for the series record — don't read it just to iterate nothing.
+ const seasons = spineOnly ? [] : ((await getSeries(seriesId)).seasons || []);
+ const volumeFindings = [];
+ for (const season of seasons) {
+ if (record.cancelRequested) return { outcome: { canceled: true } };
+ const beforeVolumeVerify = await budgetPause();
+ if (beforeVolumeVerify) return { outcome: beforeVolumeVerify };
+ const { issues } = await verifyVolume(seriesId, season.id, {
+ ...providerOverrideOpts(record, 'judge'),
+ // This gate's resolver rewrites the synopsis-level arc/volumes, not
+ // issue beats. Existing beat sheets get their own continuity gate later.
+ synopsisOnly: true,
+ });
+ await recordDomainUsage('cos', { actions: 1 });
+ for (const finding of issues) {
+ volumeFindings.push({
+ ...finding,
+ volumeId: season.id,
+ location: `volume ${season.number ?? '?'}${finding.location ? ` — ${finding.location}` : ''}`,
+ });
+ }
+ }
+ const findings = [...arcFindings, ...volumeFindings];
+ return {
+ findings,
+ blocking: findings.filter((finding) => record.options.blockingSets.arc.has(finding.severity)),
+ volumesChecked: seasons.length,
+ };
+}
+
+/**
+ * Resolve a residual one finding at a time, transactionally (#3780).
+ *
+ * The round loop rewrites the whole residual in one call and keeps or reverts
+ * that candidate as a unit, so a rewrite that closed two findings cleanly and
+ * broke a third leaves the gate holding nothing. This pass runs from the state
+ * the caller has just restored (the best verified one) and, per finding:
+ * snapshot → resolve THAT finding alone → re-verify the same way the gate does →
+ * keep the patch only if `isIsolatedFixSafe`, else put the snapshot straight
+ * back. So each accepted patch is one that demonstrably closed its own target
+ * without growing or worsening the set, and a poisoned finding costs only its
+ * own attempt instead of its neighbours' repairs.
+ *
+ * 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
+ * hands to its next round instead of re-billing the identical call — plus
+ * `outcome` when the run ended mid-pass.
+ */
+async function isolateArcFindings(seriesId, record, { scope, round, spineOnly, baseline, avoid, attemptsLeft }) {
+ // The last verification that DESCRIBES THE STORE: it advances only on an
+ // accepted patch, because a rejected one is rolled straight back to the state
+ // its predecessor verified. So later targets are judged against what the
+ // earlier ones left behind, and the caller can trust this as its next round's
+ // verification. Null until the first patch is kept — the caller already holds
+ // the baseline's verification in that case.
+ let standing = null;
+ let accepted = 0;
+ let attempts = 0;
+ const blocking = () => standing?.blocking ?? baseline;
+ for (const target of baseline) {
+ if (attempts >= attemptsLeft) break;
+ // An earlier accepted patch may have taken this one with it — paying a
+ // resolve + a verify to re-close a finding that is already gone is pure spend.
+ if (!blocking().some((finding) => sameFinding(target, finding))) continue;
+ if (record.cancelRequested) return { accepted, attempts, verified: standing, outcome: { canceled: true } };
+ const beforeResolve = await budgetPause();
+ if (beforeResolve) return { accepted, attempts, verified: standing, outcome: beforeResolve };
+ attempts += 1;
+ const before = blocking().length;
+ const snapshot = await snapshotArcState(seriesId);
+ const resolved = await resolveArcFindings(seriesId, record, { findings: [target], avoid, spineOnly });
+ const verified = await verifyArcBlocking(seriesId, record, { spineOnly });
+ if (verified.outcome) {
+ // The run is ending mid-attempt, so this patch can never be judged. Put
+ // the snapshot back rather than leaving an unverified rewrite in a plan
+ // the user is about to be handed.
+ await restoreArcState(seriesId, snapshot);
+ return { accepted, attempts, verified: standing, outcome: verified.outcome };
+ }
+ const kept = isIsolatedFixSafe(target, blocking(), verified.blocking);
+ if (kept) {
+ accepted += 1;
+ standing = verified;
+ } else {
+ await restoreArcState(seriesId, snapshot);
+ }
+ broadcast(seriesId, {
+ type: 'resolve:isolate', scope, round, attempt: attempts,
+ target: typeof target.location === 'string' ? target.location : '',
+ before, after: verified.blocking.length, kept, episodesEdited: editedCount(resolved),
+ });
+ }
+ return { accepted, attempts, verified: standing };
+}
+
export async function runArcVerify(seriesId, record, { spineOnly = false } = {}) {
const maxRounds = Number.isInteger(record.options.maxArcVerifyRounds)
? record.options.maxArcVerifyRounds
@@ -101,41 +236,26 @@ export async function runArcVerify(seriesId, record, { spineOnly = false } = {})
// 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);
+ // Single-finding attempts the isolation pass may still spend (#3780). Counted
+ // across the whole gate, not per rollback, so a resolver that keeps trading
+ // blockers can't turn every regression into another fan-out of provider calls.
+ // Resolved on first use, when the round's own verification has said what a
+ // verification costs on this series.
+ let isolationLeft = null;
+ // A verification already run against the state now in the store — the last one
+ // the isolation pass billed. The next round is a re-confirmation of exactly
+ // that state (nothing edits it in between), so re-running the gate's verifier
+ // would buy the same answer for another 1 + volumes provider calls.
+ let seededVerify = null;
for (let round = 1; round <= maxRounds; round += 1) {
if (record.cancelRequested) return { canceled: true };
- const beforeVerify = await budgetPause();
- if (beforeVerify) return beforeVerify;
- const { issues: arcFindings } = await verifyArc(seriesId, {
- ...providerOverrideOpts(record, 'judge'),
- spineOnly,
- });
- await recordDomainUsage('cos', { actions: 1 });
- const series = await getSeries(seriesId);
- const volumeFindings = [];
- for (const season of spineOnly ? [] : (series.seasons || [])) {
- if (record.cancelRequested) return { canceled: true };
- const beforeVolumeVerify = await budgetPause();
- if (beforeVolumeVerify) return beforeVolumeVerify;
- const { issues } = await verifyVolume(seriesId, season.id, {
- ...providerOverrideOpts(record, 'judge'),
- // This gate's resolver rewrites the synopsis-level arc/volumes, not
- // issue beats. Existing beat sheets get their own continuity gate later.
- synopsisOnly: true,
- });
- await recordDomainUsage('cos', { actions: 1 });
- for (const finding of issues) {
- volumeFindings.push({
- ...finding,
- volumeId: season.id,
- location: `volume ${season.number ?? '?'}${finding.location ? ` — ${finding.location}` : ''}`,
- });
- }
- }
- const findings = [...arcFindings, ...volumeFindings];
- const blocking = findings.filter((finding) => record.options.blockingSets.arc.has(finding.severity));
+ const verified = seededVerify || await verifyArcBlocking(seriesId, record, { spineOnly });
+ seededVerify = null;
+ if (verified.outcome) return verified.outcome;
+ const { findings, blocking } = verified;
broadcast(seriesId, {
type: 'verify:round', scope, round, findings: findings.length,
- blocking: blocking.length, volumesChecked: spineOnly ? 0 : (series.seasons || []).length,
+ blocking: blocking.length, volumesChecked: verified.volumesChecked,
});
if (blocking.length === 0) {
record.runState[spineOnly ? 'arcSpineVerified' : 'arcVerified'] = true;
@@ -162,17 +282,27 @@ export async function runArcVerify(seriesId, record, { spineOnly = false } = {})
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;
+ // Neither second chance is worth its LLM call without a round left to
+ // VERIFY what it wrote: 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 roundLeftToVerify = round < maxRounds;
+ const canRetry = retriesLeft > 0 && roundLeftToVerify;
+ if (isolationLeft === null) {
+ isolationLeft = resolveArcIsolationAttempts(record.options, verified.volumesChecked);
+ }
+ // Escalation after the whole-set corrective passes are spent: split the
+ // residual and try its findings one at a time (#3780). Only worth its spend
+ // on a residual that can actually be taken apart — isolating a lone finding
+ // re-issues the exact call the corrective pass just made.
+ const canIsolate = isolationLeft > 0 && roundLeftToVerify && rollbackTarget.blocking.length > 1;
broadcast(seriesId, {
type: 'resolve:rollback', scope, round,
before: lastResolve.blocking.length, after: blocking.length,
best: rollbackTarget.blocking.length,
reverted: rollback.restored,
episodesReverted: rollback.episodesRestored,
- retrying: canRetry,
+ retrying: canRetry || canIsolate,
});
// Corrective pass (#3781): the revert above put the best verified state
// back, so re-run the resolver against exactly the findings that state
@@ -188,25 +318,45 @@ export async function runArcVerify(seriesId, record, { spineOnly = false } = {})
if (record.cancelRequested) return { canceled: true };
const beforeRetry = await budgetPause();
if (beforeRetry) return beforeRetry;
- const retried = await resolveVerifyIssues(seriesId, {
- findings: rollbackTarget.blocking,
- avoid: discarded,
- spineOnly,
- ...providerOverrideOpts(record),
- ...seasonPreserveOpts(record),
+ const retried = await resolveArcFindings(seriesId, record, {
+ findings: rollbackTarget.blocking, avoid: discarded, spineOnly,
});
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, round, retry: true,
- episodesEdited: Array.isArray(retried?.episodesResolved) ? retried.episodesResolved.length : 0,
+ type: 'resolve:round', scope, round, retry: true, episodesEdited: editedCount(retried),
});
continue;
}
+ // Per-finding isolation (#3780): the whole-set passes have now failed
+ // twice on this residual, but "the set can't be rewritten safely" is not
+ // "no finding in it can be fixed". Falls through to the pause below when
+ // nothing was retained.
+ if (canIsolate) {
+ const isolated = await isolateArcFindings(seriesId, record, {
+ scope, round, spineOnly,
+ baseline: rollbackTarget.blocking,
+ avoid: discarded,
+ attemptsLeft: isolationLeft,
+ });
+ isolationLeft -= isolated.attempts;
+ if (isolated.outcome) return isolated.outcome;
+ if (isolated.accepted > 0) {
+ changed = true;
+ // Every retained patch was verified on its own, and acceptance forbids
+ // a bigger or more severe set — so the composite state is at least as
+ // good as the checkpoint and becomes the new one. Its verification is
+ // handed to the next round, which is where the gate is allowed to
+ // clear: nothing advances on the per-finding checks alone.
+ bestVerified = { blocking: isolated.verified.blocking, snapshot: await snapshotArcState(seriesId) };
+ lastResolve = bestVerified;
+ seededVerify = isolated.verified;
+ continue;
+ }
+ }
return {
pause: true,
pauseKind: 'regression',
@@ -265,25 +415,23 @@ export async function runArcVerify(seriesId, record, { spineOnly = false } = {})
// episode-empty plan, so its resolver may only patch the arc + volumes
// (#3789). The later full arc gate keeps episode corrections, which is the
// only place they can actually close a finding.
- const resolved = await resolveVerifyIssues(seriesId, {
- findings: blocking,
- spineOnly,
- ...providerOverrideOpts(record),
- ...seasonPreserveOpts(record),
- });
+ const resolved = await resolveArcFindings(seriesId, record, { findings: blocking, spineOnly });
if (resolved?.applied !== false) changed = true;
lastResolve = { blocking, snapshot };
- await recordDomainUsage('cos', { actions: 1 });
broadcast(seriesId, {
- type: 'resolve:round', scope, round,
- episodesEdited: Array.isArray(resolved?.episodesResolved) ? resolved.episodesResolved.length : 0,
+ type: 'resolve:round', scope, round, episodesEdited: editedCount(resolved),
});
}
return {};
}
// Whole-manuscript beat-continuity convergence loop (#1510). Mirrors
-// runArcVerify one altitude down: verify the whole-book beat corpus, and on
+// runArcVerify's SHAPE one altitude down, not its guards: it has no checkpoint,
+// no rollback of a regressive round (#3781) and no per-finding isolation
+// (#3780), because none of those are reachable without a beat snapshot/restore
+// pair — the arc gate's rest on `snapshotArcState`/`restoreArcState`, and beats
+// have no equivalent. That, not oversight, is the asymmetry: verify the
+// whole-book beat corpus, and on
// blocking findings resolve them by rewriting the offending issues' beats in
// place (resolveBeatContinuity → applyBeatResolutions, no beat-sheet
// regeneration), then re-verify. Bounded; pauses with the residual on
diff --git a/server/services/pipeline/seriesAutopilot/config.js b/server/services/pipeline/seriesAutopilot/config.js
index c0e63d2448..7983414850 100644
--- a/server/services/pipeline/seriesAutopilot/config.js
+++ b/server/services/pipeline/seriesAutopilot/config.js
@@ -57,6 +57,39 @@ export const MAX_CHILD_RETRIES = 1;
// ends the run is not a spend knob worth a UI.
export const MAX_ARC_RESOLVE_RETRIES = 1;
+// Per-finding ISOLATION budget for the arc-verify gate (#3780), counted in
+// PROVIDER CALLS across the whole gate. Once the corrective passes above are
+// spent, the gate stops rewriting the residual as one unit and tries its
+// findings one at a time from the best verified state, keeping only the patches
+// that close their target without growing the blocking set — so a residual that
+// contains one independently safe fix and one poisoned one no longer loses both.
+// Counted in calls rather than attempts because an attempt bills a resolve plus
+// a full verification, and the full-arc gate's verification costs one call per
+// volume: 8 calls buys the spine gate 4 attempts and a 6-volume arc 1, instead
+// of letting a wide series pay 5× for the same number. `maxArcIsolationAttempts`
+// overrides it per run (in attempts), and `maxArcResolveRetries: 0` opts out of
+// isolation with it — a run that declined corrective spend declines this too.
+export const MAX_ARC_ISOLATION_CALLS = 8;
+
+// Effective isolation budget for one arc-verify gate, in ATTEMPTS: an explicit
+// per-run `maxArcIsolationAttempts` wins; else a run that declined corrective
+// resolve spend (`maxArcResolveRetries: 0`) declines this too; else the call
+// budget above divided by what one attempt costs on this series — a resolve plus
+// a full verification, which is one call for the arc and one per volume checked.
+// Shared with the dry-run plan so the projected worst case and the spend the gate
+// can actually reach are computed from one formula.
+export function resolveArcIsolationAttempts(options = {}, volumesChecked = 0) {
+ const explicit = options?.maxArcIsolationAttempts;
+ if (Number.isInteger(explicit)) return Math.max(0, explicit);
+ const retries = options?.maxArcResolveRetries;
+ if (Number.isInteger(retries) && retries <= 0) return 0;
+ return Math.max(1, Math.floor(MAX_ARC_ISOLATION_CALLS / (2 + volumesChecked)));
+}
+
+// Worst-case actions one gate's isolation pass can bill, for the dry-run plan.
+export const arcIsolationActions = (options, volumesChecked = 0) =>
+ resolveArcIsolationAttempts(options, volumesChecked) * (2 + volumesChecked);
+
// 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
diff --git a/server/services/pipeline/seriesAutopilot/convergence.js b/server/services/pipeline/seriesAutopilot/convergence.js
index f6743567ef..8afc52c60a 100644
--- a/server/services/pipeline/seriesAutopilot/convergence.js
+++ b/server/services/pipeline/seriesAutopilot/convergence.js
@@ -223,6 +223,36 @@ export function isBlockingSetRegression(before, after) {
return false;
}
+// ---------------------------------------------------------------------------
+// Per-finding ISOLATION acceptance (#3780) — one altitude tighter again. The
+// guards above judge a WHOLE resolve round; this judges one single-finding patch
+// (see `isolateArcFindings` in childRuns.js for what the pass is FOR).
+// ---------------------------------------------------------------------------
+
+/**
+ * May an isolated single-finding patch be KEPT? True only when it did the job it
+ * was billed for and cost nothing elsewhere: `target` is gone from the re-verify,
+ * and what it left behind is not a regression on the set it started from. Pure.
+ *
+ * "Not a regression" is `isBlockingSetRegression` — deliberately the SAME
+ * operational definition of worse the whole-round rollback guard uses, so which
+ * trades survive doesn't depend on which tier happened to judge them. Ties are
+ * therefore allowed at an unchanged severity mix: a patch that closed its target
+ * and exposed one equally-severe finding next door is the same "different,
+ * narrower findings" trade the round loop's checkpoint already accepts, and the
+ * divergence guard still catches a gate that only ever trades.
+ *
+ * Closure is decided by `sameFinding`, not by prose equality, for the same
+ * reason the regression guard is: the verifier restates a standing defect in
+ * fresh words at a re-labelled location every call, and reading that as "closed"
+ * would accept a patch that changed nothing but the wording.
+ */
+export function isIsolatedFixSafe(target, before, after) {
+ const current = Array.isArray(after) ? after : [];
+ if (current.some((c) => sameFinding(target, c))) return false;
+ return !isBlockingSetRegression(before, current);
+}
+
// 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
diff --git a/server/services/pipeline/seriesAutopilot/dryRun.js b/server/services/pipeline/seriesAutopilot/dryRun.js
index 89bdbe65ec..9f66e4f074 100644
--- a/server/services/pipeline/seriesAutopilot/dryRun.js
+++ b/server/services/pipeline/seriesAutopilot/dryRun.js
@@ -10,6 +10,7 @@ import { resolveReadinessGate } from '../editorialScore.js';
import {
MAX_ARC_VERIFY_ROUNDS, MAX_FOUNDATION_ROUNDS, MAX_BEAT_CONTINUITY_ROUNDS, MAX_EDITORIAL_ROUNDS,
resolveAutopilotCheckPauseThreshold, resolveAutopilotRevision, wantsTeaser, wantsVisual,
+ arcIsolationActions,
} from './config.js';
import { roundsNote, convergenceLoopActions, VISUAL_DRAFT_ENABLED } from './convergence.js';
import { orderedIssues, byNumber, issueHasBeats, textReady, wantsComic, visualReady } from './stepResolver.js';
@@ -98,11 +99,17 @@ export function buildDryRunPlan(series, issues, options, costContext = {}) {
}
}
const arcRounds = Number.isInteger(options?.maxArcVerifyRounds) ? options.maxArcVerifyRounds : MAX_ARC_VERIFY_ROUNDS;
+ // A gate that can reach its regression guard can also reach the per-finding
+ // isolation pass (#3780), which bills a resolve + a full verification per
+ // attempt INSIDE a round — spend the round-based estimates above don't model.
+ // Needs two rounds to be reachable at all (a rollback, then a round to verify
+ // what isolation kept), so a 1-round gate projects none.
+ const isolationActions = (volumes) => (arcRounds > 1 ? arcIsolationActions(options, volumes) : 0);
plan.push({
kind: 'verifyArcSpine',
count: 1,
note: `${roundsNote(arcRounds)}; protected intent + macro arc before issue generation`,
- estActions: convergenceLoopActions(arcRounds),
+ estActions: convergenceLoopActions(arcRounds) + isolationActions(0),
});
const emptySeasons = seasons.filter((s) => !ordered.some((i) => i.seasonId === s.id));
if (emptySeasons.length) plan.push({ kind: 'generateEpisodes', count: emptySeasons.length, estActions: emptySeasons.length });
@@ -115,7 +122,7 @@ export function buildDryRunPlan(series, issues, options, costContext = {}) {
}
const verificationActions = arcRounds === 0
? 0
- : arcRounds * (1 + seasons.length) + Math.max(0, arcRounds - 1);
+ : arcRounds * (1 + seasons.length) + Math.max(0, arcRounds - 1) + isolationActions(seasons.length);
plan.push({
kind: 'verifyArc',
count: 1,
diff --git a/server/services/pipeline/seriesAutopilot/state.js b/server/services/pipeline/seriesAutopilot/state.js
index 7eac6b2910..677d229c4c 100644
--- a/server/services/pipeline/seriesAutopilot/state.js
+++ b/server/services/pipeline/seriesAutopilot/state.js
@@ -53,7 +53,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', 'resolve:rollback', 'check:complete',
+ 'note', 'step:skip', 'verify:round', 'resolve:round', 'resolve:rollback', 'resolve:isolate', 'check:complete',
'foundation:round', 'foundation:fix', 'child:retry', 'child:escalate',
'revision:cycle', 'revision:converged', 'gap:filed',
]));