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: roll back regressive foundation repairs

[._.]/ Adam Eivy36d024e6d91a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 726cb74924..12b8a65e12 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -15,6 +15,7 @@
- **Arc auto-resolve keeps corrections field-scoped and within storage limits.** A resolver fixing one synopsis now omits unrelated volume fields instead of paraphrasing them, and its prompt carries explicit headroom below every persisted arc/volume string cap so a well-intended rewrite cannot be silently clipped into the next verification failure.
- **Arc verification preserves its best demonstrated draft.** Any auto-resolve pass that raises the total blocking-finding count now pauses immediately and restores the lowest-blocker arc snapshot seen in that gate, even when the verifier describes the added problems as newly surfaced findings. Equal-count rounds advance the checkpoint because narrower replacement findings can reflect real causal repairs; divergence and max-round exits therefore keep the latest verified best state instead of rewinding useful work or preserving whichever unverified rewrite happened to run last. Because that guard is deliberately blind to finding identity, it can fire on a round that genuinely closed the problem it was handed and merely exposed latent defects — so a pause that rewinds now also reports the discarded round's own findings, collapsed beneath the restored set, making the trade reviewable instead of leaving only a count behind. The same accounting covers the foundation structure repair, whose revert previously reduced the arc blockers that condemned the rewrite to a number in its pause message while the findings it listed were the unrelated dimension-level gaps.
- **Foundation repair distinguishes a deeper critique from a stalled rewrite.** When a harsh re-judge holds a dimension at the same coarse score but identifies a genuinely different underlying gap, that new layer receives its own bounded repair window. Fuzzy-matched paraphrases of the same problem still accrue toward the divergence guard, so the loop remains finite instead of pausing simply because one successful fix exposed the next weakness.
+- **Foundation repairs must now earn their edits.** Before each world, character, structure, or craft repair, Series Autopilot checkpoints the complete foundation — universe prose and cast, series arcs and voice, volumes, and episode seeds. The next independent judge keeps a candidate only when its target dimension improves, or when a tied score exposes a genuinely new layer without lowering the weighted result. A repair that leaves its assigned problem unchanged or makes it worse is restored and verified immediately, then pauses with both the retained and discarded critiques instead of spending another long call on a worse baseline.
- **Foundation structure repairs cannot strand a newly contradictory arc.** Every judge-directed synopsis rewrite now snapshots the current plan, runs the specialized arc verifier, gives any new canon/location/timing blockers one bounded corrective pass, and restores the snapshot if that pass is still not clean or errors. The verifier uses the run's independent judge model while corrections stay on its creative model, and the extra calls are counted against the run's usage budget.
- **Continuing a video carries its prompt forward.** Continuing or extending a clip we generated now prefills the Video Gen prompt (and negative prompt) with the one that produced the source, instead of dropping you into an empty box. This covers both entry points: the **Continue** action on a video card/lightbox, and picking a prior render in Extend mode. Text you typed yourself is never overwritten — only a blank box or a value an earlier pick filled — and a clip we didn't generate (an import, or a legacy render with no stored prompt) leaves the field alone rather than clearing it. The style preset is dropped along with the prefill, since history stores the already-composed prompt and re-applying a preset would prefix it twice.
- **Subscription Usage cards now lay out in four quadrants.** The provider quota grid orders Claude, Antigravity, Codex, Grok — and because Codex and Grok typically report only a single weekly meter, they now share one grid cell stacked vertically instead of each stretching to a full-height card. Cards render at their natural height, so the Image Gen card floats into the fourth quadrant and the whole section fits above the fold on desktop.
diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.js
index a9b54ebe37..b8123692af 100644
--- a/server/services/pipeline/foundationJudge.js
+++ b/server/services/pipeline/foundationJudge.js
@@ -1452,6 +1452,75 @@ async function refineWorld(universeId, { providerId, model, effort, onRunCreated
: { applied: true };
}
+const FOUNDATION_UNIVERSE_SNAPSHOT_FIELDS = Object.freeze([
+ 'logline', 'premise', 'styleNotes', 'influences', 'characters',
+]);
+
+const FOUNDATION_SERIES_SNAPSHOT_FIELDS = Object.freeze([
+ 'styleNotes', 'styleGuide', 'characterArcs',
+]);
+
+const pickFoundationFields = (record, fields) => Object.fromEntries(
+ fields.map((field) => [
+ field,
+ record && Object.hasOwn(record, field) ? structuredClone(record[field]) : undefined,
+ ]),
+);
+
+const foundationSnapshotComparable = (snapshot) => JSON.stringify({
+ universeId: snapshot?.universeId || null,
+ universe: snapshot?.universe || null,
+ series: snapshot?.series || null,
+ arc: snapshot?.arcState?.arc ?? null,
+ seasons: snapshot?.arcState?.seasons || [],
+ episodes: snapshot?.arcState?.episodes || [],
+});
+
+/**
+ * Capture every field an owned foundation repair may rewrite. Arc planning has
+ * its own exact snapshot (including episode ideas); this adds the world,
+ * character, and craft-owned records so the conductor can reject a repair that
+ * a fresh judge proves did not earn its changes.
+ */
+export async function snapshotFoundationState(seriesId) {
+ assertValidSeriesId(seriesId);
+ const series = await getSeries(seriesId);
+ const [universe, arcState] = await Promise.all([
+ series?.universeId ? getUniverse(series.universeId).catch(() => null) : null,
+ snapshotArcState(seriesId),
+ ]);
+ return {
+ seriesId,
+ universeId: series?.universeId || null,
+ universe: universe ? pickFoundationFields(universe, FOUNDATION_UNIVERSE_SNAPSHOT_FIELDS) : null,
+ series: pickFoundationFields(series, FOUNDATION_SERIES_SNAPSHOT_FIELDS),
+ arcState,
+ };
+}
+
+/** Restore a foundation snapshot and verify the tracked fields match exactly. */
+export async function restoreFoundationState(seriesId, snapshot) {
+ if (!snapshot || snapshot.seriesId !== seriesId || !snapshot.arcState) {
+ return { restored: false, reason: 'invalid foundation snapshot' };
+ }
+ if (snapshot.universeId && snapshot.universe) {
+ await updateUniverse(snapshot.universeId, Object.fromEntries(
+ Object.entries(structuredClone(snapshot.universe)).filter(([, value]) => value !== undefined),
+ ));
+ }
+ await updateSeries(seriesId, Object.fromEntries(
+ Object.entries(structuredClone(snapshot.series)).filter(([, value]) => value !== undefined),
+ ));
+ const arcRestore = await restoreArcState(seriesId, snapshot.arcState);
+ const restoredSnapshot = await snapshotFoundationState(seriesId);
+ const restored = foundationSnapshotComparable(restoredSnapshot) === foundationSnapshotComparable(snapshot);
+ return {
+ restored,
+ reason: restored ? null : 'restored foundation fields did not match the checkpoint',
+ episodesRestored: arcRestore.episodesRestored || 0,
+ };
+}
+
/**
* Apply a fix for one foundation dimension through its OWNING service (never a
* raw write; `force:false` everywhere so locked canon is a constraint, not a
diff --git a/server/services/pipeline/foundationJudge.test.js b/server/services/pipeline/foundationJudge.test.js
index ab81eeb82b..bae7a99adc 100644
--- a/server/services/pipeline/foundationJudge.test.js
+++ b/server/services/pipeline/foundationJudge.test.js
@@ -74,6 +74,8 @@ const {
isValidFoundationShape,
isFoundationStale,
residualFindings,
+ snapshotFoundationState,
+ restoreFoundationState,
applyFoundationFix,
establishCharacterFoundation,
thinnestCharacter,
@@ -107,6 +109,59 @@ beforeEach(() => {
universeBuilderExpand.expandWorldTemplate.mockResolvedValue({ logline: 'L2', premise: 'P2', styleNotes: 'S2', influences: null });
});
+describe('foundation repair checkpoint', () => {
+ it('restores and verifies world, character, craft, arc, volume, and issue-seed state', async () => {
+ let seriesState = {
+ id: 'ser-1', universeId: 'uni-1', styleNotes: 'voice before',
+ styleGuide: { tone: ['spare'] }, characterArcs: [{ characterName: 'Example Lead' }],
+ };
+ let universeState = {
+ id: 'uni-1', logline: 'world before', premise: 'rules before', styleNotes: 'style before',
+ influences: { embrace: ['Example'], avoid: [] },
+ characters: [{ id: 'chr-1', name: 'Example Lead', need: 'trust' }],
+ };
+ let arcState = {
+ seriesId: 'ser-1', arc: { summary: 'arc before' },
+ seasons: [{ id: 'sea-1', synopsis: 'volume before' }],
+ episodes: [{ id: 'iss-1', seasonId: 'sea-1', idea: { input: 'seed before', output: '', status: 'ready' } }],
+ };
+ seriesSvc.getSeries.mockImplementation(async () => structuredClone(seriesState));
+ seriesSvc.updateSeries.mockImplementationOnce(async (_id, patch) => {
+ seriesState = { ...seriesState, ...structuredClone(patch) };
+ return structuredClone(seriesState);
+ });
+ universeBuilder.getUniverse.mockImplementation(async () => structuredClone(universeState));
+ universeBuilder.updateUniverse.mockImplementationOnce(async (_id, patch) => {
+ universeState = { ...universeState, ...structuredClone(patch) };
+ return structuredClone(universeState);
+ });
+ arcPlanner.snapshotArcState.mockImplementation(async () => structuredClone(arcState));
+ arcPlanner.restoreArcState.mockImplementation(async (_id, snapshot) => {
+ arcState = structuredClone(snapshot);
+ return { restored: true, episodesRestored: 1 };
+ });
+
+ const checkpoint = await snapshotFoundationState('ser-1');
+ seriesState = { ...seriesState, styleNotes: 'voice after', characterArcs: [] };
+ universeState = { ...universeState, premise: 'rules after', characters: [] };
+ arcState = { ...arcState, arc: { summary: 'arc after' }, episodes: [] };
+
+ const restored = await restoreFoundationState('ser-1', checkpoint);
+
+ expect(restored).toMatchObject({ restored: true, episodesRestored: 1 });
+ expect(seriesState).toMatchObject({
+ styleNotes: 'voice before',
+ styleGuide: { tone: ['spare'] },
+ characterArcs: [{ characterName: 'Example Lead' }],
+ });
+ expect(universeState).toMatchObject({
+ premise: 'rules before',
+ characters: [{ id: 'chr-1', name: 'Example Lead', need: 'trust' }],
+ });
+ expect(arcState).toEqual(checkpoint.arcState);
+ });
+});
+
describe('computeWeightedScore — weighted composite', () => {
it('weights the four dimensions 40/30/20/10', () => {
// all 10 → 10; all 5 → 5
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index cc3e265187..62ec8efbe8 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -168,6 +168,8 @@ const judgeFoundation = vi.fn(async () => ({
weakest: 'worldbuilding',
}));
const applyFoundationFix = vi.fn(async (_sId, dimension) => ({ dimension, applied: foundationFixApplied }));
+const snapshotFoundationState = vi.fn(async (seriesId) => ({ seriesId, marker: 'foundation-checkpoint' }));
+const restoreFoundationState = vi.fn(async () => ({ restored: true, episodesRestored: 0 }));
vi.mock('./foundationJudge.js', async (importOriginal) => {
const actual = await importOriginal();
return {
@@ -175,6 +177,8 @@ vi.mock('./foundationJudge.js', async (importOriginal) => {
judgeFoundation: (...args) => judgeFoundation(...args),
applyFoundationFix: (...args) => applyFoundationFix(...args),
establishCharacterFoundation: (...args) => establishCharacterFoundation(...args),
+ snapshotFoundationState: (...args) => snapshotFoundationState(...args),
+ restoreFoundationState: (...args) => restoreFoundationState(...args),
};
});
@@ -1696,10 +1700,10 @@ describe('autopilot conductor', () => {
worldbuilding: 7.4, character: 7.4, structure: 7.4, craft: 7.4,
}))
.mockImplementationOnce(async () => snap(6.6, {
- worldbuilding: 7, character: 7, structure: 5, craft: 7,
+ worldbuilding: 8, character: 7, structure: 5, craft: 7,
}))
.mockImplementationOnce(async () => snap(6.8, {
- worldbuilding: 7, character: 7, structure: 7, craft: 5,
+ worldbuilding: 8, character: 7, structure: 7, craft: 5,
}))
.mockImplementationOnce(async () => snap(8, {
worldbuilding: 8, character: 8, structure: 8, craft: 8,
@@ -1714,7 +1718,37 @@ describe('autopilot conductor', () => {
.toEqual(['worldbuilding', 'structure', 'craft']);
});
- it('foundation gate: still stops after the same target repeatedly fails to improve', async () => {
+ it('foundation gate: reverts a repair that leaves its target unchanged while lowering the aggregate', async () => {
+ const snapshot = (weightedScore) => ({
+ seriesId: 'ser-example', status: 'complete', weightedScore,
+ dimensions: {
+ worldbuilding: { score: 8, gap: 'The active-node evidence rule is undefined.', fix: 'Define it.' },
+ character: { score: 7, gap: 'Aruun privacy is mislabeled as a relapse.', fix: 'Separate privacy from safety disclosure.' },
+ structure: { score: 6, gap: 'The charter handoff is thin.', fix: 'Stage the handoff.' },
+ craft: { score: 7, gap: 'The panel grammar is thin.', fix: 'Add panel rules.' },
+ },
+ });
+ judgeFoundation
+ .mockImplementationOnce(async () => snapshot(7.2))
+ .mockImplementationOnce(async () => snapshot(7.1));
+ const checkpoint = { seriesId: 'ser-example', marker: 'before-character-repair' };
+ snapshotFoundationState.mockResolvedValueOnce(checkpoint);
+
+ const { seriesId } = await seedComplete();
+ 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.' }),
+ ]));
+ });
+
+ it('foundation gate: rejects the first repair when the same target fails to improve', async () => {
const stalled = {
seriesId: 'ser-example', status: 'complete', weightedScore: 7,
dimensions: {
@@ -1729,7 +1763,6 @@ describe('autopilot conductor', () => {
},
};
judgeFoundation
- .mockImplementationOnce(async () => stalled)
.mockImplementationOnce(async () => stalled)
.mockImplementationOnce(async () => stalled);
const { seriesId } = await seedComplete();
@@ -1737,9 +1770,9 @@ describe('autopilot conductor', () => {
await waitFor(runFinished(seriesId));
const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
- expect(last).toMatchObject({ type: 'paused', scope: 'foundationGate', pauseKind: 'divergence' });
- expect(judgeFoundation).toHaveBeenCalledTimes(3);
- expect(applyFoundationFix).toHaveBeenCalledTimes(2);
+ expect(last).toMatchObject({ type: 'paused', scope: 'foundationGate', pauseKind: 'regression' });
+ expect(judgeFoundation).toHaveBeenCalledTimes(2);
+ expect(applyFoundationFix).toHaveBeenCalledTimes(1);
});
it('foundation gate: gives a newly exposed gap at the same score its own repair window', async () => {
diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.js
index 0312c7e3d1..4cf91700f1 100644
--- a/server/services/pipeline/seriesAutopilot/childRuns.js
+++ b/server/services/pipeline/seriesAutopilot/childRuns.js
@@ -14,7 +14,7 @@ import {
} from '../arcPlanner.js';
import {
judgeFoundation, applyFoundationFix, establishCharacterFoundation, foundationGateStatus, foundationFixTarget,
- residualFindings, DEFAULT_FOUNDATION_THRESHOLD,
+ residualFindings, snapshotFoundationState, restoreFoundationState, DEFAULT_FOUNDATION_THRESHOLD,
} from '../foundationJudge.js';
import * as volumeBeatsRunner from '../volumeBeatsRunner.js';
import * as autoRunner from '../autoRunner.js';
@@ -344,6 +344,11 @@ export async function runFoundationGate(seriesId, record) {
// receives at least one repair attempt; repeated no-improvement in that same
// dimension still trips the bounded divergence guard.
const convergenceByDimension = new Map();
+ // A repair remains provisional until the next independent judge proves that
+ // it helped the dimension it was asked to fix. This is narrower than a global
+ // 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;
let changed = false;
for (let round = 1; round <= maxRounds; round += 1) {
if (record.cancelRequested) return { canceled: true };
@@ -371,6 +376,44 @@ export async function runFoundationGate(seriesId, record) {
dimensionFloor: gate.dimensionFloor, failingDimensions: gate.failingDimensions,
weakest: weak?.dimension || null,
});
+ if (pendingRepair) {
+ const dimension = pendingRepair.dimension;
+ const beforeDimension = pendingRepair.judge.dimensions?.[dimension] || {};
+ const afterDimension = snap.dimensions?.[dimension] || {};
+ const beforeTargetScore = Number(beforeDimension.score) || 0;
+ const afterTargetScore = Number(afterDimension.score) || 0;
+ const beforeWeighted = Number(pendingRepair.judge.weightedScore) || 0;
+ const targetImproved = afterTargetScore > beforeTargetScore;
+ const targetTied = afterTargetScore === beforeTargetScore;
+ const gapChanged = !sameFinding(
+ { location: dimension, problem: beforeDimension.gap || '' },
+ { location: dimension, problem: afterDimension.gap || '' },
+ );
+ // A tie can represent a deeper newly exposed layer, but only when the
+ // aggregate did not regress. A strictly improved target is accepted even
+ // if it makes another latent dimension judgeable.
+ const earned = targetImproved || (targetTied && gapChanged && score >= beforeWeighted);
+ if (!earned) {
+ 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'}.`;
+ broadcast(seriesId, {
+ type: 'foundation:rollback', round, dimension,
+ targetBefore: beforeTargetScore, targetAfter: afterTargetScore,
+ weightedBefore: beforeWeighted, weightedAfter: score,
+ reverted: rollback.restored,
+ });
+ return {
+ pause: true,
+ pauseKind: 'regression',
+ reason,
+ residual: residualFindings(pendingRepair.judge.dimensions),
+ discarded: discardedSet(residualFindings(snap.dimensions)),
+ };
+ }
+ pendingRepair = null;
+ }
if (gate.passes) {
record.runState.foundationGated = true;
if (changed && !finishPlanningMutation(record, 'arcVerified')) {
@@ -444,6 +487,7 @@ export async function runFoundationGate(seriesId, record) {
// so it gets the same treatment rather than the harshest one. The
// promptRunner has already walked its full fallback cascade by the time
// this throws, so there is no retry left to attempt here.
+ const repairSnapshot = await snapshotFoundationState(seriesId);
let fix;
try {
fix = await applyFoundationFix(seriesId, weak.dimension, {
@@ -493,6 +537,11 @@ export async function runFoundationGate(seriesId, record) {
discarded: Array.isArray(fix?.discarded) ? discardedSet(fix.discarded) : [],
};
}
+ pendingRepair = {
+ dimension: weak.dimension,
+ judge: snap,
+ snapshot: repairSnapshot,
+ };
changed = true;
}
return {};