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
address review (codex): preserve canon imageRefs across stale PATCH + route entryRef key validation (#1395)
Adam Eivyb573d240ce38
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 588f6e03fc..d67830949a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -137,4 +137,4 @@- **[issue-1383] Chunked LLM editorial checks now carry cross-chapter continuity between chunks.** When a manuscript is too long for the provider's context window, the manuscript-consuming LLM checks review it chunk-by-chunk and merge findings first-wins (#1340). But a per-chunk view is blind to problems that span chapters: `style.conformance` couldn't see that chapter 1 established past-tense when judging chapter 3, and `objects.unmotivated-interaction` could flag a "missing setup" for an object that an earlier chunk already accounted for. Those two checks now opt into a rolling **prior-findings digest** (`editorialPriorFindingsDigest`) — each chunk after the first is prefixed with a capped, first-wins summary of the findings gathered so far, riding INSIDE the manuscript var so no stage-prompt template changes (mirrors the completeness pass's `priorFindingsDigest`). The digest instructs the model not to repeat prior findings and to flag only new problems plus cross-chapter continuity issues the earlier findings reveal; exact repeats are still deduped by `editorialFindingKey`. The chunk planner reserves `EDITORIAL_PRIOR_DIGEST_TOKENS` so prepending the digest can't overrun the window, and `prose.info-dumping` deliberately stays per-chunk (its problems are localized). The shared chunk loop is factored into one `runChunkedManuscriptCheck` helper used by both the staged and custom-check paths. (`server/lib/editorial/checkRegistry.js`, #1383)-- **[issue-1395] Universe canon section-local renders now persist durably even if the page unmounts mid-render.** A single reference/clean-plate render fired from the Universe canon section round-tripped a client `updateUniverse` PATCH to append the new filename onto the entry's `imageRefs[]` — so a render that completed *after* the user navigated away, refreshed, or switched universes silently lost its attachment (the image reached the media library, but no `imageRefs[]` row was ever written). These renders now carry the same durable `universeRun.entryRef` job tag the batch path uses, so the server-side completion hook (`universeBuilderCollectionHook`) appends `imageRefs[]` independent of any mounted client — converging the section-local and batch surfaces onto one durable path (mirrors the catalog hook from #1359). The hook fires the `appendEntryImageRef` even when the render carries no collection (and the route preserves `entryRef` through a gallery-collection provisioning failure, so the imageRefs append never depends on the collection existing). The client `handleRefCompleted` keeps its optimistic/immediate-refresh role (no PATCH); the hook is idempotent against it (`mapAppendImageRef` dedupes by filename). (`server/services/universeBuilderCollectionHook.js`, `server/routes/imageGen.js`, `client/src/components/universe/UniverseCanonSection.jsx`, #1395)+- **[issue-1395] Universe canon section-local renders now persist durably even if the page unmounts mid-render.** A single reference/clean-plate render fired from the Universe canon section round-tripped a client `updateUniverse` PATCH to append the new filename onto the entry's `imageRefs[]` — so a render that completed *after* the user navigated away, refreshed, or switched universes silently lost its attachment (the image reached the media library, but no `imageRefs[]` row was ever written). These renders now carry the same durable `universeRun.entryRef` job tag the batch path uses, so the server-side completion hook (`universeBuilderCollectionHook`) appends `imageRefs[]` independent of any mounted client — converging the section-local and batch surfaces onto one durable path (mirrors the catalog hook from #1359). The hook fires the `appendEntryImageRef` even when the render carries no collection (and the route preserves `entryRef` through a gallery-collection provisioning failure, so the imageRefs append never depends on the collection existing). The client `handleRefCompleted` keeps its optimistic/immediate-refresh role (no PATCH); the hook is idempotent against it (`mapAppendImageRef` dedupes by filename). Backbone the durable path depends on: `updateUniverse` now preserves canon-entry `imageRefs[]` per-id across a stale whole-array PATCH (an inline canon edit/add/lock that round-trips a snapshot loaded before the render landed no longer clobbers the freshly-appended filename — the same guard variations and composite sheets already had); `purgeImageRefFromAllUniverses` switches to the trusted mutator form so its intentional ref-removal isn't undone by that guard; and the route rejects an `entryRef` missing its locating key (canon→`kindKey`, variation→`categoryKey`) instead of silently no-opping the append. (`server/services/universeBuilderCollectionHook.js`, `server/routes/imageGen.js`, `server/services/universeBuilder.js`, `server/services/universeCanon.js`, `client/src/components/universe/UniverseCanonSection.jsx`, #1395)diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex a71a3be1c8..1c7e79e8a3 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -125,7 +125,12 @@ const generateSchema = z.object({kindKey: z.string().min(1).max(64).optional(),categoryKey: z.string().min(1).max(64).optional(),id: z.string().min(1).max(200),- }).optional(),+ }).refine(+ // Each kind needs its locating key, else appendEntryImageRef silently+ // no-ops: canon→kindKey, variation→categoryKey (sheet needs neither).+ (r) => (r.kind === 'canon' ? !!r.kindKey : r.kind === 'variation' ? !!r.categoryKey : true),+ { message: 'entryRef requires its locating key (canon→kindKey, variation→categoryKey)' },+ ).optional(),}).optional(),// Durable catalog attach (#1359). When present, the mediaJobQueue completion// hook (catalogImageAttachHook) files the finished render onto this catalogdiff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex 640a71ccae..b261302d47 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -395,6 +395,26 @@ describe('Image Gen Routes', () => {}));});+ it('rejects a canon entryRef missing its kindKey (would no-op the append)', async () => {+ // Zod validation rejects before prepareGenerateParams reads settings, so+ // no getSettings/enqueueJob mock is primed here — priming an unconsumed+ // mockResolvedValueOnce would leak into the next test (clearAllMocks does+ // not drain the once-queue).+ const response = await request(app)+ .post('/api/image-gen/generate')+ .send({+ prompt: 'a confident pyromancer',+ universeRun: {+ universeId: 'uni-5',+ universeName: 'CanonVerse',+ entryRef: { kind: 'canon', id: 'char-ash' }, // no kindKey+ },+ });++ expect(response.status).toBe(400);+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();+ });+it('preserves the entryRef even when collection provisioning fails', async () => {getSettings.mockResolvedValueOnce({ imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3' } } });mediaJobQueue.enqueueJob.mockReturnValueOnce({ jobId: 'queued-section-2', position: 1, status: 'queued' });diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.jsindex 1606c7d29c..2376634e10 100644--- a/server/services/universeBuilder.js+++ b/server/services/universeBuilder.js@@ -1220,6 +1220,23 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {scalarPatch.compositeSheets = preserveImageRefsById(scalarPatch.compositeSheets, cur.compositeSheets);}+ // Server-stamped render history on canon entries (characters / places /+ // objects). Like the variations + composite-sheet guards above, the+ // collection hook appends to these `imageRefs[]` via the mutator form of+ // updateUniverse (which bypasses this guard). A literal whole-array PATCH+ // that round-trips a canon list the client loaded before a section-local+ // or batch render completed (#1395) would otherwise clobber the freshly-+ // appended filename. Preserve cur's imageRefs per-id when the patch is+ // 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']) {+ if (Array.isArray(scalarPatch[canonKey]) && Array.isArray(cur[canonKey])) {+ scalarPatch[canonKey] = preserveImageRefsById(scalarPatch[canonKey], cur[canonKey]);+ }+ }+ }+const mergedRecord = sanitizeTemplate({...cur,...scalarPatch,diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.jsindex d153a054cc..2bfe2caed7 100644--- a/server/services/universeBuilder.test.js+++ b/server/services/universeBuilder.test.js@@ -532,6 +532,33 @@ describe("universeBuilder service", () => {expect(charAfterStamp?.referenceSheetImageRef).toBe("sheet-C.png");});+ it("updateUniverse preserves canon entry imageRefs across a stale whole-array PATCH (#1395)", async () => {+ // The collection hook appends section-local / batch renders onto a canon+ // entry's imageRefs[] via appendEntryImageRef (mutator form). A literal+ // whole-array PATCH (inline canon edit / add / lock) that round-trips a+ // character list the client loaded BEFORE the render landed must not+ // clobber the freshly-appended filename.+ const w = await seedWorld({+ characters: [{ id: "c-ref", name: "Ref", physicalDescription: "a face" }],+ });+ // Durable append — the hook's path (mutator form, bypasses preservation).+ await svc.appendEntryImageRef(w.id, { kind: "canon", kindKey: "characters", id: "c-ref" }, "render-1.png");++ // Stale client PATCH: round-trips the character WITHOUT the new ref.+ const afterStale = await svc.updateUniverse(w.id, {+ characters: [{ id: "c-ref", name: "Ref (renamed)", physicalDescription: "a face", imageRefs: [] }],+ });+ const refChar = afterStale.characters.find((c) => c.id === "c-ref");+ expect(refChar?.imageRefs).toEqual(["render-1.png"]); // preserved+ expect(refChar?.name).toBe("Ref (renamed)"); // other edits still apply++ // Mutator path stays trusted — a subsequent append lands normally.+ await svc.appendEntryImageRef(w.id, { kind: "canon", kindKey: "characters", id: "c-ref" }, "render-2.png");+ const afterSecond = await svc.getUniverse(w.id);+ const refChar2 = afterSecond.characters.find((c) => c.id === "c-ref");+ expect(refChar2?.imageRefs).toEqual(["render-1.png", "render-2.png"]);+ });+it("updateUniverse preservation skips when cur's referenceSheetImageRef no longer resolves on disk", async () => {// GET /:id runs pruneStaleReferenceSheets, returning null when the// underlying file is gone. Client PATCHes carry the pruned null. Thediff --git a/server/services/universeCanon.js b/server/services/universeCanon.jsindex efa4501557..9b87f24809 100644--- a/server/services/universeCanon.js+++ b/server/services/universeCanon.js@@ -597,22 +597,32 @@ export async function purgeImageRefFromAllUniverses(filename) {const universes = await listUniverses();let removed = 0;for (const universe of universes) {- let touched = false;- const patch = {};- for (const key of BIBLE_KEYS) {- const list = Array.isArray(universe[key]) ? universe[key] : null;- if (!list) continue;- const nextList = list.map((entry) => {- const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : null;- if (!refs || !refs.includes(filename)) return entry;- const trimmed = refs.filter((f) => f !== filename);- removed += refs.length - trimmed.length;- touched = true;- return { ...entry, imageRefs: trimmed };- });- if (touched) patch[key] = nextList;- }- if (touched) await updateUniverse(universe.id, patch);+ let perUniverse = 0;+ // Mutator form (reads `cur`, returns the trimmed arrays) so this intentional+ // removal bypasses updateUniverse's imageRefs-preservation guard (#1395): a+ // literal PATCH carrying FEWER refs looks "stale" to that guard and would be+ // restored, undoing the purge. Reset the counter at the top so a retried+ // mutator can't double-count. Returns null (no-op) when nothing matches.+ await updateUniverse(universe.id, (cur) => {+ perUniverse = 0;+ const patch = {};+ for (const key of BIBLE_KEYS) {+ const list = Array.isArray(cur[key]) ? cur[key] : null;+ if (!list) continue;+ let keyTouched = false;+ const nextList = list.map((entry) => {+ const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : null;+ if (!refs || !refs.includes(filename)) return entry;+ const trimmed = refs.filter((f) => f !== filename);+ perUniverse += refs.length - trimmed.length;+ keyTouched = true;+ return { ...entry, imageRefs: trimmed };+ });+ if (keyTouched) patch[key] = nextList;+ }+ return Object.keys(patch).length > 0 ? patch : null;+ });+ removed += perUniverse;}return { removed };}