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
Catalog ref resolver + dangling-ref integrity (#1018)
Adam Eivy3b9366d09da9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2f901c6002..3b23164759 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -24,6 +24,7 @@- **Universe Builder now stores universes in PostgreSQL** — your universes (canon bibles, categories, composite sheets, locks, influences, and the per-universe render-run history) moved out of the per-record `data/universes/{id}/index.json` files into dedicated `universes` and `universe_runs` tables, one row per universe. Existing installs are migrated automatically and losslessly on first boot — the legacy `data/universes/` directory is renamed aside (`data/universes.imported`) as a one-release recovery source. Nothing changes in how you create, edit, delete, render, or sync universes: the Universe Builder UI and the cross-machine federation wire format are unchanged (no schema-version bump — the sync payload is storage-independent, so a machine on this version syncs universes cleanly with a peer still on the old file storage). This is the first implementation slice (#1014) of the Create relational-schema migration designed in #999. Universes still persist to the per-record file store under the `MEMORY_BACKEND=file` dev/test escape hatch.- **Pipeline series & issues now store in PostgreSQL** — your comic/TV series and their issues (the 8-stage production pipeline state: idea, prose, comic script, teleplay, comic pages, storyboards, episode video, audio) moved out of the per-record `data/pipeline-series/{id}/index.json` and `data/pipeline-issues/{id}/index.json` files into dedicated `pipeline_series` and `pipeline_issues` tables, one row per record. The hot relationships are promoted to indexed columns — `pipeline_issues (series_id, number)` directly serves the issue-renumber pass (the most common cross-record pipeline query), and `pipeline_series (universe_id)` serves the universe delete-guard and "series in this universe" lists. Existing installs are migrated automatically and losslessly on first boot. Each issue's full stage map (including its `lastRunId` transcript pointers) stays in the row's `data` payload, and the "Finish the draft" manuscript-review sibling document stays a file alongside the series — only the series/issue records themselves moved. Nothing changes in how you create, edit, delete, renumber, run, or sync the pipeline: the UI and the cross-machine federation wire format are unchanged (no schema-version bump — the sync payload is storage-independent, so a machine on this version syncs the pipeline cleanly with a peer still on the old file storage). This is the second implementation slice (#1015) of the Create relational-schema migration designed in #999, building on the Universes slice (#1014). The pipeline still persists to the per-record file store under the `MEMORY_BACKEND=file` dev/test escape hatch.- **Story Builder sessions now store in PostgreSQL** — the guided Story Builder's session records (the per-step lock/integrity state, the cross-machine staleness baseline, your current step, and the saved provider/model picker choice) moved out of the per-record `data/story-builder/{id}/index.json` files into a dedicated `story_builder_sessions` table, one row per session. The two links every session carries — its universe and its series — are promoted to indexed columns, and the OPT-IN cross-machine resume flag (`sync`) is promoted too so the federation snapshot loop can find the sync-enabled sessions without deserializing every session's body. Existing installs are migrated automatically and losslessly on first boot — the legacy `data/story-builder/` directory is renamed aside (`data/story-builder.imported`) as a one-release recovery source. Nothing changes in how you create, run, lock, reconcile, or sync sessions: the Story Builder UI and the opt-in cross-machine resume wire format are unchanged (no schema-version bump — the sync payload is storage-independent, so a machine on this version syncs sessions cleanly with a peer still on the old file storage). This is the third implementation slice (#1016) of the Create relational-schema migration designed in #999, building on the Universes (#1014) and Pipeline (#1015) slices. Sessions still persist to the per-record file store under the `MEMORY_BACKEND=file` dev/test escape hatch.+- **Catalog references now resolve against their database targets, with a dangling-ref integrity report** — a catalog ingredient records which universe / series / issue / work / Creative-Director project consumes it (the "Appears in" panel) by a string `(kind, id)` reference. Now that all five of those target kinds live in PostgreSQL (#1014–#1017, #997), a new resolver can answer "does this reference still point at a live record?" and a new integrity surface (`GET /api/catalog/refs/dangling`) lists every live reference whose target no longer resolves — deleted, or a federated reference whose target hasn't synced in yet — mirroring the existing missing-media check. References remain a plain string match with **no database foreign key** (by design): a peer can legitimately sync a reference before its target arrives, and a hard constraint would make that sync fail — so a dangling reference is reported, never an error, and resolves itself once the target lands. Read-only and local; nothing touches the cross-machine wire and there's no schema change (the existing target index already makes the lookup cheap). This is the fifth and final implementation slice (#1018) of the Create relational-schema migration designed in #999.- **Writers Room metadata now stores in PostgreSQL** — the Writers Room library's metadata — folders, work manifests, draft-version history, and writing-sprint exercises — moved out of the bespoke `data/writers-room/` file layout (`folders.json`, `exercises.json`, per-work `manifest.json`) into dedicated `writers_room_folders`, `writers_room_works`, `writers_room_draft_versions`, and `writers_room_exercises` tables. Each work's draft *versions* are decomposed into their own rows (one per version) so the library and future staleness analysis can query word counts, hashes, and lineage directly, while the **draft prose bodies stay on disk** as `.md` files (`data/writers-room/works/<id>/drafts/<draftId>.md`) — only their metadata is indexed in the database. Existing installs are migrated automatically and losslessly on first boot: the JSON metadata files are renamed aside (`*.imported.json`) as a one-release recovery source, and the `.md` bodies are left exactly where they are. Nothing changes in how you create, edit, version, delete, or run exercises on your works — the Writers Room UI is unchanged. (Writers Room is single-machine and not federated, so there's no wire-format or schema-version change.) This is the fourth implementation slice (#1017) of the Create relational-schema migration designed in #999, building on the Universes (#1014), Pipeline (#1015), and Story Builder (#1016) slices. The library still persists to the legacy file layout under the `MEMORY_BACKEND=file` dev/test escape hatch.- **Create relational schema design (Postgres-first plan, #999)** — a design doc ([`docs/plans/2026-06-07-create-relational-schema-design.md`](../docs/plans/2026-06-07-create-relational-schema-design.md)) now specifies the PostgreSQL data model for the remaining file-backed Create domains: universes, pipeline series/issues, Story Builder sessions, and Writers Room metadata, plus how `catalog_ingredient_refs` will resolve to DB-native targets. It's design-only (no behavior change): one row per record with the record body in a `data` JSONB column and only queryable fields promoted to columns (mirroring the Creative Director #997 and catalog-user-types #1001 swaps), zero hard FKs (so a federated ref can still arrive before its target), Writers Room draft `.md` bodies staying file-backed with only their metadata indexed, and — crucially — no change to the existing snapshot/push federation model, so each store's file→DB move stays invisible to peers with no schema-version bump. Five implementation slices are tracked as #1014–#1018.- **Catalog user-defined types now live in PostgreSQL** — the user-defined ingredient types you create in Settings → Catalog (the registry that defines what fields a custom catalog type has) moved out of the `data/settings.json` blob into a dedicated `catalog_user_types` table, one row per type, so type definitions version and federate alongside the catalog data they govern instead of riding the unrelated settings file. Existing installs are migrated automatically and losslessly on first boot — the legacy `catalogUserTypes` slice is renamed aside (`catalogUserTypes_imported`) as a one-release recovery source. Nothing changes in how you create, edit, delete, or sync types: the `/api/catalog/types` UI and the cross-machine federation wire format are unchanged (no schema-version bump — the sync payload is storage-independent), so a machine on this version syncs types cleanly with a peer still on the old one. This is the Phase 4 lead-in of the Postgres-first plan (#1001), unblocking typed catalog references. Types still persist to the settings slice under the `MEMORY_BACKEND=file` dev/test escape hatch.diff --git a/server/routes/catalog.js b/server/routes/catalog.jsindex fed1da4897..ec4d8a0d36 100644--- a/server/routes/catalog.js+++ b/server/routes/catalog.js@@ -4,6 +4,7 @@import { Router } from 'express';import * as catalogDB from '../services/catalogDB.js';import * as catalogSync from '../services/catalogSync.js';+import { resolveRefs, listDanglingRefs } from '../services/catalogRefResolver.js';import { projectToCanon } from '../services/catalogCanonProjection.js';import { withTransaction } from '../lib/db.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';@@ -357,6 +358,24 @@ router.get('/refs/:refKind/:refId/ingredients', asyncHandler(async (req, res) =>res.json(await catalogDB.listIngredientsForRef(req.params.refKind, req.params.refId));}));+// Resolver (#1018): does this (refKind, refId) target a LIVE app-native record?+// Pairs with the ingredients list above so a caller rendering "everything+// related to this universe/series/issue/work" can also tell whether the target+// itself still exists. Read-only, local — no FK, by design (D3 of #999).+router.get('/refs/:refKind/:refId/resolve', asyncHandler(async (req, res) => {+ const [resolved] = await resolveRefs([{ refKind: req.params.refKind, refId: req.params.refId }]);+ res.json(resolved);+}));++// Integrity surface (#1018): every LIVE ref whose target record no longer+// resolves (deleted, or never arrived after a federated ref). Mirrors the media+// `metadata-missing` check — a dangling ref isn't an error (the target may sync+// in later), just a report. `count` is handy for a badge.+router.get('/refs/dangling', asyncHandler(async (req, res) => {+ const dangling = await listDanglingRefs();+ res.json({ count: dangling.length, dangling });+}));+// --- Ingredient↔ingredient relations -----------------------------------router.get('/ingredients/:id/relations', asyncHandler(async (req, res) => {diff --git a/server/services/catalogRefResolver.js b/server/services/catalogRefResolver.jsnew file mode 100644index 0000000000..5b354601c8Binary files /dev/null and b/server/services/catalogRefResolver.js differdiff --git a/server/services/catalogRefResolver.test.js b/server/services/catalogRefResolver.test.jsnew file mode 100644index 0000000000..e11266c188--- /dev/null+++ b/server/services/catalogRefResolver.test.js@@ -0,0 +1,150 @@+/**+ * Catalog ref resolver + dangling-ref integrity (#1018).+ *+ * Two layers:+ * 1. A pure parity guard (no DB): REF_TARGET_TABLES must cover exactly the+ * REF_KINDS the validation layer accepts — so a new referenceable record+ * kind can't be added without a resolver target.+ * 2. A live-PG round-trip (SKIPS when no DB): insert refs + targets across all+ * kinds, assert resolveRefs / listDanglingRefs distinguish live from+ * deleted/absent targets. Snapshots + restores every touched table.+ */++import { describe, it, expect, afterAll, beforeAll, beforeEach } from 'vitest';+import { checkHealth, ensureSchema, query, close } from '../lib/db.js';+import { REF_TARGET_TABLES, RESOLVABLE_REF_KINDS } from './catalogRefResolver.js';+import { REF_KINDS } from '../lib/catalogValidation.js';++describe('catalog ref resolver — target-table parity (no DB)', () => {+ it('REF_TARGET_TABLES covers exactly the validated REF_KINDS', () => {+ expect([...RESOLVABLE_REF_KINDS].sort()).toEqual([...REF_KINDS].sort());+ });++ it('every target maps to a non-empty table name', () => {+ for (const kind of RESOLVABLE_REF_KINDS) {+ expect(REF_TARGET_TABLES[kind].table).toMatch(/^[a-z_]+$/);+ }+ });+});++let dbReady = false;+let skipReason = '';+{+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));+ if (!health.connected) {+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;+ } else {+ await ensureSchema().catch(() => {});+ const probe = await query(+ `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'catalog_ingredient_refs') AS ok`,+ ).catch(() => ({ rows: [{ ok: false }] }));+ if (probe.rows?.[0]?.ok) dbReady = true;+ else skipReason = 'catalog_ingredient_refs table not present';+ }+}+if (!dbReady) console.log(`⏭️ catalogRefResolver.test.js (live) skipped: ${skipReason}`);++// The catalog refs table FKs ingredient_id → catalog_ingredients(id), so we need+// a real ingredient row to hang refs on. We snapshot/restore the touched tables.+const TOUCHED = [+ 'catalog_ingredient_refs', 'catalog_ingredients',+ 'universes', 'pipeline_series', 'pipeline_issues', 'writers_room_works', 'creative_director_projects',+];++describe.skipIf(!dbReady)('catalog ref resolver — live resolution + dangling report', () => {+ let resolver;+ const snaps = {};+ const ING = 'cat-ing-resolvertest';++ beforeAll(async () => {+ resolver = await import('./catalogRefResolver.js');+ for (const t of TOUCHED) snaps[t] = (await query(`SELECT * FROM ${t}`)).rows;+ });++ beforeEach(async () => {+ await query(`DELETE FROM catalog_ingredient_refs WHERE ingredient_id = $1`, [ING]);+ await query(`DELETE FROM catalog_ingredients WHERE id = $1`, [ING]);+ // Clean the synthetic targets we create below.+ await query(`DELETE FROM universes WHERE id LIKE 'u-rt-%'`);+ await query(`DELETE FROM pipeline_series WHERE id LIKE 'ser-rt-%'`);+ await query(`DELETE FROM pipeline_issues WHERE id LIKE 'iss-rt-%'`);+ await query(`DELETE FROM writers_room_works WHERE id LIKE 'wr-work-rt%'`);+ await query(`DELETE FROM creative_director_projects WHERE id LIKE 'cd-rt-%'`);+ await query(+ `INSERT INTO catalog_ingredients (id, type, name, payload) VALUES ($1, 'character', 'Resolver Test', '{}'::jsonb)+ ON CONFLICT (id) DO NOTHING`,+ [ING],+ );+ });++ afterAll(async () => {+ for (const t of TOUCHED) {+ await query(`DELETE FROM ${t} WHERE id LIKE '%-rt-%' OR id LIKE 'wr-work-rt%'`).catch(() => {});+ }+ await query(`DELETE FROM catalog_ingredient_refs WHERE ingredient_id = $1`, [ING]).catch(() => {});+ await query(`DELETE FROM catalog_ingredients WHERE id = $1`, [ING]).catch(() => {});+ await close();+ });++ const linkRef = (refKind, refId, role = 'mentioned') => query(+ `INSERT INTO catalog_ingredient_refs (ingredient_id, ref_kind, ref_id, role)+ VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING`,+ [ING, refKind, refId, role],+ );++ it('resolveRefs marks a tuple resolved only when a live target row exists', async () => {+ await query(`INSERT INTO universes (id, name, data) VALUES ('u-rt-1', 'U', '{}'::jsonb)`);+ const out = await resolver.resolveRefs([+ { refKind: 'universe', refId: 'u-rt-1' }, // live+ { refKind: 'universe', refId: 'u-rt-absent' }, // never existed+ { refKind: 'frobnicate', refId: 'x' }, // unknown kind+ { refKind: 'series', refId: '' }, // missing id+ ]);+ expect(out[0]).toMatchObject({ resolved: true });+ expect(out[1].resolved).toBe(false); // absent target — no reason key, just unresolved+ expect(out[2]).toMatchObject({ resolved: false, reason: 'unknown-kind' });+ expect(out[3]).toMatchObject({ resolved: false, reason: 'missing-ref-id' });+ });++ it('a soft-deleted target does NOT resolve', async () => {+ await query(`INSERT INTO writers_room_works (id, title, data, deleted) VALUES ('wr-work-rt1', 'W', '{}'::jsonb, TRUE)`);+ const [out] = await resolver.resolveRefs([{ refKind: 'work', refId: 'wr-work-rt1' }]);+ expect(out.resolved).toBe(false);+ });++ it('a creative-director target resolves by row existence (hard-delete kind)', async () => {+ await query(`INSERT INTO creative_director_projects (id, data) VALUES ('cd-rt-1', '{}'::jsonb)`);+ const [live] = await resolver.resolveRefs([{ refKind: 'creative-director', refId: 'cd-rt-1' }]);+ expect(live.resolved).toBe(true);+ const [gone] = await resolver.resolveRefs([{ refKind: 'creative-director', refId: 'cd-rt-gone' }]);+ expect(gone.resolved).toBe(false);+ });++ it('listDanglingRefs reports only refs whose live target is missing', async () => {+ // One live target (universe), one missing (series), one soft-deleted (work).+ await query(`INSERT INTO universes (id, name, data) VALUES ('u-rt-1', 'U', '{}'::jsonb)`);+ await query(`INSERT INTO writers_room_works (id, title, data, deleted) VALUES ('wr-work-rt2', 'W', '{}'::jsonb, TRUE)`);+ await linkRef('universe', 'u-rt-1');+ await linkRef('series', 'ser-rt-missing');+ await linkRef('work', 'wr-work-rt2');++ const dangling = await resolver.listDanglingRefs();+ const keys = dangling.map((d) => `${d.refKind}:${d.refId}`);+ expect(keys).toContain('series:ser-rt-missing');+ expect(keys).toContain('work:wr-work-rt2');+ expect(keys).not.toContain('universe:u-rt-1'); // live → not dangling+ const series = dangling.find((d) => d.refId === 'ser-rt-missing');+ expect(series).toMatchObject({ reason: 'missing-target', linkCount: 1 });+ });++ it('a tombstoned (unlinked) ref is excluded from the dangling report', async () => {+ await linkRef('series', 'ser-rt-missing');+ await query(+ `UPDATE catalog_ingredient_refs SET deleted = TRUE, deleted_at = NOW()+ WHERE ingredient_id = $1 AND ref_id = 'ser-rt-missing'`,+ [ING],+ );+ const dangling = await resolver.listDanglingRefs();+ expect(dangling.some((d) => d.refId === 'ser-rt-missing')).toBe(false);+ });+});