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: retain best foundation structure repair

[._.]/ Adam Eivyd85d54f55c4e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0d099e3c7e..3a70080b73 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -9,6 +9,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.
- **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.
- **Arc verification can now repair the per-character milestones it judges.** The verifier already read canonical per-character arcs, but its resolver could only edit the series arc, volumes, and issue synopses, so a contradiction in a character transition was impossible to close and repeated retries rewrote unrelated records instead. Finding-keyed character-arc patches now preserve character and transition IDs, merge only named fields, participate in regression rollback, and migrate existing prompt installations to the sparse contract.
diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.js
index c1824ed35b..e982a6d038 100644
--- a/server/services/pipeline/foundationJudge.js
+++ b/server/services/pipeline/foundationJudge.js
@@ -1663,6 +1663,7 @@ export async function applyFoundationFix(seriesId, dimension, {
suggestion: finding.fix || '',
}];
const snapshot = await snapshotArcState(seriesId);
+ const structureRunIds = [];
const resolveOptions = {
providerDefault: providerOverride,
modelDefault: modelOverride,
@@ -1672,7 +1673,10 @@ export async function applyFoundationFix(seriesId, dimension, {
// Carry the same non-deletion guarantee the other two do.
preserveDroppedSeasons,
effortDefault: effortOverride,
- onRunCreated,
+ onRunCreated: (runId) => {
+ structureRunIds.push(runId);
+ onRunCreated?.(runId);
+ },
onRunSettled,
};
const verifyOptions = {
@@ -1682,15 +1686,32 @@ export async function applyFoundationFix(seriesId, dimension, {
onRunCreated: judgeOnRunCreated,
onRunSettled: judgeOnRunSettled,
};
+ const trackedResolve = async (resolveFindings) => {
+ const before = structureRunIds.length;
+ const result = await resolveVerifyIssues(seriesId, { findings: resolveFindings, ...resolveOptions });
+ return { result, runIds: structureRunIds.slice(before) };
+ };
const runGuardedStructureRepair = async () => {
- const first = await resolveVerifyIssues(seriesId, { findings, ...resolveOptions });
+ const firstAttempt = await trackedResolve(findings);
+ const first = firstAttempt.result;
if (first?.applied === false) {
return { dimension, applied: false, reason: first?.notes || 'arc resolver applied no change' };
}
let verification = await verifyArc(seriesId, verifyOptions);
let blockers = Array.isArray(verification?.issues) ? verification.issues : [];
- if (blockers.length === 0) return { dimension, applied: true, actions: 2 };
+ if (blockers.length === 0) {
+ return { dimension, applied: true, actions: 2, acceptedRunIds: firstAttempt.runIds };
+ }
+
+ const initialBlockerCount = blockers.length;
+ let retainedRunIds = [...firstAttempt.runIds];
+ let rejectedRunIds = [];
+ let bestVerified = {
+ blockers,
+ snapshot: await snapshotArcState(seriesId),
+ runIds: [...retainedRunIds],
+ };
// A foundation-directed structure rewrite can satisfy its broad judge
// while accidentally violating a narrower canon/location/timing rule.
@@ -1702,24 +1723,62 @@ export async function applyFoundationFix(seriesId, dimension, {
let actions = 2;
for (let pass = 0; pass < MAX_STRUCTURE_CORRECTION_PASSES && blockers.length > 0; pass += 1) {
const before = blockers.length;
- const correction = await resolveVerifyIssues(seriesId, {
- findings: blockers,
- ...resolveOptions,
- });
+ const correctionAttempt = await trackedResolve(blockers);
+ const correction = correctionAttempt.result;
actions += 1;
if (correction?.applied === false) break;
verification = await verifyArc(seriesId, verifyOptions);
actions += 1;
const nextBlockers = Array.isArray(verification?.issues) ? verification.issues : [];
blockers = nextBlockers;
- if (blockers.length === 0) return { dimension, applied: true, actions };
- if (blockers.length > before) break;
+ if (blockers.length === 0) {
+ return {
+ dimension,
+ applied: true,
+ actions,
+ acceptedRunIds: [...retainedRunIds, ...correctionAttempt.runIds],
+ rejectedRunIds,
+ };
+ }
+ if (blockers.length > before) {
+ rejectedRunIds = [...rejectedRunIds, ...correctionAttempt.runIds];
+ break;
+ }
+ retainedRunIds = [...retainedRunIds, ...correctionAttempt.runIds];
+ if (blockers.length <= bestVerified.blockers.length) {
+ bestVerified = {
+ blockers,
+ snapshot: await snapshotArcState(seriesId),
+ runIds: [...retainedRunIds],
+ };
+ }
+ }
+
+ // Do not throw away a demonstrated monotonic improvement merely because
+ // the next correction traded its final residual for a larger set. Keep
+ // the best independently verified checkpoint; the foundation judge will
+ // still decide whether it improved structure, and the normal full-arc
+ // gate remains latched dirty so it must close the residual before beats.
+ if (bestVerified.blockers.length < initialBlockerCount) {
+ await restoreArcState(seriesId, bestVerified.snapshot);
+ return {
+ dimension,
+ applied: true,
+ partial: true,
+ actions,
+ reason: `structure repair retained its best verified improvement (${initialBlockerCount} → ${bestVerified.blockers.length} blocker(s)); the full arc gate must close the residual`,
+ residual: bestVerified.blockers,
+ discarded: blockers,
+ acceptedRunIds: bestVerified.runIds,
+ rejectedRunIds,
+ };
}
await restoreArcState(seriesId, snapshot);
return {
dimension,
applied: false,
+ reverted: true,
actions,
reason: `structure repair left ${blockers.length} arc-verification blocker(s); reverted to the pre-repair plan`,
// The blockers that condemned the rewrite. Without them the revert is a
@@ -1727,6 +1786,7 @@ export async function applyFoundationFix(seriesId, dimension, {
// gaps instead — a different set entirely — so the user is never shown
// why a plausible rewrite was thrown away.
discarded: blockers,
+ rejectedRunIds: structureRunIds,
};
};
// Any provider/parse failure after the first mutation must not strand the
diff --git a/server/services/pipeline/foundationJudge.test.js b/server/services/pipeline/foundationJudge.test.js
index d03998d5ed..df41982e86 100644
--- a/server/services/pipeline/foundationJudge.test.js
+++ b/server/services/pipeline/foundationJudge.test.js
@@ -1040,7 +1040,7 @@ describe('applyFoundationFix — dimension → owning-service routing table', ()
expect(arcPlanner.resolveVerifyIssues).toHaveBeenCalledTimes(2);
expect(arcPlanner.resolveVerifyIssues).toHaveBeenNthCalledWith(2, 'ser-1', expect.objectContaining({
findings: [blocker], providerDefault: 'writer-provider', modelDefault: 'writer-model', effortDefault: 'max',
- onRunCreated: writerOnRunCreated,
+ onRunCreated: expect.any(Function),
}));
expect(arcPlanner.verifyArc).toHaveBeenNthCalledWith(1, 'ser-1', expect.objectContaining({
providerDefault: 'judge-provider', modelDefault: 'judge-model', effortDefault: 'xhigh',
@@ -1070,6 +1070,51 @@ describe('applyFoundationFix — dimension → owning-service routing table', ()
expect(r).toMatchObject({ dimension: 'structure', applied: true, actions: 6 });
});
+ it('retains the best verified structure checkpoint when a later correction regresses', async () => {
+ const original = { seriesId: 'ser-1', arc: { logline: 'Original' }, seasons: [], episodes: [] };
+ const firstCandidate = { seriesId: 'ser-1', arc: { logline: 'Nine blockers' }, seasons: [], episodes: [] };
+ const bestCandidate = { seriesId: 'ser-1', arc: { logline: 'One blocker' }, seasons: [], episodes: [] };
+ arcPlanner.snapshotArcState
+ .mockResolvedValueOnce(original)
+ .mockResolvedValueOnce(firstCandidate)
+ .mockResolvedValueOnce(bestCandidate);
+ const findings = (n, prefix) => Array.from({ length: n }, (_, i) => ({
+ severity: 'medium', location: `Issue ${i + 1}`, problem: `${prefix} ${i + 1}`,
+ }));
+ arcPlanner.verifyArc
+ .mockResolvedValueOnce({ issues: findings(9, 'initial') })
+ .mockResolvedValueOnce({ issues: findings(1, 'best') })
+ .mockResolvedValueOnce({ issues: findings(5, 'regressed') });
+ arcPlanner.resolveVerifyIssues
+ .mockImplementationOnce(async (_id, options) => {
+ options.onRunCreated('structure-broad');
+ return { applied: true };
+ })
+ .mockImplementationOnce(async (_id, options) => {
+ options.onRunCreated('structure-improved');
+ return { applied: true };
+ })
+ .mockImplementationOnce(async (_id, options) => {
+ options.onRunCreated('structure-regressed');
+ return { applied: true };
+ });
+
+ const r = await applyFoundationFix('ser-1', 'structure', {
+ finding: { gap: 'The issue plan contradicts the spine.', fix: 'Reconcile it.' },
+ onRunCreated: vi.fn(),
+ });
+
+ expect(arcPlanner.restoreArcState).toHaveBeenCalledWith('ser-1', bestCandidate);
+ expect(arcPlanner.restoreArcState).not.toHaveBeenCalledWith('ser-1', original);
+ expect(r).toMatchObject({
+ dimension: 'structure', applied: true, partial: true,
+ acceptedRunIds: ['structure-broad', 'structure-improved'],
+ rejectedRunIds: ['structure-regressed'],
+ });
+ expect(r.residual).toHaveLength(1);
+ expect(r.discarded).toHaveLength(5);
+ });
+
it('rolls a structure repair back when its bounded correction remains unverified', async () => {
const snapshot = { seriesId: 'ser-1', arc: { logline: 'Before' }, seasons: [], episodes: [] };
arcPlanner.snapshotArcState.mockResolvedValue(snapshot);
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index 295de5be81..1ceecf8b2e 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -2054,20 +2054,30 @@ describe('autopilot conductor', () => {
{ severity: 'high', location: 'V2', problem: 'ration authority contradicts the founding charter' },
{ severity: 'medium', location: 'V3', problem: 'the eclipse lands before the calendar allows it' },
];
- foundationScore = 3;
- applyFoundationFix.mockImplementationOnce(async (_sId, dimension) => ({
- dimension,
- applied: false,
- actions: 4,
- reason: 'structure repair left 2 arc-verification blocker(s); reverted to the pre-repair plan',
- discarded: blockers,
- }));
+ foundationScore = 7;
+ foundationDimensionScores = { worldbuilding: 8, character: 8, structure: 3, craft: 8 };
+ applyFoundationFix.mockImplementationOnce(async (_sId, dimension, options) => {
+ options.onRunCreated('structure-reverted');
+ return {
+ dimension,
+ applied: false,
+ reverted: true,
+ actions: 4,
+ reason: 'structure repair left 2 arc-verification blocker(s); reverted to the pre-repair plan',
+ discarded: blockers,
+ rejectedRunIds: ['structure-reverted'],
+ };
+ });
const { seriesId } = await seedComplete();
await autopilot.startSeriesAutopilot(seriesId, { maxFoundationRounds: 3 });
await waitFor(runFinished(seriesId));
const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
expect(last?.pauseKind).toBe('inapplicable');
expect(last?.discardedFindings).toEqual(blockers);
+ expect(recordModelOutcome).toHaveBeenCalledWith('structure-reverted', expect.objectContaining({
+ role: 'creative', stage: 'foundationGate', outcome: 'rejected', target: 'structure',
+ }));
+ expect(recordModelOutcome).not.toHaveBeenCalledWith('structure-reverted', expect.objectContaining({ outcome: 'invalid' }));
});
it('foundation gate: an inapplicable fix with nothing reverted reports no discarded set', async () => {
diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.js
index 4e1a7cddc8..c184838f6c 100644
--- a/server/services/pipeline/seriesAutopilot/childRuns.js
+++ b/server/services/pipeline/seriesAutopilot/childRuns.js
@@ -819,6 +819,12 @@ export async function runFoundationGate(seriesId, record) {
};
}
await recordDomainUsage('cos', { actions: Math.max(1, fix?.actions || 1) });
+ const explicitlyRejectedRunIds = new Set(Array.isArray(fix?.rejectedRunIds) ? fix.rejectedRunIds : []);
+ await Promise.all([...explicitlyRejectedRunIds].map((runId) => recordModelOutcome(runId, {
+ role: 'creative', stage: 'foundationGate', outcome: 'rejected', target: weak.dimension,
+ }).catch(() => {})));
+ const retainedRepairRunIds = (Array.isArray(fix?.acceptedRunIds) ? fix.acceptedRunIds : repairRunIds)
+ .filter((runId) => !explicitlyRejectedRunIds.has(runId));
broadcast(seriesId, {
type: 'foundation:fix', round, dimension: weak.dimension, applied: fix?.applied === true, reason: fix?.reason || null,
});
@@ -828,8 +834,8 @@ export async function runFoundationGate(seriesId, record) {
// review rather than burning the remaining rounds re-judging an unchanged
// foundation.
if (fix?.applied !== true) {
- await Promise.all(repairRunIds.map((runId) => recordModelOutcome(runId, {
- role: 'creative', stage: 'foundationGate', outcome: 'invalid', target: weak.dimension,
+ await Promise.all(retainedRepairRunIds.map((runId) => recordModelOutcome(runId, {
+ role: 'creative', stage: 'foundationGate', outcome: fix?.reverted === true ? 'rejected' : 'invalid', target: weak.dimension,
}).catch(() => {})));
return {
pause: true,
@@ -846,7 +852,7 @@ export async function runFoundationGate(seriesId, record) {
dimension: weak.dimension,
judge: snap,
snapshot: repairSnapshot,
- runIds: repairRunIds,
+ runIds: retainedRepairRunIds,
};
changed = true;
}