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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: give foundation structure repair an episode-edit rollback manifest (#4135)
[._.]/ Adam Eivy463ec4455eba
diff --git a/.changelog/next/fixed-issue-4135.md b/.changelog/next/fixed-issue-4135.mdnew file mode 100644index 0000000000..5f2eb5d83e--- /dev/null+++ b/.changelog/next/fixed-issue-4135.md@@ -0,0 +1 @@+- Foundation-gate structure repair now rolls back only the episode synopses its own arc resolves wrote, so a planning-synopsis edit that lands from elsewhere during the repair is no longer reverted with the rejected candidatediff --git a/server/services/pipeline/seriesAutopilot/arcMutationLedger.js b/server/services/pipeline/arcMutationLedger.jssimilarity index 74%rename from server/services/pipeline/seriesAutopilot/arcMutationLedger.jsrename to server/services/pipeline/arcMutationLedger.jsindex 2c98c6614f..4cdca927ae 100644--- a/server/services/pipeline/seriesAutopilot/arcMutationLedger.js+++ b/server/services/pipeline/arcMutationLedger.js@@ -1,5 +1,10 @@/**- * Rollback OWNERSHIP for the autopilot's arc gate.+ * Rollback OWNERSHIP for the gates that revert an arc round they just verified —+ * the autopilot's arc gate (`seriesAutopilot/childRuns.js`) and the foundation+ * gate's structure repair (`foundationJudge.js`). It sits beside them rather+ * than inside `seriesAutopilot/` because the autopilot already imports the+ * foundation judge; a shared helper one level down would point the dependency+ * back the way it came.** `restoreArcState` can put an episode's planning synopsis back, but nothing in* a snapshot says who wrote the difference: the rollback used to treat every@@ -15,12 +20,13 @@* AFTER its snapshot was taken. Everything else in the store keeps whatever it* has.*- * One ledger serves the whole gate — the round loop AND its per-finding- * isolation pass — because a checkpoint outlives the round that took it:+ * One ledger serves a whole gate — the arc gate's round loop AND its per-finding+ * isolation pass, or the structure repair's first resolve AND its bounded+ * correction passes — because a checkpoint outlives the round that took it:* rewinding to a `bestVerified` from three rounds back has to undo every- * resolve that landed since, including the isolation pass's. Two hand-rolled- * accumulators is how they drift while a reader assumes they haven't (the same- * argument `discardedEvidence.js` makes for findings evidence).+ * resolve that landed since. Two hand-rolled accumulators is how they drift+ * while a reader assumes they haven't (the same argument+ * `seriesAutopilot/discardedEvidence.js` makes for findings evidence).** Pure except for the ledger's own closed-over state: no I/O, no broadcast, and* no import of the arc planner — the caller derives the writes and hands themdiff --git a/server/services/pipeline/seriesAutopilot/arcMutationLedger.test.js b/server/services/pipeline/arcMutationLedger.test.jssimilarity index 100%rename from server/services/pipeline/seriesAutopilot/arcMutationLedger.test.jsrename to server/services/pipeline/arcMutationLedger.test.jsdiff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.jsindex a1a0842d20..32b5aca578 100644--- a/server/services/pipeline/arcPlanner/arcCore.js+++ b/server/services/pipeline/arcPlanner/arcCore.js@@ -1167,10 +1167,11 @@ export async function snapshotArcState(seriesId) {* expected to rewrite all three, so the false-revert exposure is small — but* it is the same reasoning, and closing it needs a manifest one level up.*- * Omit `episodeEdits` and every differing episode is restored. That is the right- * contract for `restoreFoundationState`, which verifies its own restore fidelity- * by diffing episodes wholesale; the foundation gate's structure-repair rollbacks- * merely inherit it, and are the next callers that should pass a manifest.+ * Omit `episodeEdits` and every differing episode is restored. The one caller+ * that still wants that is `restoreFoundationState`, which verifies its own+ * restore fidelity by diffing episodes wholesale. Both rollback loops that judge+ * a round by re-verifying it — the arc gate and the foundation gate's structure+ * repair — pass a manifest.** 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 keepdiff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.jsindex 876ba169f3..c2ad2727ed 100644--- a/server/services/pipeline/foundationJudge.js+++ b/server/services/pipeline/foundationJudge.js@@ -53,10 +53,12 @@ import { listIssues } from './issues.js';import { getSeriesCanon } from './seriesCanon.js';import {resolveVerifyIssues,+ resolvedEpisodeEdits,restoreArcState,snapshotArcState,verifyArc,} from './arcPlanner.js';+import { createArcMutationLedger } from './arcMutationLedger.js';const STAGE = 'pipeline-judge-foundation';const REPAIR_STAGE = 'pipeline-foundation-repair';@@ -1840,7 +1842,20 @@ export async function applyFoundationFix(seriesId, dimension, {problem: finding.gap || 'arc structure is below the foundation-quality bar',suggestion: finding.fix || '',}];- const snapshot = await snapshotArcState(seriesId);+ // Which episode synopses each rollback below may put back: the ones the+ // resolver reported writing after that checkpoint was taken, and nothing+ // else (see `createArcMutationLedger`). Without it, a repair that runs a+ // resolve plus up to MAX_STRUCTURE_CORRECTION_PASSES correct/verify pairs+ // reverted every episode `idea` that merely DIFFERED from its checkpoint —+ // including a write that landed from elsewhere across that whole window.+ // One ledger for the whole repair, because a checkpoint outlives the pass+ // that took it: rewinding to `bestVerified` has to undo every resolve since.+ const ledger = createArcMutationLedger();+ const takeSnapshot = async () => ledger.hold(await snapshotArcState(seriesId));+ const restoreTo = (checkpoint) => restoreArcState(seriesId, checkpoint, {+ episodeEdits: ledger.since(checkpoint),+ });+ const snapshot = await takeSnapshot();const structureRunIds = [];const resolveOptions = {providerDefault: providerOverride,@@ -1871,6 +1886,7 @@ export async function applyFoundationFix(seriesId, dimension, {const trackedResolve = async (resolveFindings) => {const before = structureRunIds.length;const result = await resolveVerifyIssues(seriesId, { findings: resolveFindings, ...resolveOptions });+ ledger.note(resolvedEpisodeEdits(result));return { result, runIds: structureRunIds.slice(before) };};const runGuardedStructureRepair = async () => {@@ -1891,7 +1907,7 @@ export async function applyFoundationFix(seriesId, dimension, {let rejectedRunIds = [];let bestVerified = {blockers,- snapshot: await snapshotArcState(seriesId),+ snapshot: await takeSnapshot(),runIds: [...retainedRunIds],};@@ -1930,7 +1946,7 @@ export async function applyFoundationFix(seriesId, dimension, {if (compareArcBlockers(blockers, bestVerified.blockers) <= 0) {bestVerified = {blockers,- snapshot: await snapshotArcState(seriesId),+ snapshot: await takeSnapshot(),runIds: [...retainedRunIds],};}@@ -1942,7 +1958,7 @@ export async function applyFoundationFix(seriesId, dimension, {// still decide whether it improved structure, and the normal full-arc// gate remains latched dirty so it must close the residual before beats.if (compareArcBlockers(bestVerified.blockers, initialBlockers) < 0) {- await restoreArcState(seriesId, bestVerified.snapshot);+ await restoreTo(bestVerified.snapshot);return {dimension,applied: true,@@ -1956,7 +1972,7 @@ export async function applyFoundationFix(seriesId, dimension, {};}- await restoreArcState(seriesId, snapshot);+ await restoreTo(snapshot);return {dimension,applied: false,@@ -1975,7 +1991,7 @@ export async function applyFoundationFix(seriesId, dimension, {// 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);+ await restoreTo(snapshot);throw err;});}diff --git a/server/services/pipeline/foundationJudge.structureRollback.test.js b/server/services/pipeline/foundationJudge.structureRollback.test.jsnew file mode 100644index 0000000000..d7de9ddf8b--- /dev/null+++ b/server/services/pipeline/foundationJudge.structureRollback.test.js@@ -0,0 +1,167 @@+/**+ * Foundation gate — structure repair rollback OWNERSHIP, against the real arc+ * store (#4135).+ *+ * `foundationJudge.test.js` stubs `restoreArcState`, so it can prove which+ * manifest each rollback is handed but not what the store looks like afterwards.+ * That is the half that mattered here: the repair's rollbacks used to revert+ * every episode `idea` that merely DIFFERED from the checkpoint, so a write that+ * landed from elsewhere across a resolve plus up to three correct/verify pairs+ * was reverted along with the candidate.+ *+ * These run `applyFoundationFix('…', 'structure')` with the REAL arc resolver,+ * snapshot and restore over an in-memory series/issue store (the setup+ * `arcPlanner.test.js` uses), stubbing only `verifyArc` — which doubles as the+ * place a foreign write lands mid-verification, exactly where the exposure is.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { mockNoPeerSync, mockNoPeers } from '../../lib/mockPathsDataRoot.js';++const fileStore = new Map();+let stageRunnerSpy;++vi.mock('../../lib/fileUtils.js', async (importActual) => {+ const actual = await importActual();+ return {+ ...actual,+ PATHS: { ...actual.PATHS, data: '/mock/data' },+ ensureDir: vi.fn().mockResolvedValue(undefined),+ tryReadFile: vi.fn().mockResolvedValue(null),+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),+ readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),+ };+});++let uuidCounter = 0;+vi.mock('crypto', async () => {+ const actual = await vi.importActual('crypto');+ return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };+});++vi.mock('../instances.js', () => mockNoPeers());+vi.mock('../sharing/peerSync.js', () => mockNoPeerSync());++vi.mock('../../lib/stageRunner.js', () => ({+ runStagedLLM: vi.fn((...args) => stageRunnerSpy(...args)),+ extractJson: (raw) => JSON.parse(raw),+ resolveStageContext: vi.fn(async () => ({ provider: { id: 'p' }, model: 'm', contextWindow: 1_000_000 })),+ resolveJudgeForStage: vi.fn(async () => ({ provider: { id: 'judge-x' }, model: 'jm' })),+}));++// Everything about the arc planner is REAL except the specialized verifier —+// the repair's control flow is driven by what it returns, and it is the one+// call that runs between a resolve and the rollback that judges it.+vi.mock('./arcPlanner.js', async (importActual) => ({+ ...(await importActual()),+ verifyArc: vi.fn(),+}));++const seriesSvc = await import('./series.js');+const issuesSvc = await import('./issues.js');+const seasonsSvc = await import('./seasons.js');+const arcPlanner = await import('./arcPlanner.js');+const { applyFoundationFix } = await import('./foundationJudge.js');++const REPAIR_FINDING = { gap: 'The issue plan contradicts the spine.', fix: 'Reconcile it.' };+const blockers = (n, prefix) => Array.from({ length: n }, (_, i) => ({+ severity: 'high', location: `Issue ${i + 1}`, problem: `${prefix} ${i + 1}`,+}));++// Two episodes under one volume, each with a planning synopsis the repair could+// rewrite. Only e1 is ever named by the resolver's response.+async function seedSeries() {+ const series = await seriesSvc.createSeries({+ name: 'Example Series',+ logline: 'A relay station goes dark.',+ premise: 'Long-form premise.',+ issueCountTarget: 2,+ });+ await seriesSvc.updateSeries(series.id, { arc: { logline: 'original logline', summary: 'original summary' } });+ const volume = await seasonsSvc.createSeason(series.id, { title: 'Volume 1', episodeCountTarget: 2 });+ const e1 = await issuesSvc.createIssue({ seriesId: series.id, seasonId: volume.id, title: 'Ep 1' });+ const e2 = await issuesSvc.createIssue({ seriesId: series.id, seasonId: volume.id, title: 'Ep 2' });+ await issuesSvc.updateStage(e1.id, 'idea', { input: 'e1 planning synopsis', status: 'empty' });+ await issuesSvc.updateStage(e2.id, 'idea', { input: 'e2 planning synopsis', status: 'empty' });+ return { series, volume, e1: await issuesSvc.getIssue(e1.id), e2: await issuesSvc.getIssue(e2.id) };+}++// A resolve response that rewrites the arc logline and e1's synopsis, and names+// nothing else. `synopsis` varies per pass so each pass's write is identifiable.+const resolveResponse = ({ volume, e1, logline, synopsis }) => ({+ content: {+ arc: { logline, summary: 'rewritten summary', themes: [], protagonistArc: '' },+ seasons: [],+ episodes: [{ seasonNumber: volume.number, episodeNumber: e1.number, synopsis }],+ notes: '',+ },+ runId: 'r', providerId: 'p', model: 'm',+});++const ideaInput = async (id) => (await issuesSvc.getIssue(id)).stages.idea.input;++describe('applyFoundationFix — structure repair restores only what it wrote', () => {+ beforeEach(() => {+ fileStore.clear();+ uuidCounter = 0;+ stageRunnerSpy = undefined;+ vi.mocked(arcPlanner.verifyArc).mockReset();+ });++ it('keeps a write that landed mid-verification when the whole repair is reverted', async () => {+ const { series, volume, e1, e2 } = await seedSeries();+ let pass = 0;+ stageRunnerSpy = vi.fn(async () => {+ pass += 1;+ return resolveResponse({ volume, e1, logline: `rewritten logline ${pass}`, synopsis: `resolver rewrote e1 (${pass})` });+ });+ // Never improves, so the repair spends its cap and reverts to the pre-repair+ // plan. The first verification is where the foreign write lands — from+ // outside this repair, on an episode the resolver never named.+ let verifies = 0;+ vi.mocked(arcPlanner.verifyArc).mockImplementation(async () => {+ verifies += 1;+ if (verifies === 1) await issuesSvc.updateStage(e2.id, 'idea', { input: 'edited elsewhere mid-verify' });+ return { issues: blockers(1, 'still blocked') };+ });++ const r = await applyFoundationFix(series.id, 'structure', { finding: REPAIR_FINDING });++ expect(r).toMatchObject({ dimension: 'structure', applied: false, reverted: true });+ // The repair's own writes are gone…+ expect((await seriesSvc.getSeries(series.id)).arc.logline).toBe('original logline');+ expect(await ideaInput(e1.id)).toBe('e1 planning synopsis');+ // …and the write it never made is still standing. This is the regression:+ // without a manifest the rollback reverted e2 to 'e2 planning synopsis'.+ expect(await ideaInput(e2.id)).toBe('edited elsewhere mid-verify');+ });++ it('undoes only the passes after its best checkpoint when it retains a partial improvement', async () => {+ const { series, volume, e1, e2 } = await seedSeries();+ let pass = 0;+ stageRunnerSpy = vi.fn(async () => {+ pass += 1;+ return resolveResponse({ volume, e1, logline: `rewritten logline ${pass}`, synopsis: `resolver rewrote e1 (${pass})` });+ });+ // 9 blockers → 1 (the checkpoint worth keeping) → 5 (regressed, rewound).+ // The foreign write lands during the LAST verification, i.e. after the kept+ // checkpoint was captured — so a manifest-free rewind would undo it.+ let verifies = 0;+ vi.mocked(arcPlanner.verifyArc).mockImplementation(async () => {+ verifies += 1;+ if (verifies === 1) return { issues: blockers(9, 'initial') };+ if (verifies === 2) return { issues: blockers(1, 'best') };+ await issuesSvc.updateStage(e2.id, 'idea', { input: 'edited elsewhere mid-verify' });+ return { issues: blockers(5, 'regressed') };+ });++ const r = await applyFoundationFix(series.id, 'structure', { finding: REPAIR_FINDING });++ expect(r).toMatchObject({ dimension: 'structure', applied: true, partial: true });+ // The rewind undid the third pass only, so the retained second pass's arc+ // and synopsis rewrites both survive…+ expect((await seriesSvc.getSeries(series.id)).arc.logline).toBe('rewritten logline 2');+ expect(await ideaInput(e1.id)).toBe('resolver rewrote e1 (2)');+ // …as does the write that was never this repair's to revert.+ expect(await ideaInput(e2.id)).toBe('edited elsewhere mid-verify');+ });+});diff --git a/server/services/pipeline/foundationJudge.test.js b/server/services/pipeline/foundationJudge.test.jsindex c7ef6785e0..4e27962198 100644--- a/server/services/pipeline/foundationJudge.test.js+++ b/server/services/pipeline/foundationJudge.test.js@@ -1207,18 +1207,19 @@ describe('applyFoundationFix — dimension → owning-service routing table', ().mockResolvedValueOnce({ issues: findings(9, 'initial') }).mockResolvedValueOnce({ issues: findings(1, 'best') }).mockResolvedValueOnce({ issues: findings(5, 'regressed') });+ const wrote = (issueId) => ({ issueId, idea: { input: `${issueId} synopsis`, output: '', status: 'empty' } });arcPlanner.resolveVerifyIssues.mockImplementationOnce(async (_id, options) => {options.onRunCreated('structure-broad');- return { applied: true };+ return { applied: true, episodesResolved: [wrote('iss-broad')] };}).mockImplementationOnce(async (_id, options) => {options.onRunCreated('structure-improved');- return { applied: true };+ return { applied: true, episodesResolved: [wrote('iss-improved')] };}).mockImplementationOnce(async (_id, options) => {options.onRunCreated('structure-regressed');- return { applied: true };+ return { applied: true, episodesResolved: [wrote('iss-regressed')] };});const r = await applyFoundationFix('ser-1', 'structure', {@@ -1226,8 +1227,14 @@ describe('applyFoundationFix — dimension → owning-service routing table', ()onRunCreated: vi.fn(),});- expect(arcPlanner.restoreArcState).toHaveBeenCalledWith('ser-1', bestCandidate);- expect(arcPlanner.restoreArcState).not.toHaveBeenCalledWith('ser-1', original);+ // The rewind to the best checkpoint may only undo what landed AFTER it: the+ // regressed pass's episode write. The two retained passes' writes are part+ // of the improvement being kept, and anything else in the store belongs to+ // whoever wrote it (#4135).+ expect(arcPlanner.restoreArcState).toHaveBeenCalledWith('ser-1', bestCandidate, {+ episodeEdits: [wrote('iss-regressed')],+ });+ expect(arcPlanner.restoreArcState).not.toHaveBeenCalledWith('ser-1', original, expect.anything());expect(r).toMatchObject({dimension: 'structure', applied: true, partial: true,acceptedRunIds: ['structure-broad', 'structure-improved'],@@ -1274,7 +1281,7 @@ describe('applyFoundationFix — dimension → owning-service routing table', ()onRunCreated: vi.fn(),});- expect(arcPlanner.restoreArcState).toHaveBeenCalledWith('ser-1', lowerCheckpoint);+ expect(arcPlanner.restoreArcState).toHaveBeenCalledWith('ser-1', lowerCheckpoint, { episodeEdits: [] });expect(r).toMatchObject({dimension: 'structure', applied: true, partial: true,acceptedRunIds: ['structure-broad', 'structure-lower-severity'],@@ -1287,7 +1294,15 @@ describe('applyFoundationFix — dimension → owning-service routing table', ()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);+ // A fresh object per call, as the real `snapshotArcState` returns — the+ // ledger keys checkpoints by identity, so a shared literal would make every+ // later checkpoint alias the pre-repair one.+ arcPlanner.snapshotArcState.mockImplementation(async () => structuredClone(snapshot));+ const wrote = (issueId) => ({ issueId, idea: { input: `${issueId} synopsis`, output: '', status: 'empty' } });+ arcPlanner.resolveVerifyIssues.mockImplementation(async () => ({+ applied: true,+ episodesResolved: [wrote(`iss-${arcPlanner.resolveVerifyIssues.mock.calls.length}`)],+ }));arcPlanner.verifyArc.mockResolvedValueOnce({ issues: [{ severity: 'high', location: 'Issue 6', problem: 'First blocker' }] }).mockResolvedValueOnce({ issues: [{ severity: 'high', location: 'Issue 7', problem: 'Residual blocker' }] })@@ -1298,21 +1313,28 @@ describe('applyFoundationFix — dimension → owning-service routing table', ()finding: { gap: 'The midpoint lacks a costly reversal.', fix: 'Add a costly reversal.' },});- expect(arcPlanner.restoreArcState).toHaveBeenCalledWith('ser-1', snapshot);+ // The full-revert manifest spans the whole exposure window: the first+ // resolve plus every correction pass, and nothing outside them (#4135).+ expect(arcPlanner.restoreArcState).toHaveBeenCalledWith('ser-1', snapshot, {+ episodeEdits: [wrote('iss-1'), wrote('iss-2'), wrote('iss-3'), wrote('iss-4')],+ });expect(r).toMatchObject({ dimension: 'structure', applied: false, actions: 8 });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: [] };+ const wrote = { issueId: 'iss-1', idea: { input: 'resolver rewrote iss-1', output: '', status: 'empty' } };arcPlanner.snapshotArcState.mockResolvedValue(snapshot);+ arcPlanner.resolveVerifyIssues.mockResolvedValue({ applied: true, episodesResolved: [wrote] });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);+ // Even the provider-failure bail-out undoes only the resolve's own writes.+ expect(arcPlanner.restoreArcState).toHaveBeenCalledWith('ser-1', snapshot, { episodeEdits: [wrote] });});it('routes character → judge-directed core-cast and character-arc repair', async () => {diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.jsindex fc5d91a80c..d7fa25c6fb 100644--- a/server/services/pipeline/seriesAutopilot.js+++ b/server/services/pipeline/seriesAutopilot.js@@ -78,7 +78,6 @@ export * from './seriesAutopilot/state.js';export * from './seriesAutopilot/config.js';export * from './seriesAutopilot/convergence.js';export * from './seriesAutopilot/discardedEvidence.js';-export * from './seriesAutopilot/arcMutationLedger.js';export * from './seriesAutopilot/stepResolver.js';export * from './seriesAutopilot/session.js';export * from './seriesAutopilot/diagnosisCore.js';diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.jsindex cc83b35040..a09a313867 100644--- a/server/services/pipeline/seriesAutopilot/childRuns.js+++ b/server/services/pipeline/seriesAutopilot/childRuns.js@@ -32,7 +32,7 @@ import {isIsolatedFixSafe,} from './convergence.js';import { createDiscardedBank } from './discardedEvidence.js';-import { createArcMutationLedger } from './arcMutationLedger.js';+import { createArcMutationLedger } from '../arcMutationLedger.js';import { broadcast, budgetPause, providerOverrideOpts, providerIdOpts, roleLlm, seasonPreserveOpts } from './session.js';import { recordModelOutcome } from './modelPerformance.js';import { requiredScriptStages, textReady } from './stepResolver.js';