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: backfill legacy canon descriptions once on upgrade (#10019)

[._.]/ Adam Eivyd1e6084b214b
diff --git a/docs/API.md b/docs/API.md
index f8f7da7cc6..b773f84bb6 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -1011,3 +1011,16 @@ The server validates the graph before embedding or writing. Duplicate directed t
`relationships: []` means no edges. Omitting `relationships` preserves legacy all-pairs `related-to` links for batches of 2–25 entries. Explicit graphs work above that legacy batch limit. Supported kinds include `owned-by` (inverse: Owns) and `used-by` (inverse: Uses); using an object does not establish ownership. The caller must supply only grounded, accepted facts.
Ingredients, source links, optional `universeRef` bindings, and edges commit in one transaction. No existing records are backfilled. The relation wire shape and existing evidence fields are unchanged; unknown relation kinds continue to round-trip through peer sync. Structured extraction and relationship review are tracked separately under #7895.
+
+### Canon description repair
+
+`POST /api/universe-builder/:id/canon/backfill-descriptions` repairs legacy canon
+entries using their existing image prompts. It accepts no body and returns
+`{ universe, report }`, where `report` includes `filled`, `byKind`
+(`character`, `place`, `object`), `alreadyDescribed`, `missingPrompt`, and
+`skippedLocked`. It fills blank character `physicalDescription` or place/object
+`description` fields, trims and bounds prompt text, and preserves authored
+(including legacy character) descriptions and locked entries. No AI provider is
+called. The normal instance authentication gate applies; missing universes return
+404. Migration 422 applies this repair once across live universes on upgrade;
+this endpoint remains available for explicit agent or operator repairs afterward.
diff --git a/scripts/migrations/422-canon-description-backfill.js b/scripts/migrations/422-canon-description-backfill.js
new file mode 100644
index 0000000000..3fb74d945c
--- /dev/null
+++ b/scripts/migrations/422-canon-description-backfill.js
@@ -0,0 +1,29 @@
+/** Repair legacy prompt-only canon once, without generating new content or seeds. */
+export default {
+ async up() {
+ // Keep this service graph off migration/status imports until the write runs.
+ const { listUniverses } = await import('../../server/services/universeBuilder.js');
+ const { backfillCanonDescriptionsFromPrompts, DESC_FIELD } = await import('../../server/services/universeCanon.js');
+ const { BIBLE_KINDS, BIBLE_FIELD } = await import('../../server/lib/storyBible.js');
+ const universes = await listUniverses();
+ let updated = 0;
+ let filled = 0;
+ for (const universe of universes) {
+ const hasLegacyEntries = BIBLE_KINDS.some((kind) =>
+ (universe[BIBLE_FIELD[kind]] || []).some((entry) =>
+ entry.locked !== true
+ && !(entry[DESC_FIELD[kind]] || '').trim()
+ && !(kind === 'character' && (entry.description || '').trim())
+ && typeof entry.prompt === 'string' && entry.prompt.trim(),
+ ),
+ );
+ if (!hasLegacyEntries) continue;
+ // The service re-reads under the record write queue and rechecks locks.
+ const { report } = await backfillCanonDescriptionsFromPrompts(universe.id);
+ if (report.filled > 0) updated += 1;
+ filled += report.filled;
+ }
+ console.log(`📝 migration 422: canon description backfill updated=${updated} filled=${filled}`);
+ return { updated, filled };
+ },
+};
diff --git a/scripts/migrations/422-canon-description-backfill.test.js b/scripts/migrations/422-canon-description-backfill.test.js
new file mode 100644
index 0000000000..5c5011f133
--- /dev/null
+++ b/scripts/migrations/422-canon-description-backfill.test.js
@@ -0,0 +1,70 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdirSync, rmSync } from 'fs';
+import { mockNoPeers, mockNoPeerSync, mockPathsDataRoot } from '../../server/lib/mockPathsDataRoot.js';
+
+const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-canon-migration-' });
+afterAll(cleanup);
+vi.mock('../../server/lib/fileUtils.js', async () => makeProxy(await vi.importActual('../../server/lib/fileUtils.js')));
+vi.mock('../../server/services/instances.js', () => mockNoPeers());
+vi.mock('../../server/services/sharing/peerSync.js', () => mockNoPeerSync());
+const providerCall = vi.fn(() => { throw new Error('Migration must not call AI'); });
+vi.mock('../../server/services/bibleExtractor.js', () => ({ extractBible: providerCall }));
+vi.mock('../../server/services/stageRunner.js', () => ({ runStagedLLM: providerCall }));
+vi.mock('../../server/services/pipeline/refineHelpers.js', () => ({ runPromptRefine: providerCall }));
+
+const svc = await import('../../server/services/universeBuilder.js');
+const { default: migration } = await import('./422-canon-description-backfill.js');
+
+beforeEach(() => {
+ rmSync(tempRoot, { recursive: true, force: true });
+ mkdirSync(tempRoot, { recursive: true });
+ providerCall.mockClear();
+});
+
+const seed = async (name, canon) => {
+ const universe = await svc.createUniverse({ name, starterPrompt: 'Synthetic fixture' });
+ return svc.updateUniverse(universe.id, canon);
+};
+
+describe('migration 422 — persisted canon description repair', () => {
+ it('repairs all live universes while preserving locks, authored text, and tombstones; reruns write nothing', async () => {
+ const first = await seed('First fixture', {
+ characters: [
+ { name: 'Courier', physicalDescription: ' ', prompt: ' yellow coat ', locked: false },
+ { name: 'Authored', physicalDescription: 'blue coat', prompt: 'replace me', locked: false },
+ { name: 'Legacy', description: 'legacy coat', prompt: 'replace me', locked: false },
+ ],
+ places: [{ name: 'Locked', description: '', prompt: 'stone room', locked: true }],
+ objects: [{ name: 'Unknown', description: '', prompt: ' ', locked: false }],
+ });
+ const second = await seed('Second fixture', {
+ places: [{ name: 'Hall', description: '', prompt: 'stone hall', locked: false }],
+ objects: [{ name: 'Key', description: '', prompt: 'brass key', locked: false }],
+ });
+ const deleted = await seed('Deleted fixture', {
+ objects: [{ name: 'Discarded', description: '', prompt: 'unused prompt', locked: false }],
+ });
+ await svc.deleteUniverse(deleted.id);
+ const beforeDeleted = await svc.store().loadOneRaw(deleted.id);
+
+ await expect(migration.up()).resolves.toEqual({ updated: 2, filled: 3 });
+ const repaired = await svc.getUniverse(first.id);
+ expect(repaired.characters.map((c) => c.physicalDescription)).toEqual(['yellow coat', 'blue coat', 'legacy coat']);
+ expect(repaired.places[0].description).toBe('');
+ expect(repaired.objects[0].description).toBe('');
+ const other = await svc.getUniverse(second.id);
+ expect(other.places[0].description).toBe('stone hall');
+ expect(other.objects[0].description).toBe('brass key');
+ expect(await svc.store().loadOneRaw(deleted.id)).toEqual(beforeDeleted);
+ const persisted = await svc.store().listRaw();
+ await expect(migration.up()).resolves.toEqual({ updated: 0, filled: 0 });
+ expect(await svc.store().listRaw()).toEqual(persisted);
+ expect(providerCall).not.toHaveBeenCalled();
+ });
+
+ it('skips an install with no universes without creating records', async () => {
+ await expect(migration.up()).resolves.toEqual({ updated: 0, filled: 0 });
+ expect(await svc.store().listRaw()).toEqual([]);
+ expect(providerCall).not.toHaveBeenCalled();
+ });
+});