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: strip write-path-owned fields for every canon array in foundation rollback checks (#3778)
[._.]/ Adam Eivy0d44e769fac2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6034ca50f2..77f8b719d8 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -40,3 +40,5 @@- **A foundation repair that was correctly rolled back no longer reports the rollback as corrupted.** When Series Autopilot reverted a character repair that failed to improve its target dimension, the pause said "checkpoint verification failed after rollback: restored foundation fields did not match the checkpoint" — implying the cast had been left in a half-repaired state. Nothing was actually wrong: undoing a repair is itself a content change, so the universe write path re-stamped `updatedAt` on every canon entry it restored (it has to — that timestamp is the clock the canon→catalog projection uses to carry the revert), and the verification compared those server-owned stamps byte-for-byte along with the authored prose. Every faithful character rollback therefore failed its own check. The comparison now ignores exactly the per-entry fields the write path owns and deliberately does not revert — the LWW timestamp, plus the reference-sheet and render pointers, which are preserved from the live record so a render that finished mid-repair isn't thrown away by the undo — while still comparing all authored content byte-for-byte. When a restore genuinely doesn't come back, the pause now names the fields that failed instead of stating only that something didn't match.- **Arc verification now banks the fixes that worked instead of discarding a whole round for one bad edit.** The gate resolved its blocking findings as a single rewrite: every finding went to the resolver in one call, and the next check kept or reverted that candidate as a unit. So a rewrite that cleanly closed two problems and broke a third was thrown away in full, and the gate ended up holding nothing — on the observed run it reached a verified best of 2 blockers, watched the next pass come back with 5 and the corrective retry with 3, correctly preserved the 2-blocker draft both times, and then paused for review with seven of its twelve permitted rounds unspent. The rollback guard is unchanged and still refuses any candidate that grows the blocking set or worsens its severity mix. What is new is what happens after the corrective retry is spent: when the residual has more than one finding, the gate now takes it apart and tries the findings one at a time from the best verified plan. Each attempt is its own transaction — snapshot, resolve that one finding, re-run the same verification the gate uses, and keep the edit only when the finding it targeted is actually gone and what it left behind is not a regression by the same count-then-severity rule the whole-round guard applies — so which trades survive no longer depends on which tier judged them. Anything else is restored on the spot, so a poisoned finding now costs only its own attempt instead of its neighbours' repairs, and the surviving fixes are re-verified together before the gate is allowed to clear. Closure is judged the same way the rollback guard judges identity, so a verifier that merely restates a standing problem in fresh words can't pass as a fix. The pass is bounded by a spend budget counted in provider calls — so a wide series, whose every check costs one call per volume, gets fewer attempts rather than a proportionally larger bill — skipped when only one finding is left (that is the corrective retry again, at twice the price), never run without a round left to verify what it kept, capped per run by `maxArcIsolationAttempts`, and switched off entirely by that or by `maxArcResolveRetries: 0`. The dry-run plan now includes its worst case, so the estimate you approve a run from still bounds the gate. The live status line reports each isolated attempt and whether it was kept.++- **The rollback comparison now ignores write-path-owned fields on every kind of canon entry, not just characters.** The fix that stopped a faithful foundation rollback from reporting itself as a corrupted checkpoint stripped the server-owned per-entry fields (the LWW timestamp and the sheet/render pointers) from `characters` only, which happened to be the sole canon array the foundation snapshot tracked. The universe write path stamps those fields across characters, places, and objects alike, so extending the snapshot to worldbuilding canon would have quietly brought the same bogus "restored foundation fields did not match the checkpoint" pause back with no test to catch it. The comparison now walks every canon array the story bible defines, and the universe write path's three separate hardcoded copies of that list were collapsed onto the shared one so a future canon kind flows through instead of being silently skipped by the timestamp stamper.diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.jsindex 6f0e6f4757..52a42b9cb0 100644--- a/server/services/pipeline/foundationJudge.js+++ b/server/services/pipeline/foundationJudge.js@@ -43,7 +43,7 @@ import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextBimport { getStage } from '../promptService.js';import { composeStyleNotes, sanitizeStyleGuide, STYLE_GUIDE_LIMITS } from '../../lib/styleGuide.js';import { renderCharacterArcsForPrompt, sanitizeCharacterArcList } from '../../lib/seriesCharacterArc.js';-import { BIBLE_SOURCE, sanitizeCharacter } from '../../lib/storyBible.js';+import { BIBLE_KEYS, BIBLE_SOURCE, sanitizeCharacter } from '../../lib/storyBible.js';import { renderEntitiesSummary } from '../../lib/universePromptRenderers.js';import { getUniverse, updateUniverse } from '../universeBuilder.js';import { isBlankString, isBlankArray } from '../universeCharacterExpand.js';@@ -1490,10 +1490,18 @@ const comparableCanonEntry = (entry) => {return rest;};+// Walk EVERY canon array the bible defines, not just `characters`. The write+// path (`stampChangedCanonEntries` in universeBuilder/crud.js) stamps+// `updatedAt` across all of `BIBLE_KEYS`, so the moment a canon array beyond+// `characters` joins FOUNDATION_UNIVERSE_SNAPSHOT_FIELDS the same false+// "restored foundation fields did not match the checkpoint" pause would return.const comparableUniverseFields = (universe) => {if (!universe || typeof universe !== 'object') return universe ?? null;- if (!Array.isArray(universe.characters)) return universe;- return { ...universe, characters: universe.characters.map(comparableCanonEntry) };+ const comparable = { ...universe };+ for (const key of BIBLE_KEYS) {+ if (Array.isArray(comparable[key])) comparable[key] = comparable[key].map(comparableCanonEntry);+ }+ return comparable;};// `undefined` (field absent from the record) is NOT the same as `null` — the@@ -1740,5 +1748,7 @@ export const __testing = {CHARACTER_FOUNDATION_BATCH_SIZE,FRAMEWORK_STRING_FIELDS,mismatchedFoundationFields,+ comparableUniverseFields,CANON_WRITE_PATH_OWNED_FIELDS,+ FOUNDATION_UNIVERSE_SNAPSHOT_FIELDS,};diff --git a/server/services/pipeline/foundationJudge.rollback.test.js b/server/services/pipeline/foundationJudge.rollback.test.jsindex c389654c62..41831ad8b3 100644--- a/server/services/pipeline/foundationJudge.rollback.test.js+++ b/server/services/pipeline/foundationJudge.rollback.test.js@@ -68,6 +68,9 @@ vi.mock('./series.js', async (importActual) => ({}),}));+// Imported after the mocks (which are hoisted above the TEST_DATA_ROOT literal)+// so the mocked `PATHS.data` is in place before the store modules read it.+const { BIBLE_KEYS } = await import('../../lib/storyBible.js');const { createUniverse, getUniverse, updateUniverse, PREMISE_MAX } = await import('../universeBuilder.js');const {snapshotFoundationState,@@ -97,6 +100,7 @@ async function seedFoundation() {styleNotes: 'style before',influences: { embrace: ['Example'], avoid: [] },characters: CAST,+ places: [{ name: 'Example Gatehouse', description: 'a shuttered relay station', imageRefs: ['gate-1.png'] }],});seriesState = {id: 'ser-1',@@ -200,6 +204,53 @@ describe('restoreFoundationState — against the real universe write path', () =.toEqual(['universe.characters']);});+ it('strips the write-path-owned fields from EVERY canon array, not just characters', () => {+ const { comparableUniverseFields } = __testing;+ const owned = {+ updatedAt: '2026-01-01T00:00:00.000Z',+ referenceSheetImageRef: 'a.png',+ referenceSheets: { front: 'f.png' },+ imageRefs: ['a.png'],+ };+ // No `characters` key at all — the old `characters`-only guard bailed out+ // here and returned every other canon array with its owned fields intact.+ const universe = {+ logline: 'L',+ ...Object.fromEntries(BIBLE_KEYS+ .filter((key) => key !== 'characters')+ .map((key) => [key, [{ id: `${key}-1`, name: `Example ${key}`, ...owned }]])),+ };++ const comparable = comparableUniverseFields(universe);++ expect(comparable.logline).toBe('L');+ for (const key of BIBLE_KEYS.filter((k) => k !== 'characters')) {+ expect(Object.keys(comparable[key][0]).sort()).toEqual(['id', 'name']);+ }+ });++ it('tolerates the write path re-stamping a NON-character canon entry', async () => {+ const universe = await seedFoundation();+ const before = await getUniverse(universe.id);++ // A worldbuilding repair rewriting an existing place — the same shape of+ // edit a character repair makes, on the canon array the character-only+ // stripping used to miss.+ await updateUniverse(universe.id, (latest) => ({+ places: latest.places.map((p) => ({ ...p, description: `${p.description} (rewritten by the repair)` })),+ }));+ // ...and the faithful undo, which is itself a content change.+ await updateUniverse(universe.id, () => ({ places: structuredClone(before.places) }));+ const after = await getUniverse(universe.id);++ const { comparableUniverseFields } = __testing;+ // Authored content came back byte-for-byte once the owned fields are gone.+ expect(comparableUniverseFields(after).places).toEqual(comparableUniverseFields(before).places);+ // ...and the reason a raw comparison would have failed: the LWW clock moved.+ expect(Date.parse(after.places[0].updatedAt))+ .toBeGreaterThan(Date.parse(before.places[0].updatedAt));+ });+it('distinguishes an absent checkpoint field from a null one', () => {const { mismatchedFoundationFields } = __testing;const base = {diff --git a/server/services/universeBuilder/crud.js b/server/services/universeBuilder/crud.jsindex 2e85dff80a..dd404e8e41 100644--- a/server/services/universeBuilder/crud.js+++ b/server/services/universeBuilder/crud.js@@ -13,7 +13,7 @@import { randomUUID } from 'crypto';import { PATHS, ensureDir, resolveImageRef } from '../../lib/fileUtils.js';import {- pruneStaleReferenceSheets, mergePreservedSheetPointers, isStr, trimTo,+ BIBLE_KEYS, pruneStaleReferenceSheets, mergePreservedSheetPointers, isStr, trimTo,} from '../../lib/storyBible.js';import { store } from './storeFacade.js';import {@@ -304,9 +304,6 @@ export async function insertUniverseWithId(input = {}) {return next;}-// Canon array keys carrying bible entries that project to catalog rows.-const CANON_ARRAY_KEYS = ['characters', 'places', 'objects'];-// Compare two canon entries for CONTENT equality, ignoring `updatedAt` (the// field we're deciding whether to bump). A cheap stable-stringify is enough —// entries are small plain objects and a false "changed" only costs a redundant@@ -324,7 +321,7 @@ function canonEntryContentEqual(a, b) {// their old timestamp so this never manufactures projection churn.function stampChangedCanonEntries(prev, next) {const nowMs = Date.now();- for (const key of CANON_ARRAY_KEYS) {+ for (const key of BIBLE_KEYS) {const nextList = Array.isArray(next[key]) ? next[key] : null;if (!nextList) continue;const prevById = new Map(@@ -452,7 +449,7 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {'imageMode', 'imageModelId',// Canon entity arrays — patched wholesale (the sanitizer reruns// sanitizeBibleList so per-entry shape is enforced on every save).- 'characters', 'places', 'objects',+ ...BIBLE_KEYS,// Share-bucket origin metadata (importer sets it; user clears via wholesale null).'origin',// Local-only "don't sync" marker — see sanitizeTemplate. The safety@@ -549,7 +546,7 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {// stale. (The characters array was already remapped above for sheet// pointers — this preserves a different field and composes cleanly.)if (!isMutator) {- for (const canonKey of ['characters', 'places', 'objects']) {+ for (const canonKey of BIBLE_KEYS) {if (Array.isArray(scalarPatch[canonKey]) && Array.isArray(cur[canonKey])) {scalarPatch[canonKey] = preserveImageRefsById(scalarPatch[canonKey], cur[canonKey]);}