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: guard foundation structure rewrites

[._.]/ Adam Eivy25b3ec0382a9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f08b41aa04..24cd71fcf9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -11,6 +11,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.
- **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 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/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.js
index 43a497e986..e65d607cf6 100644
--- a/server/services/pipeline/arcPlanner/arcCore.js
+++ b/server/services/pipeline/arcPlanner/arcCore.js
@@ -682,11 +682,11 @@ export async function snapshotArcState(seriesId) {
* damage because a lock flipped mid-run would strand the user with the damage.
* A locked `idea` stage IS skipped — the resolve pass never touched it.
*
- * Only the autopilot's convergence loop calls this: it is the one caller that
- * re-verifies after every resolve, so it is the only one that can tell a
- * regressive round from a good one without paying for an extra verify. The
- * manual `/arc/resolve` route and the foundation gate's structure fix run the
- * same resolver with no rollback, deliberately.
+ * Callers must re-verify after every resolve so they can distinguish a
+ * regressive round from a good one. The arc convergence loop uses this to keep
+ * its best verified checkpoint; foundation structure repair uses it to restore
+ * the pre-repair plan when its bounded verify/correct pass is still blocked.
+ * The manual `/arc/resolve` route remains an explicit unguarded user edit.
*/
export async function restoreArcState(seriesId, snapshot) {
if (!snapshot || snapshot.seriesId !== seriesId || !Array.isArray(snapshot.episodes)) {
diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.js
index 98acda5c3d..1399caaeb7 100644
--- a/server/services/pipeline/foundationJudge.js
+++ b/server/services/pipeline/foundationJudge.js
@@ -51,7 +51,12 @@ import { expandWorldTemplate, narrativeRepairTargets } from '../universeBuilderE
import { getSeries, updateSeries } from './series.js';
import { listIssues } from './issues.js';
import { getSeriesCanon } from './seriesCanon.js';
-import { resolveVerifyIssues } from './arcPlanner.js';
+import {
+ resolveVerifyIssues,
+ restoreArcState,
+ snapshotArcState,
+ verifyArc,
+} from './arcPlanner.js';
const STAGE = 'pipeline-judge-foundation';
const REPAIR_STAGE = 'pipeline-foundation-repair';
@@ -1466,6 +1471,9 @@ export async function applyFoundationFix(seriesId, dimension, {
providerOverride,
modelOverride,
effortOverride,
+ judgeProviderDefault,
+ judgeModelDefault,
+ judgeEffortDefault,
preserveDroppedSeasons = false,
onRunCreated,
onRunSettled,
@@ -1517,8 +1525,8 @@ export async function applyFoundationFix(seriesId, dimension, {
problem: finding.gap || 'arc structure is below the foundation-quality bar',
suggestion: finding.fix || '',
}];
- const r = await resolveVerifyIssues(seriesId, {
- findings,
+ const snapshot = await snapshotArcState(seriesId);
+ const resolveOptions = {
providerDefault: providerOverride,
modelDefault: modelOverride,
// The autopilot's unlock-for-run mode clears both `series.locked.arc`
@@ -1529,8 +1537,55 @@ export async function applyFoundationFix(seriesId, dimension, {
effortDefault: effortOverride,
onRunCreated,
onRunSettled,
+ };
+ const verifyOptions = {
+ providerDefault: judgeProviderDefault,
+ modelDefault: judgeModelDefault,
+ effortDefault: judgeEffortDefault,
+ onRunCreated,
+ onRunSettled,
+ };
+ const runGuardedStructureRepair = async () => {
+ const first = await resolveVerifyIssues(seriesId, { findings, ...resolveOptions });
+ 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 };
+
+ // 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) {
+ verification = await verifyArc(seriesId, verifyOptions);
+ blockers = Array.isArray(verification?.issues) ? verification.issues : [];
+ }
+ if (blockers.length === 0) return { dimension, applied: true, actions: 4 };
+
+ await restoreArcState(seriesId, snapshot);
+ return {
+ dimension,
+ applied: false,
+ actions: correction?.applied === false ? 3 : 4,
+ reason: `structure repair left ${blockers.length} arc-verification blocker(s); reverted to the pre-repair plan`,
+ };
+ };
+ // Any provider/parse failure after the first mutation must not strand the
+ // series in the unverified intermediate draft. Restore, then preserve the
+ // original error so the conductor pauses with the real provider diagnosis.
+ return runGuardedStructureRepair().catch(async (err) => {
+ await restoreArcState(seriesId, snapshot);
+ throw err;
});
- return { dimension, applied: r?.applied !== false };
}
return { dimension, applied: false, reason: `unknown dimension: ${dimension}` };
diff --git a/server/services/pipeline/foundationJudge.test.js b/server/services/pipeline/foundationJudge.test.js
index 0339520fc6..ab81eeb82b 100644
--- a/server/services/pipeline/foundationJudge.test.js
+++ b/server/services/pipeline/foundationJudge.test.js
@@ -51,6 +51,9 @@ vi.mock('./seriesCanon.js', async (importActual) => ({
vi.mock('./arcPlanner.js', async (importActual) => ({
...(await importActual()),
resolveVerifyIssues: vi.fn(async () => ({ applied: true })),
+ restoreArcState: vi.fn(async () => ({ restored: true })),
+ snapshotArcState: vi.fn(async () => ({ seriesId: 'ser-1', arc: {}, seasons: [], episodes: [] })),
+ verifyArc: vi.fn(async () => ({ issues: [] })),
}));
const fileUtils = await import('../../lib/fileUtils.js');
@@ -95,6 +98,10 @@ beforeEach(() => {
seriesSvc.getSeries.mockResolvedValue({ id: 'ser-1', name: 'S', logline: 'L', premise: 'P', universeId: 'uni-1' });
universeBuilder.getUniverse.mockResolvedValue(null);
issuesSvc.listIssues.mockResolvedValue([]);
+ arcPlanner.resolveVerifyIssues.mockResolvedValue({ applied: true });
+ arcPlanner.restoreArcState.mockResolvedValue({ restored: true });
+ arcPlanner.snapshotArcState.mockResolvedValue({ seriesId: 'ser-1', arc: {}, seasons: [], episodes: [] });
+ arcPlanner.verifyArc.mockResolvedValue({ issues: [] });
// Restore the default authored-scalar echo so a test that overrides it (blank
// /null values) doesn't leak into later order-dependent tests.
universeBuilderExpand.expandWorldTemplate.mockResolvedValue({ logline: 'L2', premise: 'P2', styleNotes: 'S2', influences: null });
@@ -947,7 +954,67 @@ describe('applyFoundationFix — dimension → owning-service routing table', ()
expect(arcPlanner.resolveVerifyIssues).toHaveBeenCalledWith('ser-1', expect.objectContaining({
findings: expect.arrayContaining([expect.objectContaining({ location: 'arc', problem: 'thin midpoint' })]),
}));
- expect(r).toMatchObject({ dimension: 'structure', applied: true });
+ expect(arcPlanner.snapshotArcState).toHaveBeenCalledWith('ser-1');
+ expect(arcPlanner.verifyArc).toHaveBeenCalledWith('ser-1', expect.any(Object));
+ expect(r).toMatchObject({ dimension: 'structure', applied: true, actions: 2 });
+ });
+
+ it('gives a structure repair one bounded arc-verifier correction pass', async () => {
+ const blocker = {
+ severity: 'high', location: 'Issue 6', problem: 'The crossing skips its destination consent.',
+ suggestion: 'Require the far operator to authorize the opening.',
+ };
+ arcPlanner.verifyArc
+ .mockResolvedValueOnce({ issues: [blocker] })
+ .mockResolvedValueOnce({ issues: [] });
+
+ const r = await applyFoundationFix('ser-1', 'structure', {
+ finding: { gap: 'The midpoint lacks a costly reversal.', fix: 'Add a costly reversal.' },
+ providerOverride: 'writer-provider',
+ modelOverride: 'writer-model',
+ effortOverride: 'max',
+ judgeProviderDefault: 'judge-provider',
+ judgeModelDefault: 'judge-model',
+ judgeEffortDefault: 'xhigh',
+ });
+
+ expect(arcPlanner.resolveVerifyIssues).toHaveBeenCalledTimes(2);
+ expect(arcPlanner.resolveVerifyIssues).toHaveBeenNthCalledWith(2, 'ser-1', expect.objectContaining({
+ findings: [blocker], providerDefault: 'writer-provider', modelDefault: 'writer-model', effortDefault: 'max',
+ }));
+ expect(arcPlanner.verifyArc).toHaveBeenNthCalledWith(1, 'ser-1', expect.objectContaining({
+ providerDefault: 'judge-provider', modelDefault: 'judge-model', effortDefault: 'xhigh',
+ }));
+ expect(arcPlanner.restoreArcState).not.toHaveBeenCalled();
+ expect(r).toMatchObject({ dimension: 'structure', applied: true, actions: 4 });
+ });
+
+ 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' }] });
+
+ 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.reason).toMatch(/reverted to the pre-repair plan/);
+ });
+
+ it('rolls a mutated structure repair back when verification errors', async () => {
+ const snapshot = { seriesId: 'ser-1', arc: { logline: 'Before' }, seasons: [], episodes: [] };
+ arcPlanner.snapshotArcState.mockResolvedValue(snapshot);
+ arcPlanner.verifyArc.mockRejectedValueOnce(new Error('judge provider unavailable'));
+
+ await expect(applyFoundationFix('ser-1', 'structure', {
+ finding: { gap: 'The midpoint lacks a costly reversal.', fix: 'Add a costly reversal.' },
+ })).rejects.toThrow('judge provider unavailable');
+
+ expect(arcPlanner.restoreArcState).toHaveBeenCalledWith('ser-1', snapshot);
});
it('routes character → judge-directed core-cast and character-arc repair', async () => {
diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.js
index a2b4b26444..62e6393661 100644
--- a/server/services/pipeline/seriesAutopilot/childRuns.js
+++ b/server/services/pipeline/seriesAutopilot/childRuns.js
@@ -430,6 +430,9 @@ export async function runFoundationGate(seriesId, record) {
finding: snap.dimensions?.[weak.dimension] || {},
providerOverride: creativeLlm.providerOverride,
modelOverride: creativeLlm.modelOverride,
+ judgeProviderDefault: judgeLlm.providerOverride,
+ judgeModelDefault: judgeLlm.modelOverride,
+ judgeEffortDefault: judgeLlm.effortOverride,
...seasonPreserveOpts(record),
effortOverride: creativeLlm.effortOverride,
onRunCreated: providerOverrideOpts(record).onRunCreated,
@@ -449,7 +452,7 @@ export async function runFoundationGate(seriesId, record) {
residual: residualFindings(snap.dimensions),
};
}
- await recordDomainUsage('cos', { actions: 1 });
+ await recordDomainUsage('cos', { actions: Math.max(1, fix?.actions || 1) });
broadcast(seriesId, {
type: 'foundation:fix', round, dimension: weak.dimension, applied: fix?.applied === true, reason: fix?.reason || null,
});