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
retry a reverted foundation repair instead of ending the run on the first one
[._.]/ Adam Eivyd3958d1ccad0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e55e1b1c60..66e2447e4b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,6 +8,7 @@- **Series Autopilot can route individual steps to specialist models.** A run may now override provider, model, and reasoning effort for the creative or judge role of one named orchestration step, from either the start API or the Options panel. Stage routes survive pause/resume, take precedence over learned and run-wide choices, and remain soft defaults beneath exact prompt-stage pins, so a weak foundation repair model can be replaced without repointing episode drafting or independent verification.+- **A reverted foundation repair now gets another attempt instead of ending the run.** A repair whose independent re-judge showed no gain for the dimension it targeted was correctly rolled back to its pre-repair checkpoint — and then treated as terminal, so a run configured for twelve foundation rounds paused after a single rejected attempt. The gate now retries that dimension from the verified checkpoint, telling the next attempt what was reverted and what the rejected re-judge still reported so it can change strategy, and reusing the rewound verdict rather than paying for an identical re-judge. Retries stay budget- and cancellation-gated, count against both the round limit and the existing per-dimension stall patience, and never retain an unvalidated edit; a rollback that fails its own checkpoint verification still stops immediately.- **Foundation structure repair retains shrinking corrective progress.** A broad structure rewrite whose specialized arc verification improved from many blockers to a smaller residual used to get one correction attempt and then roll the entire improvement back. The repair now continues a bounded correction sequence while the blocker count stays monotonic, still restoring the original checkpoint if the set grows or cannot clear within the cap.- **A late structure-repair regression no longer erases an independently verified improvement.** The bounded correction sequence could shrink nine arc blockers to one, then let its final attempt trade that residual for five and restore the entire pre-repair plan—discarding the proven one-blocker checkpoint. It now restores the best verified intermediate state, sends that partial improvement through the harsh foundation re-judge, and leaves the full arc gate dirty so the residual must still clear before beats. Model evidence follows the same transaction boundary: the retained repair runs remain provisional, while the regressive run is immediately scored as rejected; a fully reverted repair is also a rejection rather than a schema-invalid response.- **Character-first planning now includes the cast's visual foundation.** The pre-arc character architect used to complete psychology and relationships while its response contract omitted physical description, silhouette, visual identity, and palette, so a graphic-novel series could settle its plot around characters the image pipeline still had to invent. Those identity-bearing fields now participate in completeness, prompt hashing, harsh foundation scoring, and repair; optional sheets such as props, expressions, gestures, and wardrobes are authored when the character's form supports them.diff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsxindex 88ecb365ff..32edb83996 100644--- a/client/src/components/pipeline/AutopilotPanel.jsx+++ b/client/src/components/pipeline/AutopilotPanel.jsx@@ -313,6 +313,12 @@ function frameLabel(f) {// #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})` : ''}`}`;+ // A repair whose re-judge showed no gain is rewound. Like resolve:rollback,+ // say whether the gate is retrying from the restored checkpoint — otherwise+ // every revert reads as "this run is about to stop".+ case 'foundation:rollback': return `Foundation ${f.dimension} repair did not improve its target `+ + `(${f.targetBefore} → ${f.targetAfter}) — ${f.reverted ? 'reverted that repair' : 'could not revert that repair'}`+ + `${f.retrying ? ', retrying from the checkpoint' : ''}`;// #1578 — per-check telemetry forwarded from the editorial-checks runner.case 'check:start': return `Editorial check: ${f.label || f.checkId}…`;case 'check:complete': {diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.jsindex fa6641bfde..8f5073e453 100644--- a/server/services/pipeline/foundationJudge.js+++ b/server/services/pipeline/foundationJudge.js@@ -1202,6 +1202,10 @@ async function runFoundationRepair(series, issues, dimension, finding, characterconst maxAttempts = dimension === 'craft' ? CRAFT_REPAIR_MAX_ATTEMPTS : 1;for (let attempt = 0; attempt < maxAttempts; attempt += 1) {const findingPayload = { gap: finding?.gap || '', fix: finding?.fix || '' };+ // The gate may already have reverted an attempt at this dimension — say so,+ // so the next proposal changes strategy instead of re-earning the same+ // rollback. Craft's storage-contract retry below appends to this.+ if (finding?.retryReason) findingPayload.retryReason = finding.retryReason;if (dimension === 'craft') {findingPayload.hardStorageContract = {voiceExemplars: '1-2 entries',@@ -1211,7 +1215,10 @@ async function runFoundationRepair(series, issues, dimension, finding, characterrequirement: 'Every passage and note must end as complete prose within these limits; storage never preserves overflow.',};if (violations.length > 0) {- findingPayload.retryReason = `The previous proposal violated the hard storage contract: ${violations.join('; ')}. Rewrite it shorter; do not merely cut it off.`;+ findingPayload.retryReason = [+ findingPayload.retryReason,+ `The previous proposal violated the hard storage contract: ${violations.join('; ')}. Rewrite it shorter; do not merely cut it off.`,+ ].filter(Boolean).join(' ');}}const result = await runStagedLLM(stage, {@@ -1514,7 +1521,10 @@ async function refineWorld(universeId, { providerId, model, effort, onRunCreatedpremise: universe.premise,styleNotes: universe.styleNotes,locked: universe.locked,- foundationDirective: [finding.gap, finding.fix].filter(Boolean).join('\nRequested repair: '),+ foundationDirective: [+ [finding.gap, finding.fix].filter(Boolean).join('\nRequested repair: '),+ finding.retryReason ? `Previous attempt: ${finding.retryReason}` : '',+ ].filter(Boolean).join('\n'),providerId,model,effort,@@ -1673,8 +1683,18 @@ export async function snapshotFoundationState(seriesId) {};}-/** Restore a foundation snapshot and verify the tracked fields match exactly. */-export async function restoreFoundationState(seriesId, snapshot) {+/**+ * Restore a foundation snapshot and verify the tracked fields match exactly.+ *+ * `judge` is the verdict that scored the checkpoint being restored. The cached+ * verdict on disk is keyed by a content hash, so after a rewind it describes+ * content that no longer exists and the next `judgeFoundation` pays a full LLM+ * call to re-derive a score this one already holds. Re-pinning it on a VERIFIED+ * restore puts the cache back in step with the content. Optional: a caller+ * without the pre-rewind verdict simply leaves the stale entry to self-+ * invalidate on its hash.+ */+export async function restoreFoundationState(seriesId, snapshot, { judge } = {}) {if (!snapshot || snapshot.seriesId !== seriesId || !snapshot.arcState) {return { restored: false, reason: 'invalid foundation snapshot' };}@@ -1690,6 +1710,10 @@ export async function restoreFoundationState(seriesId, snapshot) {const restoredSnapshot = await snapshotFoundationState(seriesId);const mismatched = mismatchedFoundationFields(snapshot, restoredSnapshot);const restored = mismatched.length === 0;+ if (restored && judge?.seriesId === seriesId && judge.sourceInputsHash) {+ const { cached, ...verdict } = judge;+ await saveSnapshot(verdict);+ }return {restored,reason: restored@@ -1713,9 +1737,19 @@ export async function restoreFoundationState(seriesId, snapshot) {** `finding` is the judge's `{ gap, fix }` for the targeted dimension, threaded* into the structure resolve as a synthesized arc finding.+ *+ * A retry after the caller REVERTED an earlier attempt at this same dimension+ * describes that attempt so this one changes strategy instead of re-proposing+ * discarded edits. It arrives on whichever channel the owning route has: the+ * prose `finding.retryReason` for the LLM-payload routes (character/craft's+ * finding JSON, worldbuilding's directive), and `avoidFindings` — the shared+ * "a previous attempt produced these, do not author them again" contract of+ * `resolveVerifyIssues` — for the structure route, so those stay OUT of the+ * work-to-close list a `suggestion` would have put them in.*/export async function applyFoundationFix(seriesId, dimension, {finding = {},+ avoidFindings,providerOverride,modelOverride,effortOverride,@@ -1780,6 +1814,10 @@ export async function applyFoundationFix(seriesId, dimension, {const resolveOptions = {providerDefault: providerOverride,modelDefault: modelOverride,+ // What a reverted earlier attempt at this dimension produced. The resolver+ // renders these in its own "do not author these again" block, apart from+ // the findings it must close (mirrors the arc gate's rollback retry).+ ...(Array.isArray(avoidFindings) && avoidFindings.length > 0 ? { avoid: avoidFindings } : {}),// The autopilot's unlock-for-run mode clears both `series.locked.arc`// (disarming the short-circuit above) and every per-season lock, so this// is the third arc-rewriting path that could otherwise delete a volume.diff --git a/server/services/pipeline/foundationJudge.rollback.test.js b/server/services/pipeline/foundationJudge.rollback.test.jsindex 41831ad8b3..fb232eef03 100644--- a/server/services/pipeline/foundationJudge.rollback.test.js+++ b/server/services/pipeline/foundationJudge.rollback.test.js@@ -75,6 +75,7 @@ const { createUniverse, getUniverse, updateUniverse, PREMISE_MAX } = await imporconst {snapshotFoundationState,restoreFoundationState,+ getFoundationJudge,__testing,} = await import('./foundationJudge.js');@@ -157,6 +158,35 @@ describe('restoreFoundationState — against the real universe write path', () =expect(Date.parse(afterStamp)).toBeGreaterThan(Date.parse(beforeStamp));});+ it('re-pins the checkpoint verdict on a verified rewind, and leaves it alone on a failed one', async () => {+ // The cached verdict is keyed by a content hash, so after a rewind the+ // stored one describes content that no longer exists — and the gate's next+ // read (a resume, the UI) buys a whole judge call to learn a score the+ // rewind already had. Only a VERIFIED restore may put it back.+ await seedFoundation();+ const checkpoint = await snapshotFoundationState('ser-1');+ const judge = {+ seriesId: 'ser-1', status: 'complete', sourceInputsHash: 'hash-before-repair',+ weightedScore: 6.5, cached: true,+ dimensions: { character: { score: 5, gap: 'thin lead', fix: 'build the chain' } },+ };++ const rollback = await restoreFoundationState('ser-1', checkpoint, { judge });+ expect(rollback.restored).toBe(true);+ const repinned = await getFoundationJudge('ser-1');+ expect(repinned).toMatchObject({ sourceInputsHash: 'hash-before-repair', weightedScore: 6.5 });+ // `cached` is a per-read flag, not part of the stored verdict.+ expect(repinned).not.toHaveProperty('cached');++ const corrupted = structuredClone(checkpoint);+ corrupted.universe.premise = 'x'.repeat(PREMISE_MAX + 100);+ const failed = await restoreFoundationState('ser-1', corrupted, {+ judge: { ...judge, sourceInputsHash: 'hash-that-must-not-be-pinned' },+ });+ expect(failed.restored).toBe(false);+ expect((await getFoundationJudge('ser-1')).sourceInputsHash).toBe('hash-before-repair');+ });+it('still reports a mismatch — naming the field — when authored content does not come back', async () => {const universe = await seedFoundation();const checkpoint = await snapshotFoundationState('ser-1');diff --git a/server/services/pipeline/foundationJudge.test.js b/server/services/pipeline/foundationJudge.test.jsindex c71e765319..1ed709d656 100644--- a/server/services/pipeline/foundationJudge.test.js+++ b/server/services/pipeline/foundationJudge.test.js@@ -1286,6 +1286,41 @@ describe('applyFoundationFix — dimension → owning-service routing table', ()expect(r).toMatchObject({ dimension: 'character', applied: true, characterArcsUpdated: true });});+ it('carries a rejected earlier attempt into the retry so it can change strategy', async () => {+ // The gate reverts a repair whose target did not improve and then retries it+ // (see runFoundationGate). Without the reverted attempt in the payload, the+ // retry re-proposes the same edits and buys a second rollback.+ const retryReason = 'A previous character repair this run was REVERTED: it left the target score at 5.';+ const uni = { id: 'uni-1', characters: [{ id: 'chr-thin', name: 'B' }] };+ universeBuilder.getUniverse.mockResolvedValue(uni);+ universeBuilder.updateUniverse.mockImplementation(async (id, mutator) => ({ id, ...(mutator(uni) || {}) }));+ stageRunner.runStagedLLM.mockResolvedValue({ content: { characters: [] } });++ await applyFoundationFix('ser-1', 'character', { finding: { gap: 'blank lead', fix: 'build the chain', retryReason } });+ expect(JSON.parse(stageRunner.runStagedLLM.mock.calls.at(-1)[1].foundationFindingJson)).toMatchObject({+ gap: 'blank lead', fix: 'build the chain', retryReason,+ });++ stageRunner.runStagedLLM.mockClear();+ await applyFoundationFix('ser-1', 'worldbuilding', { finding: { gap: 'costless magic', fix: 'price it', retryReason } });+ expect(universeBuilderExpand.expandWorldTemplate).toHaveBeenCalledWith(expect.objectContaining({+ foundationDirective: expect.stringContaining(retryReason),+ }));++ // Structure has a structured channel of its own: the reverted findings ride+ // `avoid` (never authored again) instead of the suggestion the resolver+ // would read as work to close.+ const discarded = [{ severity: 'high', location: 'arc', problem: 'the charter handoff is still thin' }];+ await applyFoundationFix('ser-1', 'structure', {+ finding: { gap: 'thin handoff', fix: 'stage it', retryReason },+ avoidFindings: discarded,+ });+ expect(arcPlanner.resolveVerifyIssues).toHaveBeenCalledWith('ser-1', expect.objectContaining({+ findings: [expect.objectContaining({ problem: 'thin handoff', suggestion: 'stage it' })],+ avoid: discarded,+ }));+ });+it('keeps existing transition beats structure-owned during post-arc character repair', async () => {const existingTransition = { kind: 'decision', atIssue: 6, label: 'refuses the unsupported shortcut' };const series = {diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex 3f956ad6cf..f790ebac1e 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -274,6 +274,13 @@ beforeEach(() => {// Reset settings to empty so a test that set persisted convergence rounds// doesn't leak its default into the next test.getSettings.mockImplementation(async () => ({}));+ // `clearAllMocks` above keeps implementations, and the foundation-gate tests+ // set persistent ones. `mockReset` restores the implementation each was+ // constructed with, so a stalled-foundation test can't leak into the next.+ judgeFoundation.mockReset();+ applyFoundationFix.mockReset();+ snapshotFoundationState.mockReset();+ restoreFoundationState.mockReset();});// ---------------------------------------------------------------------------@@ -1963,7 +1970,7 @@ describe('autopilot conductor', () => {.toEqual(['worldbuilding', 'structure', 'craft']);});- it('foundation gate: reverts a repair that leaves its target unchanged while lowering the aggregate', async () => {+ it('foundation gate: reverts a repair that leaves its target unchanged, then retries it from the checkpoint', async () => {const snapshot = (weightedScore) => ({seriesId: 'ser-example', status: 'complete', weightedScore,dimensions: {@@ -1983,14 +1990,27 @@ describe('autopilot conductor', () => {await autopilot.startSeriesAutopilot(seriesId, { maxFoundationRounds: 4 });await waitFor(runFinished(seriesId));- const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;- expect(last?.pauseKind).toBe('regression');- expect(last?.reason).toMatch(/character repair did not improve its target \(7 → 7; weighted 7\.2 → 7\.1\)/);- expect(applyFoundationFix).toHaveBeenCalledTimes(1);- expect(restoreFoundationState).toHaveBeenCalledWith(seriesId, checkpoint);- expect(last?.residualFindings).toEqual(expect.arrayContaining([- expect.objectContaining({ location: expect.stringContaining('character'), problem: 'Aruun privacy is mislabeled as a relapse.' }),- ]));+ // The rejected edits are rolled back to the checkpoint that was taken before+ // them — but one bad proposal does not end a 4-round budget, so the same+ // dimension is repaired again, and the retry is told what was reverted.+ // The pre-repair verdict rides along so the restored content keeps its+ // matching cached judgment instead of forcing a re-judge on resume.+ expect(restoreFoundationState).toHaveBeenCalledWith(+ seriesId,+ checkpoint,+ { judge: expect.objectContaining({ weightedScore: 7.2 }) },+ );+ const characterRepairs = applyFoundationFix.mock.calls.filter(([, dimension]) => dimension === 'character');+ expect(characterRepairs.length).toBeGreaterThan(1);+ expect(characterRepairs[0][2].finding.gap).toBe('Aruun privacy is mislabeled as a relapse.');+ expect(characterRepairs[0][2].finding.retryReason).toBeUndefined();+ expect(characterRepairs[1][2].finding).toMatchObject({+ // The ORIGINAL gap — the foundation is back at the pre-repair checkpoint.+ gap: 'Aruun privacy is mislabeled as a relapse.',+ retryReason: expect.stringMatching(/REVERTED/),+ });+ // The rewound judgment is reused instead of paying for an identical re-judge.+ expect(judgeFoundation).toHaveBeenCalledTimes(3);});it('foundation gate: keeps a tied character repair that objectively filled blank cast fields', async () => {@@ -2032,7 +2052,7 @@ describe('autopilot conductor', () => {expect(applyFoundationFix.mock.calls.map(([, dimension]) => dimension)).toEqual(['character', 'character']);});- it('foundation gate: rejects the first repair when the same target fails to improve', async () => {+ it('foundation gate: pauses only after repeated rejected repairs exhaust the same target', async () => {const stalled = {seriesId: 'ser-example', status: 'complete', weightedScore: 7,dimensions: {@@ -2046,19 +2066,88 @@ describe('autopilot conductor', () => {craft: { score: 10, gap: 'clean', fix: 'none' },},};- judgeFoundation- .mockImplementationOnce(async () => stalled)- .mockImplementationOnce(async () => stalled);+ judgeFoundation.mockImplementation(async () => stalled);+ let checkpointSeq = 0;+ snapshotFoundationState.mockImplementation(async (sId) => {+ checkpointSeq += 1;+ return { seriesId: sId, marker: `checkpoint-${checkpointSeq}` };+ });const { seriesId } = await seedComplete();await autopilot.startSeriesAutopilot(seriesId, { maxFoundationRounds: 5 });await waitFor(runFinished(seriesId));const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;expect(last).toMatchObject({ type: 'paused', scope: 'foundationGate', pauseKind: 'regression' });- expect(judgeFoundation).toHaveBeenCalledTimes(2);+ // Every rejected attempt was rolled back — to the checkpoint taken just+ // before IT, so no retry ever builds on a rejected edit — and the pause says so.+ expect(applyFoundationFix.mock.calls.length).toBeGreaterThan(1);+ expect(restoreFoundationState.mock.calls.map(([, cp]) => cp.marker))+ .toEqual(applyFoundationFix.mock.calls.map((_call, index) => `checkpoint-${index + 1}`));+ expect(last?.reason).toMatch(/reverted to the pre-repair checkpoint/);+ for (const [, , options] of applyFoundationFix.mock.calls) {+ expect(options.finding.gap).toBe(stalled.dimensions.worldbuilding.gap);+ }+ // The residual describes the RESTORED foundation the user is handed back.+ expect(last?.residualFindings).toEqual(expect.arrayContaining([+ expect.objectContaining({+ location: expect.stringContaining('worldbuilding'),+ problem: stalled.dimensions.worldbuilding.gap,+ }),+ ]));+ });++ it('foundation gate: stops immediately when a rejected repair cannot be rolled back', async () => {+ const stalled = {+ seriesId: 'ser-example', status: 'complete', weightedScore: 7,+ dimensions: {+ worldbuilding: { score: 7, gap: 'The scarcity mechanism is undefined.', fix: 'Define it.' },+ character: { score: 10, gap: 'clean', fix: 'none' },+ structure: { score: 10, gap: 'clean', fix: 'none' },+ craft: { score: 10, gap: 'clean', fix: 'none' },+ },+ };+ judgeFoundation.mockImplementation(async () => stalled);+ restoreFoundationState.mockResolvedValueOnce({ restored: false, reason: 'universe.premise' });++ const { seriesId } = await seedComplete();+ await autopilot.startSeriesAutopilot(seriesId, { maxFoundationRounds: 5 });+ await waitFor(runFinished(seriesId));++ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;+ expect(last).toMatchObject({ type: 'paused', scope: 'foundationGate', pauseKind: 'regression' });+ expect(last?.reason).toMatch(/checkpoint verification failed after rollback: universe\.premise/);+ // An unverified checkpoint is the one case that must NOT be retried.expect(applyFoundationFix).toHaveBeenCalledTimes(1);});+ it('foundation gate: accepts a retry that improves its target after an earlier attempt was reverted', async () => {+ const snapshot = (weightedScore, worldbuilding) => ({+ seriesId: 'ser-example', status: 'complete', weightedScore,+ dimensions: {+ worldbuilding: { score: worldbuilding, gap: 'The scarcity mechanism is undefined.', fix: 'Define it.' },+ character: { score: 10, gap: 'clean', fix: 'none' },+ structure: { score: 10, gap: 'clean', fix: 'none' },+ craft: { score: 10, gap: 'clean', fix: 'none' },+ },+ });+ judgeFoundation+ // Round 1: worldbuilding is the weak target.+ .mockImplementationOnce(async () => snapshot(7, 5))+ // Round 2: the repair moved nothing and cost aggregate score → reverted.+ .mockImplementationOnce(async () => snapshot(6.6, 5))+ // Round 3 re-judges the SECOND attempt (the rewound round reuses the+ // round-1 verdict), which earned its keep and clears the gate.+ .mockImplementationOnce(async () => snapshot(9, 9));++ const { seriesId } = await seedComplete();+ await autopilot.startSeriesAutopilot(seriesId, { maxFoundationRounds: 5 });+ await waitFor(runFinished(seriesId));++ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');+ expect(restoreFoundationState).toHaveBeenCalledTimes(1);+ expect(applyFoundationFix.mock.calls.filter(([, d]) => d === 'worldbuilding')).toHaveLength(2);+ });+it('foundation gate: gives a newly exposed gap at the same score its own repair window', async () => {const snap = (gap, score = 7) => ({seriesId: 'ser-example', status: 'complete', weightedScore: score,diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.jsindex 1f44edb2f9..8b44c36285 100644--- a/server/services/pipeline/seriesAutopilot/childRuns.js+++ b/server/services/pipeline/seriesAutopilot/childRuns.js@@ -27,7 +27,8 @@ import {import {CHILD_POLL_MS, DIVERGENCE_PATIENCE, trackConvergence, convergencePauseReason,divergencePauseReason, foundationPauseReason, foundationDivergenceReason,- regressionPauseReason, sameFinding, isBlockingSetRegression, isIsolatedFixSafe,+ foundationRepairMissed, regressionPauseReason, sameFinding, isBlockingSetRegression,+ isIsolatedFixSafe,} from './convergence.js';import { broadcast, budgetPause, providerOverrideOpts, providerIdOpts, roleLlm, seasonPreserveOpts } from './session.js';import { recordModelOutcome } from './modelPerformance.js';@@ -44,6 +45,18 @@ 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);+// Everything a foundation round reads off one judge verdict. Hoisted because a+// rejected repair rewinds to its checkpoint and the round then re-reads the+// PRE-repair verdict — two spellings of this derivation is how they drift.+const readFoundationVerdict = (snap, threshold) => {+ const score = snap.weightedScore ?? 0;+ return {+ score,+ gate: foundationGateStatus(snap.dimensions, score, threshold),+ weak: foundationFixTarget(snap.dimensions, threshold),+ };+};+// 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@@ -591,6 +604,14 @@ export async function runCharacterFoundation(seriesId, record) {// structure gap; a repaired structure can expose missing craft). Comparing all// of those owned repairs to one global weighted-score high-water mark made a// newly surfaced dimension look like divergence before its editor ran once.+//+// A repair whose independent re-judge does NOT show its target improving is+// rewound to the checkpoint taken before it — and then RETRIED, not treated as+// terminal: one rejected generative proposal says nothing about whether the+// dimension is repairable, and stopping on it stranded runs after a single fix+// out of a configured 12 rounds. Each retry starts from the verified checkpoint,+// counts against maxFoundationRounds and the per-dimension stall patience, and+// carries a note describing what was reverted so it can change strategy.export async function runFoundationGate(seriesId, record) {const maxRounds = Number.isInteger(record.options.maxFoundationRounds)? record.options.maxFoundationRounds@@ -619,6 +640,25 @@ export async function runFoundationGate(seriesId, record) {// score high-water mark: a genuinely improved target may expose another weak// layer, but an unchanged target cannot keep edits by moving the problem.let pendingRepair = null;+ // What the last REJECTED (and reverted) attempt for a dimension looked like:+ // the strategy note and discarded findings handed to its next attempt, plus+ // the rewind notice to report if that dimension ends up exhausting its+ // patience. Cleared as soon as an attempt for that dimension earns its keep.+ const rejectionByDimension = new Map();+ // A terminal pause for `dimension`, folding in its last rewind when it had+ // one: the state being handed back is that checkpoint, and saying so is the+ // difference between a trustworthy pause and an unexplained rewind.+ // `rejectedKind` overrides the stop kind when the stop cause IS the rewinding.+ const foundationPause = (dimension, pauseKind, reason, judged, rejectedKind) => {+ const rejected = rejectionByDimension.get(dimension);+ return {+ pause: true,+ pauseKind: rejected && rejectedKind ? rejectedKind : pauseKind,+ reason: rejected ? `${reason} ${rejected.rewind}` : reason,+ residual: residualFindings(judged.dimensions),+ ...(rejected ? { discarded: rejected.discarded } : {}),+ };+ };let changed = false;for (let round = 1; round <= maxRounds; round += 1) {if (record.cancelRequested) return { canceled: true };@@ -631,7 +671,14 @@ export async function runFoundationGate(seriesId, record) {// a user edit) flips the pinned hash and re-judges automatically.let judgeRunId = null;const judgeHooks = providerOverrideOpts(record, 'judge');- const snap = await judgeFoundation(seriesId, {+ // `let` because a rejected repair rewinds the foundation to its checkpoint:+ // the restored content is exactly what the PRE-repair judge scored, so the+ // rest of the round re-reads that verdict rather than re-judging (see the+ // rollback branch below). Looping back to this call instead would also+ // re-derive it — the hash cache absorbs the LLM cost — but it would spend a+ // whole round of the run's repair budget re-learning what the gate is+ // already holding, which is the budget the retry exists to use.+ let snap = await judgeFoundation(seriesId, {providerDefault: judgeLlm.providerOverride,modelDefault: judgeLlm.modelOverride,effortDefault: judgeLlm.effortOverride,@@ -643,9 +690,7 @@ export async function runFoundationGate(seriesId, record) {});// A cached (content-hash unchanged) verdict did no LLM work — don't bill it.if (!snap.cached) await recordDomainUsage('cos', { actions: 1 });- const score = snap.weightedScore ?? 0;- const gate = foundationGateStatus(snap.dimensions, score, threshold);- const weak = foundationFixTarget(snap.dimensions, threshold);+ let { score, gate, weak } = readFoundationVerdict(snap, threshold);if (!snap.cached && judgeRunId) {await recordModelOutcome(judgeRunId, {role: 'judge', stage: 'foundationGate', outcome: 'valid',@@ -687,36 +732,63 @@ export async function runFoundationGate(seriesId, record) {const earned = targetImproved|| (targetTied && objectivelyFilled)|| (targetTied && gapChanged && score >= beforeWeighted);+ await Promise.all((pendingRepair.runIds || []).map((runId) => recordModelOutcome(runId, {+ role: 'creative', stage: 'foundationGate', outcome: earned ? 'accepted' : 'rejected', target: dimension,+ scoreBefore: beforeTargetScore, scoreAfter: afterTargetScore,+ weightedBefore: beforeWeighted, weightedAfter: score,+ }).catch(() => {})));+ const rejectedJudge = pendingRepair.judge;+ const rejectedSnapshot = pendingRepair.snapshot;+ pendingRepair = null;if (!earned) {- await Promise.all((pendingRepair.runIds || []).map((runId) => recordModelOutcome(runId, {- role: 'creative', stage: 'foundationGate', outcome: 'rejected', target: dimension,- scoreBefore: beforeTargetScore, scoreAfter: afterTargetScore,+ const copy = foundationRepairMissed({+ dimension,+ targetBefore: beforeTargetScore, targetAfter: afterTargetScore,weightedBefore: beforeWeighted, weightedAfter: score,- }).catch(() => {})));- const rollback = await restoreFoundationState(seriesId, pendingRepair.snapshot);- const reason = rollback.restored- ? `Foundation ${dimension} repair did not improve its target (${beforeTargetScore} → ${afterTargetScore}; weighted ${beforeWeighted} → ${score}), so its edits were reverted to the pre-repair checkpoint.`- : `Foundation ${dimension} repair did not improve its target (${beforeTargetScore} → ${afterTargetScore}; weighted ${beforeWeighted} → ${score}), and checkpoint verification failed after rollback: ${rollback.reason || 'unknown restore mismatch'}.`;+ });+ // Hand back the verdict that scored this checkpoint: the rewind puts its+ // content back, and re-pinning its judgment keeps a resume (or the next+ // read) from re-buying a score the gate is holding.+ const rollback = await restoreFoundationState(seriesId, rejectedSnapshot, { judge: rejectedJudge });+ const discarded = discardedSet(residualFindings(snap.dimensions));broadcast(seriesId, {type: 'foundation:rollback', round, dimension,targetBefore: beforeTargetScore, targetAfter: afterTargetScore,weightedBefore: beforeWeighted, weightedAfter: score,+ // A verified rewind is also a retryable one; an unverified one stops+ // the gate below, so this single flag says both.reverted: rollback.restored,});- return {- pause: true,- pauseKind: 'regression',- reason,- residual: residualFindings(pendingRepair.judge.dimensions),- discarded: discardedSet(residualFindings(snap.dimensions)),- };+ // An unverified restore is the one unrecoverable case: the foundation is+ // no longer known to match ANY judged state, so another repair would be+ // built on corruption. Everything else keeps going.+ if (!rollback.restored) {+ return {+ pause: true,+ pauseKind: 'regression',+ reason: copy.unverified(rollback.reason),+ residual: residualFindings(rejectedJudge.dimensions),+ discarded,+ };+ }+ // The checkpoint is verified back in place, so the foundation is once+ // again exactly what `rejectedJudge` scored: adopt that verdict for the+ // rest of this round (no second judge call, nothing billed) and let the+ // stall guard below count the rejection before another attempt runs.+ rejectionByDimension.set(dimension, {+ discarded,+ rewind: copy.rewind,+ note: copy.retryNote(afterDimension.gap),+ });+ snap = rejectedJudge;+ ({ score, gate, weak } = readFoundationVerdict(snap, threshold));+ console.log(`↩️ foundation ${dimension} repair reverted — series=${seriesId.slice(0, 12)} round=${round}: ${copy.missed}`);+ } else {+ // A kept repair clears the dimension's rejection history: the next+ // attempt is working from different content, so a stale "this failed"+ // note would misdirect it.+ rejectionByDimension.delete(dimension);}- await Promise.all((pendingRepair.runIds || []).map((runId) => recordModelOutcome(runId, {- role: 'creative', stage: 'foundationGate', outcome: 'accepted', target: dimension,- scoreBefore: beforeTargetScore, scoreAfter: afterTargetScore,- weightedBefore: beforeWeighted, weightedAfter: score,- }).catch(() => {})));- pendingRepair = null;}if (gate.passes) {record.runState.foundationGated = true;@@ -745,12 +817,10 @@ export async function runFoundationGate(seriesId, record) {const floorReason = gate.failingDimensions.length > 0? `Foundation quality left ${gate.failingDimensions.join(', ')} below the ${gate.dimensionFloor} dimension floor after ${maxRounds} round(s). Strengthen those foundations and resume.`: foundationPauseReason(maxRounds, score, threshold);- return {- pause: true,- pauseKind: 'maxRounds',- reason: floorReason,- residual: residualFindings(snap.dimensions),- };+ // The round bound is the stop cause even when the last attempt rewound —+ // that attempt still says what state the user is holding, so it rides the+ // reason rather than relabeling why the loop ended.+ return foundationPause(weak?.dimension, 'maxRounds', floorReason, snap);}// Divergence guard (#1571): bail only when repeated repairs fail to improve// THEIR OWN target. A global weighted high-water mark is not comparable@@ -780,12 +850,10 @@ export async function runFoundationGate(seriesId, record) {const floorReason = gate.failingDimensions.length > 0? `Foundation quality stopped improving with ${gate.failingDimensions.join(', ')} below the ${gate.dimensionFloor} dimension floor. Review those foundations and resume.`: foundationDivergenceReason(score, threshold, DIVERGENCE_PATIENCE);- return {- pause: true,- pauseKind: 'divergence',- reason: floorReason,- residual: residualFindings(snap.dimensions),- };+ // A stall whose attempts were all REVERTED is reported as a regression:+ // the pre-#3818 gate raised that kind on the very first rewind, and the+ // state the user is handed — the pre-repair checkpoint — is the same one.+ return foundationPause(weak.dimension, 'divergence', floorReason, snap, 'regression');}if (record.cancelRequested) return { canceled: true };const beforeFix = await budgetPause();@@ -813,9 +881,18 @@ export async function runFoundationGate(seriesId, record) {const repairRunIds = [];const creativeHooks = providerOverrideOpts(record);const repairJudgeHooks = providerOverrideOpts(record, 'judge');+ // A retry after a reverted attempt gets the ORIGINAL judge gap/fix (the+ // foundation is back at that checkpoint) plus what the rejected re-judge+ // said, so it can change strategy instead of re-proposing the same edits.+ const priorRejection = rejectionByDimension.get(weak.dimension);+ const repairFinding = {+ ...(snap.dimensions?.[weak.dimension] || {}),+ ...(priorRejection ? { retryReason: priorRejection.note } : {}),+ };try {fix = await applyFoundationFix(seriesId, weak.dimension, {- finding: snap.dimensions?.[weak.dimension] || {},+ finding: repairFinding,+ avoidFindings: priorRejection?.discarded,providerOverride: creativeLlm.providerOverride,modelOverride: creativeLlm.modelOverride,judgeProviderDefault: judgeLlm.providerOverride,diff --git a/server/services/pipeline/seriesAutopilot/convergence.js b/server/services/pipeline/seriesAutopilot/convergence.jsindex 8afc52c60a..bb54b9cc53 100644--- a/server/services/pipeline/seriesAutopilot/convergence.js+++ b/server/services/pipeline/seriesAutopilot/convergence.js@@ -277,6 +277,26 @@ export function foundationPauseReason(maxRounds, score, threshold) {return `${label} couldn't reach the threshold (weighted ${score} < ${threshold}) in ${maxRounds} ${plural} — `+ `paused for review. ${fix}, or raise the ${limit} limit in Options and resume.`;}+// A foundation repair whose independent re-judge showed no gain for the target+// it was asked to fix. `missed` is the shared head of every sentence about that+// attempt — the rewind notice, the unverified-restore pause, and the note the+// NEXT attempt at that dimension is handed — so the three can't disagree about+// what the numbers were.+export function foundationRepairMissed({ dimension, targetBefore, targetAfter, weightedBefore, weightedAfter }) {+ const missed = `Foundation ${dimension} repair did not improve its target `+ + `(${targetBefore} → ${targetAfter}; weighted ${weightedBefore} → ${weightedAfter})`;+ return {+ missed,+ rewind: `${missed}, so its edits were reverted to the pre-repair checkpoint.`,+ unverified: (reason) => `${missed}, and checkpoint verification failed after rollback: ${reason || 'unknown restore mismatch'}.`,+ // Handed to the retry so it changes strategy instead of re-proposing edits+ // the gate has already thrown away. Names the rejected re-judge's own gap:+ // that is the evidence the last attempt failed to move anything.+ retryNote: (gap) => `A previous ${dimension} repair this run was REVERTED: it left the target score at ${targetAfter} `+ + `(weighted ${weightedBefore} → ${weightedAfter}), so none of its edits were kept. The re-judge of that attempt still `+ + `reported: ${gap || 'the same gap'}. Take a different approach — repeating those edits will be reverted again.`,+ };+}export function foundationDivergenceReason(score, threshold, rounds) {const { label, fix } = PAUSE_GATES.foundation;const plural = rounds === 1 ? 'round' : 'rounds';diff --git a/server/services/pipeline/seriesAutopilot/state.js b/server/services/pipeline/seriesAutopilot/state.jsindex 36fd2ddedc..b252732cc4 100644--- a/server/services/pipeline/seriesAutopilot/state.js+++ b/server/services/pipeline/seriesAutopilot/state.js@@ -54,7 +54,7 @@ export const AUTOPILOT_TERMINAL_TYPES = new Set(['complete', 'paused', 'canceled// `reason` arguments instead.export const SIGNAL_FRAME_TYPES = Object.freeze(new Set(['note', 'step:skip', 'verify:round', 'resolve:round', 'resolve:rollback', 'resolve:isolate', 'check:complete',- 'foundation:round', 'foundation:fix', 'canon:repair', 'child:retry', 'child:escalate',+ 'foundation:round', 'foundation:fix', 'foundation:rollback', 'canon:repair', 'child:retry', 'child:escalate','revision:cycle', 'revision:converged', 'gap:filed',]));