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

fix: accumulate every rejected foundation repair per dimension (#3835)

[._.]/ Adam Eivy5a92fd50adda
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d4786c528a..df6f085041 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -104,3 +104,4 @@
- **The Digital Twin's 19 sections are grouped now, instead of one 19-wide tab strip you had to read end to end.** The strip carried every section in a single flat row with no ordering a user could infer — setup, content, output and archival tasks interleaved, `Import` sitting between `Interview` and `Avatar Bio`, and `Export`, `Legacy` and `Time Capsule` as three adjacent tabs that all mean "get data out" — so every visit started by scanning 19 labels, several of which (`Enrich` vs `Taste` vs `Personality` vs `Personas`) only tell you apart if you already know the feature. They now collapse into five groups named for what you're doing to the twin: **Profile** (who it is), **Sources** (where its material comes from), **Assessment** (whether it's actually you), **Presence** (how it shows up) and **Legacy** (how you get it out). Above `sm` that's a group row over the active group's sections — at most six at a time; on a phone the whole thing becomes one `<select>` with `<optgroup>` headers, which is the measured fix for a 375x812 screen where the strip plus the health header pushed **Analyze Traits**, **Recalculate** and **Check for Contradictions** below the fold. Nothing about addressing changed: the section id is still the route param, so every deep link, ⌘K entry and voice `ui_navigate` target resolves exactly as before, and the group is derived from the section rather than stored. The nav manifest carries the grouping as a keyword tag per section plus a `twin-<group>` alias, so "twin sources" lands somewhere sensible without inventing a group path no route serves.
- **An arc verification no longer forgets a rejected rewrite one round after it reverted it.** The gate already carried a reverted candidate's own blockers into the corrective retry that follows the rollback, as "do not author these" evidence — but only that one call. If the retry landed on a state that was no better than the checkpoint yet still blocked, the next ordinary resolve rebuilt its avoid list from scratch, so the resolver was free to re-author the exact rewrite the gate had just thrown away. That is what a paused run showed: 2 blockers resolved down to 1, a rewrite back up to 5 (reverted), the retry back to 1, then straight back to 2 with no retries left and a pause for review. Every blocker set discarded during a run is now accumulated and passed to every later resolve in that gate — ordinary, corrective, and per-finding isolated alike — bounded by the same limit the persisted marker uses, newest evidence first so it is never the part that gets trimmed. Anything that has since become an active repair target is filtered out, so the resolver is never told to both fix and avoid the same finding, and the cross-Resume evidence from a previous run still layers in underneath.
- **That rejected-rewrite evidence now survives the pause, and the isolation pass banks its own.** Accumulating a run's discarded blocker sets fixed the gate mid-run, but two boundaries still threw the evidence away — both the same failure one level out. A run that reverted two *different* rewrites before pausing persisted only the newest set, so a Resume inherited the last rollback alone and its resolver could re-author the first; the whole history now rides a separate `runDiscardedFindings` on the paused marker, which leaves the panel's "Discarded — what the reverted round produced" copy true of the field it renders and hands the resumed gate everything. And the per-finding isolation pass — the escalation that resolves a residual one finding at a time once the whole-set retries are spent — computed its avoid list once for the whole pass and never recorded its own rejected patches, so a rewrite rejected on target 1 could be re-proposed verbatim on target 3, and nothing it learned reached the ordinary resolve that follows a successful isolation. Each rejected patch's verified consequence is now banked like a whole-set rollback's, and the avoid list is rebuilt per target. It is still filtered against everything the pass is currently repairing, so no attempt is told to both fix and avoid the same finding, and a marker written before the new field exists resumes on what it has.
+- **The foundation gate now remembers every repair it rejected for a dimension, not just the last one.** Two rollback-evidence models were living side by side in one file: the arc gate accumulates every discarded set for its whole lifetime and carries it across a pause, while the foundation gate kept a single most-recent rejection per dimension — so a dimension that rejected two different repairs handed the third evidence of only the second, and the editor was free to re-author the first. Same evidence loss, one level down, and a reader had every reason to assume the two behaved alike. Both gates now ride one shared per-key bank: the arc gate banks a flat history as before, the foundation gate banks one per dimension, and each rejected set is recorded at the moment it is thrown away rather than when the next attempt happens to read it — so an unverified restore, which pauses without ever reaching a retry, still contributes its evidence. An accepted repair no longer wipes the dimension's history (a candidate the gate rejected is still a candidate it rejected; only the stale "this failed, try another angle" strategy note is cleared), and the evidence is filtered against the gap the call is actually being asked to close, so no editor is told to both fix and avoid the same thing. It survives the pause too, as a per-dimension `foundationDiscardedFindings` on the paused marker that a resume seeds its bank from — a marker written before the field existed simply resumes with an empty bank, exactly as it does today.
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index e880296bbf..f440ada707 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -242,6 +242,26 @@ const sanitizeAutopilotFindings = (raw, limit) => (Array.isArray(raw)
.slice(0, limit)
: []);
+// How many repair targets may carry their own discarded history. The foundation
+// gate keys by dimension and there are a fixed handful of those, so this only
+// ever bounds a marker written by a peer that knows dimensions this one doesn't.
+const AUTOPILOT_DISCARDED_KEYS_MAX = 12;
+
+// The keyed form of the above, for a gate whose repairs are owned by independent
+// targets (the foundation gate's dimensions): each key keeps its own bounded
+// history, and a key whose findings all fail sanitization is dropped rather than
+// persisted as an empty bucket.
+const sanitizeAutopilotKeyedFindings = (raw, limit) => {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
+ const out = {};
+ for (const [key, findings] of Object.entries(raw).slice(0, AUTOPILOT_DISCARDED_KEYS_MAX)) {
+ const name = trimTo(key, 80);
+ const bounded = sanitizeAutopilotFindings(findings, limit);
+ if (name && bounded.length > 0) out[name] = bounded;
+ }
+ return out;
+};
+
export const sanitizeAutopilot = (raw) => {
if (!raw || typeof raw !== 'object') return null;
const status = AUTOPILOT_STATUSES.includes(raw.status) ? raw.status : 'idle';
@@ -270,6 +290,17 @@ export const sanitizeAutopilot = (raw) => {
raw.runDiscardedFindings ?? raw.discardedFindings,
AUTOPILOT_DISCARDED_MAX,
),
+ // The same resume evidence for the foundation gate, which banks PER
+ // DIMENSION because its repairs are owned by independent editors: a rejected
+ // character rewrite is no reason for the structure editor to avoid anything
+ // (#3835). No `discardedFindings` fallback here — that field is flat and
+ // dimension-less, so there is nothing to key an older marker's set under;
+ // an install that paused before this field existed simply resumes with the
+ // in-run accumulation only, exactly as it does today.
+ foundationDiscardedFindings: sanitizeAutopilotKeyedFindings(
+ raw.foundationDiscardedFindings,
+ AUTOPILOT_DISCARDED_MAX,
+ ),
lastError: trimTo(raw.lastError, AUTOPILOT_ERROR_MAX) || null,
// No `pipelineSeries` schema-gate bump for this (or any) autopilot field: the
// marker is transient, regenerated-every-run status, NOT durable creative
diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.js
index 1595358778..ab631793f8 100644
--- a/server/services/pipeline/series.test.js
+++ b/server/services/pipeline/series.test.js
@@ -929,6 +929,25 @@ describe('pipeline series service', () => {
});
expect(b.runDiscardedFindings).toEqual([]);
});
+
+ it('bounds foundationDiscardedFindings per dimension and drops empty keys (#3835)', () => {
+ const many = Array.from({ length: 40 }, (_, i) => ({ severity: 'high', location: `V${i}`, problem: `hole ${i}` }));
+ const a = svc.sanitizeAutopilot({
+ status: 'paused',
+ foundationDiscardedFindings: { character: many, structure: [], craft: 'nope' },
+ });
+ expect(a.foundationDiscardedFindings.character).toHaveLength(20);
+ expect(a.foundationDiscardedFindings.character[0]).toEqual(many[0]);
+ expect(a.foundationDiscardedFindings).not.toHaveProperty('structure');
+ expect(a.foundationDiscardedFindings).not.toHaveProperty('craft');
+ // A marker written before the field existed resumes with an empty bank —
+ // there is no flat set to key by dimension, so there is nothing to fall
+ // back to (unlike runDiscardedFindings above).
+ expect(svc.sanitizeAutopilot({ status: 'paused' }).foundationDiscardedFindings).toEqual({});
+ expect(svc.sanitizeAutopilot({
+ status: 'paused', foundationDiscardedFindings: ['flat'],
+ }).foundationDiscardedFindings).toEqual({});
+ });
});
describe('sanitizeAutopilot resumeOptions', () => {
diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.js
index a6805146b5..052b078bd8 100644
--- a/server/services/pipeline/seriesAutopilot.js
+++ b/server/services/pipeline/seriesAutopilot.js
@@ -77,6 +77,7 @@
export * from './seriesAutopilot/state.js';
export * from './seriesAutopilot/config.js';
export * from './seriesAutopilot/convergence.js';
+export * from './seriesAutopilot/discardedEvidence.js';
export * from './seriesAutopilot/stepResolver.js';
export * from './seriesAutopilot/session.js';
export * from './seriesAutopilot/diagnosisCore.js';
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index 3b7b1b6243..de5e8e2842 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -2174,6 +2174,111 @@ describe('autopilot conductor', () => {
expect(applyFoundationFix.mock.calls.filter(([, d]) => d === 'worldbuilding')).toHaveLength(2);
});
+ it('foundation gate: a third attempt carries BOTH earlier rejections for its dimension (#3835)', async () => {
+ // The evidence-loss #3829/#3832 closed for the arc gate: the foundation gate
+ // kept only the LAST rejection per dimension, so a dimension that rejected
+ // two different repairs handed the next one evidence of only the second and
+ // the editor was free to re-author the first.
+ const snap = (weightedScore, characterScore, characterGap) => ({
+ seriesId: 'ser-example', status: 'complete', weightedScore,
+ dimensions: {
+ worldbuilding: { score: 9, gap: 'The ration authority is unnamed.', fix: 'Name it.' },
+ character: { score: characterScore, gap: characterGap, fix: `repair ${characterGap}` },
+ structure: { score: 9, gap: 'The charter handoff is thin.', fix: 'Stage the handoff.' },
+ craft: { score: 9, gap: 'The panel grammar is thin.', fix: 'Add panel rules.' },
+ },
+ });
+ const standing = 'The visitor has no defined body scale or metabolic support needs.';
+ const firstRejected = 'The mentor subplot vanishes entirely after the second issue.';
+ const surfaced = 'Every core cast member shares one identical grief reflex.';
+ const secondRejected = 'The finale resolves offstage inside a single unread letter.';
+ judgeFoundation
+ // R1: character is the weak target → repair #1.
+ .mockImplementationOnce(async () => snap(6, 5, standing))
+ // R2: repair #1 left character WORSE → reverted, rejection banked → repair #2.
+ .mockImplementationOnce(async () => snap(5.5, 4, firstRejected))
+ // R3: repair #2 earned its keep (5 → 6) → repair #3 from the new state.
+ .mockImplementationOnce(async () => snap(6.5, 6, surfaced))
+ // R4: repair #3 regressed → reverted, second rejection banked → repair #4.
+ .mockImplementationOnce(async () => snap(6, 5, secondRejected))
+ // R5: repair #4 cleared the gate.
+ .mockImplementationOnce(async () => snap(9, 9, 'clean'));
+
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, { maxFoundationRounds: 5 });
+ await waitFor(runFinished(seriesId));
+
+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');
+ const characterRepairs = applyFoundationFix.mock.calls.filter(([, d]) => d === 'character');
+ expect(characterRepairs).toHaveLength(4);
+ const avoided = characterRepairs[3][2].avoidFindings.map((f) => f.problem);
+ // BOTH rejected candidates, not just the most recent one — and the accepted
+ // repair in between did not wipe the first: a candidate the gate rejected is
+ // still a candidate it rejected.
+ expect(avoided).toEqual(expect.arrayContaining([secondRejected, firstRejected]));
+ // The gap this call is being ASKED to close is filtered out — telling the
+ // editor both "fix this" and "never author this" is contradictory.
+ expect(avoided).not.toContain(surfaced);
+ });
+
+ it('foundation gate: stamps its per-dimension rollback history on the pause marker (#3835)', async () => {
+ const stalled = {
+ seriesId: 'ser-example', status: 'complete', weightedScore: 6,
+ dimensions: {
+ worldbuilding: { score: 9, gap: 'The ration authority is unnamed.', fix: 'Name it.' },
+ character: { score: 5, gap: 'The mentor subplot vanishes entirely after the second issue.', fix: 'Restore it.' },
+ structure: { score: 9, gap: 'The charter handoff is thin.', fix: 'Stage the handoff.' },
+ craft: { score: 9, gap: 'The panel grammar is thin.', fix: 'Add panel rules.' },
+ },
+ };
+ judgeFoundation.mockImplementation(async () => stalled);
+
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, { maxFoundationRounds: 5 });
+ await waitFor(runFinished(seriesId));
+
+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('paused');
+ // Keyed by dimension so a resumed gate hands each editor back its OWN
+ // history — a rejected character rewrite is no reason for the structure
+ // editor to avoid anything.
+ const { foundationDiscardedFindings } = (await seriesSvc.getSeries(seriesId)).autopilot;
+ expect(Object.keys(foundationDiscardedFindings)).toEqual(['character']);
+ expect(foundationDiscardedFindings.character).toEqual(expect.arrayContaining([
+ expect.objectContaining({ problem: stalled.dimensions.character.gap }),
+ ]));
+ });
+
+ it('foundation gate: seeds a resumed run with the dimension history the pause carried (#3835)', async () => {
+ const carried = [{ severity: 'high', location: 'character (weight 25%, scored 4)', problem: 'The mentor subplot vanishes entirely after the second issue.' }];
+ const snap = (weightedScore, characterScore) => ({
+ seriesId: 'ser-example', status: 'complete', weightedScore,
+ dimensions: {
+ worldbuilding: { score: 9, gap: 'The ration authority is unnamed.', fix: 'Name it.' },
+ character: { score: characterScore, gap: 'The visitor has no defined body scale or metabolic support needs.', fix: 'Author it.' },
+ structure: { score: 9, gap: 'The charter handoff is thin.', fix: 'Stage the handoff.' },
+ craft: { score: 9, gap: 'The panel grammar is thin.', fix: 'Add panel rules.' },
+ },
+ });
+ judgeFoundation
+ .mockImplementationOnce(async () => snap(6, 5))
+ .mockImplementationOnce(async () => snap(9, 9));
+
+ const { seriesId } = await seedComplete();
+ await seriesSvc.updateSeries(seriesId, {
+ autopilot: {
+ status: 'paused', currentStep: 'foundationGate',
+ foundationDiscardedFindings: { character: carried },
+ },
+ });
+ await autopilot.startSeriesAutopilot(seriesId, { maxFoundationRounds: 5 });
+ await waitFor(runFinished(seriesId));
+
+ // A resume starts a fresh gate with an empty bank, so without the carry the
+ // very repair the paused run reverted is free to come straight back.
+ const [, , options] = applyFoundationFix.mock.calls.find(([, d]) => d === 'character');
+ expect(options.avoidFindings.map((f) => f.problem)).toEqual([carried[0].problem]);
+ });
+
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.js
index 34ea7e5e31..2f4de7af73 100644
--- a/server/services/pipeline/seriesAutopilot/childRuns.js
+++ b/server/services/pipeline/seriesAutopilot/childRuns.js
@@ -31,6 +31,7 @@ import {
isTargetedPatchRegression,
isIsolatedFixSafe,
} from './convergence.js';
+import { createDiscardedBank } from './discardedEvidence.js';
import { broadcast, budgetPause, providerOverrideOpts, providerIdOpts, roleLlm, seasonPreserveOpts } from './session.js';
import { recordModelOutcome } from './modelPerformance.js';
import { requiredScriptStages, textReady } from './stepResolver.js';
@@ -211,7 +212,7 @@ async function verifyArcBlocking(seriesId, record, { spineOnly }) {
* resolve after a successful isolation gets too. Computing it once up front
* made every attempt repeat the prompt the previous one had just failed with.
*/
-async function isolateArcFindings(seriesId, record, { scope, round, spineOnly, baseline, avoidFindings, bankDiscarded, attemptsLeft }) {
+async function isolateArcFindings(seriesId, record, { scope, round, spineOnly, baseline, bank, 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
@@ -238,7 +239,7 @@ async function isolateArcFindings(seriesId, record, { scope, round, spineOnly, b
// target for this pass, so the whole set — not just `target` — is what the
// avoid list is filtered against; the resolver is never told to both fix
// and avoid the same finding.
- const avoid = avoidFindings([], blocking());
+ const avoid = bank.avoid([], blocking());
const resolved = await resolveArcFindings(seriesId, record, { findings: [target], avoid, spineOnly });
const verified = await verifyArcBlocking(seriesId, record, { spineOnly });
if (verified.outcome) {
@@ -267,7 +268,7 @@ async function isolateArcFindings(seriesId, record, { scope, round, spineOnly, b
// same evidence a whole-set rollback banks, at single-finding grain.
// Without this the pass paid a resolve + a verify to learn something no
// later attempt (or the round that follows) ever hears about.
- bankDiscarded(discardedSet(verified.blocking));
+ bank.record(discardedSet(verified.blocking));
}
broadcast(seriesId, {
type: 'resolve:isolate', scope, round, attempt: attempts,
@@ -293,12 +294,23 @@ async function isolateArcFindings(seriesId, record, { scope, round, spineOnly, b
* the first.
*/
export async function runArcVerify(seriesId, record, opts = {}) {
- const runDiscarded = [];
- const outcome = await runArcVerifyRounds(seriesId, record, { ...opts, runDiscarded });
- return outcome?.pause ? { ...outcome, runDiscarded: discardedSet(runDiscarded) } : outcome;
+ // Every blocker set THIS gate has discarded, newest first (see
+ // `createDiscardedBank`). A rollback's evidence used to reach only the
+ // corrective retry that immediately followed it: the next ordinary resolve
+ // rebuilt its avoid list from scratch, so once a retry landed on a non-worse
+ // but still-blocked state the resolver was free to re-author the exact rewrite
+ // the gate had just reverted — the observed 2 → 1 → 5 (revert) → 1 → 2
+ // (revert, out of retries) stall. Seeded with whatever a prior pause carried,
+ // so a gate resumed twice still stamps the WHOLE history rather than only what
+ // this run threw away.
+ const bank = createDiscardedBank(Array.isArray(record.options.priorArcAvoidFindings)
+ ? record.options.priorArcAvoidFindings
+ : []);
+ const outcome = await runArcVerifyRounds(seriesId, record, { ...opts, bank });
+ return outcome?.pause ? { ...outcome, runDiscarded: bank.all() } : outcome;
}
-async function runArcVerifyRounds(seriesId, record, { spineOnly = false, runDiscarded }) {
+async function runArcVerifyRounds(seriesId, record, { spineOnly = false, bank }) {
const maxRounds = Number.isInteger(record.options.maxArcVerifyRounds)
? record.options.maxArcVerifyRounds
: MAX_ARC_VERIFY_ROUNDS;
@@ -312,46 +324,6 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, runDisc
// from a spine round misreports the failure to both the status line and the
// stall-diagnosis prompt that replays these frames.
const scope = spineOnly ? 'arcSpine' : 'arc';
- const priorAvoid = Array.isArray(record.options.priorArcAvoidFindings)
- ? record.options.priorArcAvoidFindings
- : [];
- // Every blocker set THIS gate has already discarded, newest first. A
- // rollback's evidence used to reach only the corrective retry that immediately
- // followed it: the next ordinary resolve rebuilt its avoid list from scratch,
- // so once a retry landed on a non-worse but still-blocked state the resolver
- // was free to re-author the exact rewrite the gate had just reverted — the
- // observed 2 → 1 → 5 (revert) → 1 → 2 (revert, out of retries) stall.
- // Records a discarded blocker set as this gate's newest evidence. Called at
- // the moment a rewrite is thrown away — the rollback, the rewind, an isolated
- // patch's revert — so no exit has to remember to do it on that path's behalf.
- const bankDiscarded = (current = []) => {
- runDiscarded.unshift(...current.filter((finding) => !containsFinding(runDiscarded, finding)));
- };
- // Builds the avoid list for ONE resolve call and banks that call's own newest
- // evidence into the history, so this is where a rejected candidate stops being
- // the retry's private knowledge. Preserves cross-Resume evidence and this run's
- // earlier rollbacks underneath. `discardedSet` keeps the provider prompt bounded
- // exactly like the persisted marker — `current` leads so the newest evidence is
- // never the part that gets cut at that bound.
- const avoidFindings = (current = [], active = []) => {
- const avoid = discardedSet([
- // The caller's own discarded set stays whole because its restatements
- // describe the exact candidate that was just rejected and are intentional
- // retry evidence.
- ...current,
- // A latent defect from a rejected candidate can later be found in the
- // restored checkpoint itself. Once it is a CURRENT target, telling the
- // resolver both "fix this" and "avoid this" is contradictory, so the
- // carried-over evidence is filtered against what this call is fixing —
- // and against `current`, which routinely restates an earlier rollback's
- // findings the history above already holds.
- ...[...runDiscarded, ...priorAvoid].filter((candidate) => (
- !containsFinding(active, candidate) && !containsFinding(current, candidate)
- )),
- ]);
- bankDiscarded(current);
- return avoid;
- };
let convergence = { best: null, sinceBest: 0 };
let changed = false;
// Best verified checkpoint seen in this gate, paired with the exact arc /
@@ -421,7 +393,7 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, runDisc
const rollbackTarget = bestVerified || lastResolve;
const rollback = await restoreArcState(seriesId, rollbackTarget.snapshot);
const discarded = discardedSet(blocking);
- bankDiscarded(discarded);
+ bank.record(discarded);
// 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
@@ -473,7 +445,7 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, runDisc
if (beforeRetry) return beforeRetry;
const retried = await resolveArcFindings(seriesId, record, {
findings: rollbackTarget.blocking,
- avoid: avoidFindings(discarded, rollbackTarget.blocking),
+ avoid: bank.avoid(discarded, rollbackTarget.blocking),
spineOnly,
});
if (retried?.applied !== false) changed = true;
@@ -498,8 +470,7 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, runDisc
const isolated = await isolateArcFindings(seriesId, record, {
scope, round, spineOnly,
baseline: rollbackTarget.blocking,
- avoidFindings,
- bankDiscarded,
+ bank,
attemptsLeft: isolationLeft,
});
isolationLeft -= isolated.attempts;
@@ -561,7 +532,7 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, runDisc
if (isNewBest || !bestVerified) return { residual: blocking, discarded: [] };
await restoreArcState(seriesId, bestVerified.snapshot);
const discarded = discardedSet(blocking);
- bankDiscarded(discarded);
+ bank.record(discarded);
return { residual: bestVerified.blocking, discarded };
};
if (round === maxRounds) {
@@ -592,7 +563,7 @@ async function runArcVerifyRounds(seriesId, record, { spineOnly = false, runDisc
// only place they can actually close a finding.
const resolved = await resolveArcFindings(seriesId, record, {
findings: blocking,
- avoid: avoidFindings([], blocking),
+ avoid: bank.avoid([], blocking),
spineOnly,
});
if (resolved?.applied === false) {
@@ -753,6 +724,17 @@ export async function runCharacterFoundation(seriesId, record) {
// 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) {
+ // Same one-exit stamping as `runArcVerify` (#3829), for the same reason: every
+ // pause the loop can produce owes the next run the whole gate's evidence, and
+ // spelling that at each `return` is how the forwarded ones get missed. Keyed
+ // by dimension — a rejected character repair says nothing about a structure
+ // attempt — and seeded with what a prior pause carried.
+ const bank = createDiscardedBank(record.options.priorFoundationAvoidFindings);
+ const outcome = await runFoundationRounds(seriesId, record, { bank });
+ return outcome?.pause ? { ...outcome, foundationDiscarded: bank.byKey() } : outcome;
+}
+
+async function runFoundationRounds(seriesId, record, { bank }) {
const maxRounds = Number.isInteger(record.options.maxFoundationRounds)
? record.options.maxFoundationRounds
: MAX_FOUNDATION_ROUNDS;
@@ -781,9 +763,14 @@ export async function runFoundationGate(seriesId, record) {
// 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.
+ // the strategy note describing what was just reverted, the set that attempt
+ // discarded (what the pause renders), plus the rewind notice to report if that
+ // dimension ends up exhausting its patience. Deliberately last-only — the note
+ // and the rewind notice describe ONE reverted attempt and go stale the moment
+ // the dimension keeps a repair. The accumulating evidence a retry must avoid
+ // authoring lives in `bank` instead, which is not cleared by an accepted
+ // repair: a candidate this gate already rejected is still a candidate it
+ // rejected, and the arc gate keeps its history for the same reason (#3835).
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
@@ -891,6 +878,10 @@ export async function runFoundationGate(seriesId, record) {
// read) from re-buying a score the gate is holding.
const rollback = await restoreFoundationState(seriesId, rejectedSnapshot, { judge: rejectedJudge });
const discarded = discardedSet(residualFindings(snap.dimensions));
+ // Bank it the moment it is thrown away, not when the next repair reads
+ // it — an unverified restore returns below without ever reaching a
+ // retry, and its evidence still belongs to the resume.
+ bank.record(discarded, dimension);
broadcast(seriesId, {
type: 'foundation:rollback', round, dimension,
targetBefore: beforeTargetScore, targetAfter: afterTargetScore,
@@ -924,9 +915,10 @@ export async function runFoundationGate(seriesId, record) {
({ 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.
+ // A kept repair clears the dimension's last-rejection NOTE: the next
+ // attempt is working from different content, so a stale "this failed,
+ // try another angle" strategy line would misdirect it. The banked
+ // evidence survives — those candidates were still rejected.
rejectionByDimension.delete(dimension);
}
}
@@ -1029,10 +1021,21 @@ export async function runFoundationGate(seriesId, record) {
...(snap.dimensions?.[weak.dimension] || {}),
...(priorRejection ? { retryReason: priorRejection.note } : {}),
};
+ // EVERY candidate this dimension has discarded, not just the last one — a
+ // dimension that rejected two different repairs used to hand the third
+ // evidence of only the second, leaving the repairer free to re-author the
+ // first. Filtered against the gap this call is being asked to close, which
+ // a rejected attempt's residual set routinely restates: telling the editor
+ // both "fix this" and "do not author this" is contradictory.
+ const avoidFindings = bank.avoid(
+ [],
+ residualFindings({ [weak.dimension]: snap.dimensions?.[weak.dimension] }),
+ weak.dimension,
+ );
try {
fix = await applyFoundationFix(seriesId, weak.dimension, {
finding: repairFinding,
- avoidFindings: priorRejection?.discarded,
+ avoidFindings,
providerOverride: creativeLlm.providerOverride,
modelOverride: creativeLlm.modelOverride,
judgeProviderDefault: judgeLlm.providerOverride,
diff --git a/server/services/pipeline/seriesAutopilot/discardedEvidence.js b/server/services/pipeline/seriesAutopilot/discardedEvidence.js
new file mode 100644
index 0000000000..d9297e6cff
--- /dev/null
+++ b/server/services/pipeline/seriesAutopilot/discardedEvidence.js
@@ -0,0 +1,104 @@
+/**
+ * Rollback evidence for the autopilot's convergence gates (#3835).
+ *
+ * Every gate that can THROW A REPAIR AWAY owes the next attempt the whole set of
+ * candidates it has already discarded — not just the most recent one. A gate
+ * that remembers only the last rejection lets the resolver re-author the first:
+ * the observed 2 → 1 → 5 (revert) → 1 → 2 (revert, out of retries) stall the arc
+ * gate was fixed for (#3829/#3832), and the same loss the foundation gate had
+ * per dimension.
+ *
+ * The arc gate banks ONE flat history for the run; the foundation gate banks one
+ * per dimension, because its repairs are owned by independent editors and a
+ * character rejection says nothing about a structure attempt. That is the only
+ * difference between them, so both ride this keyed bank — the arc gate simply
+ * never passes a key. Two hand-rolled accumulators in one file is how their
+ * behaviour drifts while a reader assumes it hasn't.
+ *
+ * Pure except for the bank's own closed-over state: no I/O, no broadcast.
+ */
+
+import { AUTOPILOT_DISCARDED_MAX } from '../series.js';
+import { containsFinding } from './convergence.js';
+
+// A gate's evidence is diagnostic context for one prompt, so it is bounded to
+// the same cap the persisted marker uses — otherwise the live SSE frame and the
+// resume marker would disagree about what was thrown away.
+export const boundDiscarded = (findings) => (Array.isArray(findings)
+ ? findings.slice(0, AUTOPILOT_DISCARDED_MAX)
+ : []);
+
+// The single-history gates (arc) bank under one key rather than growing a second
+// code path for "no key".
+const FLAT = '';
+
+/**
+ * A gate-lifetime bank of discarded findings, newest first, keyed by repair
+ * target.
+ *
+ * `prior` seeds it with evidence carried across a pause — an array for a flat
+ * gate, or a `{ key: findings[] }` map for a keyed one. Seeding (rather than
+ * holding it alongside) is what keeps a SECOND pause from dropping the first
+ * run's evidence: `byKey()`/`all()` re-emit what was carried in, so the marker a
+ * twice-resumed gate stamps is still the whole history.
+ */
+export function createDiscardedBank(prior) {
+ const banked = new Map();
+ const seed = Array.isArray(prior) ? { [FLAT]: prior } : (prior || {});
+ for (const [key, findings] of Object.entries(seed)) {
+ if (Array.isArray(findings) && findings.length > 0) banked.set(key, [...findings]);
+ }
+
+ /** Everything banked for `key`, newest first, bounded. */
+ const history = (key = FLAT) => boundDiscarded(banked.get(key) || []);
+
+ /**
+ * Record a discarded set as this key's newest evidence. Called at the moment a
+ * candidate is thrown away — a rollback, a rewind, an isolated patch's revert
+ * — so no exit has to remember to do it on that path's behalf. Findings the
+ * bank already holds are not re-banked: the verifier restates the same problem
+ * freely, and a bank of paraphrases would push the real history past the bound.
+ */
+ const record = (findings, key = FLAT) => {
+ const current = Array.isArray(findings) ? findings : [];
+ const held = banked.get(key) || [];
+ held.unshift(...current.filter((finding) => !containsFinding(held, finding)));
+ banked.set(key, held);
+ };
+
+ /**
+ * Build the avoid list for ONE repair call and bank that call's own evidence,
+ * so a rejected candidate stops being the next retry's private knowledge.
+ *
+ * `current` — the set this call is itself discarding — leads and stays whole:
+ * it describes the exact candidate just rejected, and leading it means the
+ * newest evidence is never the part the bound cuts. `active` is what this call
+ * is being asked to FIX; a latent defect from a rejected candidate can later be
+ * found in the restored checkpoint itself, and telling the repairer both "fix
+ * this" and "avoid this" is contradictory, so carried evidence is filtered
+ * against it (and against `current`, which routinely restates it).
+ */
+ const avoid = (current = [], active = [], key = FLAT) => {
+ const own = Array.isArray(current) ? current : [];
+ const list = boundDiscarded([
+ ...own,
+ ...history(key).filter((candidate) => (
+ !containsFinding(active, candidate) && !containsFinding(own, candidate)
+ )),
+ ]);
+ record(own, key);
+ return list;
+ };
+
+ /** The flat gate's whole history — what a pause stamps onto its marker. */
+ const all = () => history(FLAT);
+
+ /** The keyed gate's whole history, bounded per key, empty keys dropped. */
+ const byKey = () => Object.fromEntries(
+ [...banked.keys()]
+ .map((key) => [key, history(key)])
+ .filter(([, findings]) => findings.length > 0),
+ );
+
+ return { record, avoid, history, all, byKey };
+}
diff --git a/server/services/pipeline/seriesAutopilot/discardedEvidence.test.js b/server/services/pipeline/seriesAutopilot/discardedEvidence.test.js
new file mode 100644
index 0000000000..08b8f453c2
--- /dev/null
+++ b/server/services/pipeline/seriesAutopilot/discardedEvidence.test.js
@@ -0,0 +1,86 @@
+import { describe, it, expect } from 'vitest';
+import { createDiscardedBank, boundDiscarded } from './discardedEvidence.js';
+import { AUTOPILOT_DISCARDED_MAX } from '../series.js';
+
+const finding = (problem, location = 'volume 1') => ({ severity: 'high', location, problem });
+
+const FIRST = finding('The mentor subplot vanishes entirely after the second issue.');
+const SECOND = finding('The finale resolves offstage inside a single unread letter.');
+const THIRD = finding('The visitor has no defined body scale or metabolic support needs.');
+
+describe('createDiscardedBank (#3835)', () => {
+ it('accumulates every discarded set, newest first, instead of the last one', () => {
+ const bank = createDiscardedBank();
+ bank.record([FIRST]);
+ bank.record([SECOND]);
+ expect(bank.history().map((f) => f.problem)).toEqual([SECOND.problem, FIRST.problem]);
+ });
+
+ it('does not re-bank a paraphrase of something it already holds', () => {
+ const bank = createDiscardedBank();
+ bank.record([FIRST]);
+ bank.record([{ ...FIRST, problem: 'the mentor subplot vanishes after the second issue entirely' }]);
+ expect(bank.history()).toHaveLength(1);
+ });
+
+ it('keeps each key\'s history separate', () => {
+ const bank = createDiscardedBank();
+ bank.record([FIRST], 'character');
+ bank.record([SECOND], 'structure');
+ expect(bank.history('character').map((f) => f.problem)).toEqual([FIRST.problem]);
+ expect(bank.history('structure').map((f) => f.problem)).toEqual([SECOND.problem]);
+ expect(bank.byKey()).toEqual({ character: [FIRST], structure: [SECOND] });
+ });
+
+ it('avoid() leads with the call\'s own set, then the carried history, and banks both', () => {
+ const bank = createDiscardedBank();
+ bank.record([FIRST]);
+ expect(bank.avoid([SECOND]).map((f) => f.problem)).toEqual([SECOND.problem, FIRST.problem]);
+ expect(bank.history().map((f) => f.problem)).toEqual([SECOND.problem, FIRST.problem]);
+ });
+
+ it('avoid() drops carried evidence that is now an active repair target', () => {
+ const bank = createDiscardedBank();
+ bank.record([FIRST]);
+ bank.record([SECOND]);
+ // Telling the repairer both "fix this" and "never author this" is contradictory.
+ expect(bank.avoid([], [FIRST]).map((f) => f.problem)).toEqual([SECOND.problem]);
+ // Filtering the PROMPT does not forget it — a later call still avoids it.
+ expect(bank.history().map((f) => f.problem)).toEqual([SECOND.problem, FIRST.problem]);
+ });
+
+ it('seeds from a flat prior and re-emits it, so a second pause keeps the first run\'s evidence', () => {
+ const bank = createDiscardedBank([FIRST]);
+ bank.record([SECOND]);
+ expect(bank.all().map((f) => f.problem)).toEqual([SECOND.problem, FIRST.problem]);
+ });
+
+ it('seeds from a keyed prior', () => {
+ const bank = createDiscardedBank({ character: [FIRST] });
+ bank.record([SECOND], 'character');
+ bank.record([THIRD], 'craft');
+ expect(bank.byKey().character.map((f) => f.problem)).toEqual([SECOND.problem, FIRST.problem]);
+ expect(bank.byKey().craft.map((f) => f.problem)).toEqual([THIRD.problem]);
+ });
+
+ it('bounds each key at the marker\'s cap, keeping the newest', () => {
+ const bank = createDiscardedBank();
+ // Wholly disjoint wording per entry — `sameFinding` is deliberately loose
+ // about phrasing, so a shared sentence frame would read as one repeat.
+ const distinct = (i) => finding(`alpha${i} beta${i} gamma${i} delta${i}`, `volume ${i}`);
+ for (let i = 0; i < AUTOPILOT_DISCARDED_MAX + 5; i += 1) bank.record([distinct(i)]);
+ const history = bank.history();
+ expect(history).toHaveLength(AUTOPILOT_DISCARDED_MAX);
+ expect(history[0].problem).toBe(distinct(AUTOPILOT_DISCARDED_MAX + 4).problem);
+ });
+
+ it('byKey() drops keys that banked nothing', () => {
+ const bank = createDiscardedBank();
+ bank.record([], 'character');
+ expect(bank.byKey()).toEqual({});
+ });
+
+ it('boundDiscarded tolerates a non-array', () => {
+ expect(boundDiscarded(null)).toEqual([]);
+ });
+});
diff --git a/server/services/pipeline/seriesAutopilot/orchestrator.js b/server/services/pipeline/seriesAutopilot/orchestrator.js
index b3b6da2874..a5d8b393f6 100644
--- a/server/services/pipeline/seriesAutopilot/orchestrator.js
+++ b/server/services/pipeline/seriesAutopilot/orchestrator.js
@@ -82,6 +82,16 @@ export async function startSeriesAutopilot(sId, options = {}) {
? seriesRecord.autopilot
: null;
const priorArcAvoidFindings = arcPause?.runDiscardedFindings || [];
+ // Same carry for the foundation gate, keyed by dimension (#3835). A resume
+ // starts a fresh gate with an empty bank, so without this the very repair the
+ // paused run reverted is free to come straight back — the loss #3832 closed
+ // for the arc gate. Only read off a pause that came FROM the foundation gate:
+ // evidence describing dimension gaps means nothing to another step's repairs.
+ const foundationPause = seriesRecord?.autopilot?.status === 'paused'
+ && seriesRecord.autopilot.currentStep === 'foundationGate'
+ ? seriesRecord.autopilot
+ : null;
+ const priorFoundationAvoidFindings = foundationPause?.foundationDiscardedFindings || {};
const autoSelectModels = resolveAutopilotAutoSelectModels(options, settings);
const modelPerformance = autoSelectModels
? await getModelPerformanceReport().catch((err) => {
@@ -125,6 +135,7 @@ export async function startSeriesAutopilot(sId, options = {}) {
judge: judgeRouteExplicit,
},
priorArcAvoidFindings,
+ priorFoundationAvoidFindings,
// Run provider/model: per-run override → the series' own `series.llm` →
// unset (stage pin / active provider downstream). Resolved ONCE here so the
// manual run, a scheduled run and the UI's "this run calls X / Y" copy all
@@ -440,6 +451,10 @@ export async function startSeriesAutopilot(sId, options = {}) {
// that gate emits it. `discardedFindings` above stays scoped to the
// round that was reverted last, which is what the panel renders.
runDiscardedFindings: result.runDiscarded || [],
+ // The foundation gate's equivalent, keyed by dimension because its
+ // repairs are owned by independent editors (#3835). Same posture:
+ // resume evidence, not rendered.
+ foundationDiscardedFindings: result.foundationDiscarded || {},
pauseKind: result.pauseKind || null,
healthBreakdown: result.healthBreakdown || null,
...pm,