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 shrinking structure repair progress

[._.]/ Adam Eivy4ad22aa6a53d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 32a0ce97c0..dc585a1aef 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,6 +4,8 @@
- **Series Autopilot can learn which models actually work at each step.** AI run history now distinguishes technical completion from a later editorial keep/revert decision and aggregates evidence by orchestration step, creative-versus-judge role, provider, model, and reasoning effort. The new opt-in selector requires multiple quality-reviewed samples plus a positive reliability threshold, ignores disabled providers and removed models, and remains a soft default beneath explicit run choices and exact prompt-stage pins. The Options panel reports how much attributed and quality-reviewed evidence exists, while local APIs expose the full metrics and allow an operator to correct or backfill a historical outcome, including its effort when the older run predates effort telemetry. Concurrent metadata updates for one run are serialized so provider telemetry cannot overwrite its Autopilot step/role attribution, and internal structure-verification calls retain the judge role instead of inheriting their repairer's creative role. Foundation judges record contract-valid responses separately from true editorial approval, and foundation repairs automatically record accepted versus rolled-back outcomes, so a model that finishes a long run but makes the story worse is not learned as a success.
+- **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.
+
- **Completed CoS agents no longer strand a worktree because of their own completion marker.** The `.agent-done` sentinel is consumed before worktree cleanup, but Git still reported the untracked file as ordinary authored work and the safety gate preserved the otherwise-clean checkout with a high-priority warning. Cleanup now ignores only that runtime marker: sentinel-only trees are removed normally, while any real source change still preserves the worktree and is named in the warning.
- **A failed CoS task now diagnoses itself and comes back on its own.** A failing task used to pile up a queue of approval-gated tasks — the crash filed one, the provider failure filed another, repeated orphaning filed a third — and then, even after the cause was fixed, the original task sat `blocked` until someone un-blocked it by hand (or the 14-day reaper quietly retired it as stale). Both halves of that are now automatic. Every failure-driven investigation is filed through one producer, so they share a single approval policy, a single storm counter, and a single dedup fingerprint: unattended by default, held for you in exactly the two cases where another unattended agent would just repeat itself — the same cause was already investigated in the last 24 hours, or failures are cascading rather than isolated — and the task says which of the two it is. Completing an investigation, whether an agent finished it or you fixed the cause and ticked it off, then automatically retries every task that failure was blocking. Bounded at two automatic retries per task, after which the task stays blocked and says the retry loop gave up rather than still showing the original failure. A task you terminated or paused, one parked awaiting your arbitration, and one waiting on a repository path you have to fix are never revived behind your back.
diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.js
index f188e6fd08..c1824ed35b 100644
--- a/server/services/pipeline/foundationJudge.js
+++ b/server/services/pipeline/foundationJudge.js
@@ -70,6 +70,7 @@ const WRITER_STAGE = 'pipeline-arc-overview';
// the weighted composite, the fix router, sanitize, and client rendering.
// Order is display order. Weights sum to 1.0 (asserted at module load).
export const FOUNDATION_DIMENSIONS = Object.freeze(['worldbuilding', 'character', 'structure', 'craft']);
+const MAX_STRUCTURE_CORRECTION_PASSES = 3;
export const FOUNDATION_WEIGHTS = Object.freeze({
worldbuilding: 0.4,
character: 0.3,
@@ -1693,25 +1694,33 @@ export async function applyFoundationFix(seriesId, dimension, {
// A foundation-directed structure rewrite can satisfy its broad judge
// while accidentally violating a narrower canon/location/timing rule.
- // Give the specialized arc verifier's concrete findings one bounded
- // corrective pass before the next foundation round. This keeps those
- // contradictions from consuming the foundation budget as if they were
- // deeper critique, while still bounding spend and rewrite blast radius.
- const correction = await resolveVerifyIssues(seriesId, {
- findings: blockers,
- ...resolveOptions,
- });
- if (correction?.applied !== false) {
+ // Keep correcting while the specialized verifier's blocker count shrinks.
+ // A single all-or-nothing pass threw away demonstrated 10 → 3 progress and
+ // forced the next run to rebuy all ten fixes. The bounded loop preserves
+ // the original rollback guarantee, but spends up to three focused passes
+ // when each one is moving monotonically toward a clean plan.
+ 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,
+ });
+ actions += 1;
+ if (correction?.applied === false) break;
verification = await verifyArc(seriesId, verifyOptions);
- blockers = Array.isArray(verification?.issues) ? verification.issues : [];
+ 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: 4 };
await restoreArcState(seriesId, snapshot);
return {
dimension,
applied: false,
- actions: correction?.applied === false ? 3 : 4,
+ 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
// bare count in prose, and the pause it raises reports dimension-level
diff --git a/server/services/pipeline/foundationJudge.test.js b/server/services/pipeline/foundationJudge.test.js
index 2e1c877f2b..d03998d5ed 100644
--- a/server/services/pipeline/foundationJudge.test.js
+++ b/server/services/pipeline/foundationJudge.test.js
@@ -1050,19 +1050,41 @@ describe('applyFoundationFix — dimension → owning-service routing table', ()
expect(r).toMatchObject({ dimension: 'structure', applied: true, actions: 4 });
});
+ it('keeps correcting a structure repair while its blocker count shrinks', async () => {
+ const many = Array.from({ length: 10 }, (_, idx) => ({
+ severity: 'medium', location: `Issue ${idx + 1}`, problem: `Blocker ${idx + 1}`,
+ }));
+ const three = many.slice(0, 3);
+ arcPlanner.verifyArc
+ .mockResolvedValueOnce({ issues: many })
+ .mockResolvedValueOnce({ issues: three })
+ .mockResolvedValueOnce({ issues: [] });
+
+ const r = await applyFoundationFix('ser-1', 'structure', {
+ finding: { gap: 'The issue plan contradicts the series spine.', fix: 'Reconcile it.' },
+ });
+
+ expect(arcPlanner.resolveVerifyIssues).toHaveBeenCalledTimes(3);
+ expect(arcPlanner.verifyArc).toHaveBeenCalledTimes(3);
+ expect(arcPlanner.restoreArcState).not.toHaveBeenCalled();
+ expect(r).toMatchObject({ dimension: 'structure', applied: true, actions: 6 });
+ });
+
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);
arcPlanner.verifyArc
.mockResolvedValueOnce({ issues: [{ severity: 'high', location: 'Issue 6', problem: 'First blocker' }] })
- .mockResolvedValueOnce({ issues: [{ severity: 'high', location: 'Issue 7', problem: 'Residual blocker' }] });
+ .mockResolvedValueOnce({ issues: [{ severity: 'high', location: 'Issue 7', problem: 'Residual blocker' }] })
+ .mockResolvedValueOnce({ issues: [{ severity: 'high', location: 'Issue 8', problem: 'Still blocked' }] })
+ .mockResolvedValueOnce({ issues: [{ severity: 'high', location: 'Issue 9', problem: 'Still blocked after cap' }] });
const r = await applyFoundationFix('ser-1', 'structure', {
finding: { gap: 'The midpoint lacks a costly reversal.', fix: 'Add a costly reversal.' },
});
expect(arcPlanner.restoreArcState).toHaveBeenCalledWith('ser-1', snapshot);
- expect(r).toMatchObject({ dimension: 'structure', applied: false, actions: 4 });
+ expect(r).toMatchObject({ dimension: 'structure', applied: false, actions: 8 });
expect(r.reason).toMatch(/reverted to the pre-repair plan/);
});