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: drop dangling catalog 'Appears in' chips to soft-deleted targets (#1812)

[._.]/ Adam Eivyeb87588f43f4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
new file mode 100644
index 0000000000..2fc6a991dc
--- /dev/null
+++ b/.changelog/NEXT.md
@@ -0,0 +1,3 @@
+## Fixed
+
+- Catalog "Appears in" panel no longer renders dangling chips that deep-link to soft-deleted universe/series/creative-director targets — the detail page filters refs to live targets only (the orphan stays recoverable via the "Orphaned" album). Also fixed a stale resolver bug where soft-deleted Creative Director projects (#1564) wrongly resolved as live, and extended orphan-bucket detection so a deleted CD project's ex-cast surfaces as orphaned rather than unlinked. (#1812)
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index 5808d10c38..623c640b1e 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -244,7 +244,10 @@ router.get('/ingredients/:id/details', asyncHandler(async (req, res) => {
const ing = await catalogDB.getIngredient(req.params.id);
if (!ing) throw new ServerError('Ingredient not found', { status: 404 });
const [refs, sources, relations, revisions, media, missingMedia] = await Promise.all([
- catalogDB.listRefsForIngredient(req.params.id),
+ // Live refs only (#1812): the detail page's "Appears in" panel must not
+ // render a chip deep-linking to a soft-deleted universe/series/CD target.
+ // The orphan stays recoverable via the Catalog "Orphaned" album.
+ catalogDB.listLiveRefsForIngredient(req.params.id),
catalogDB.listSourcesForIngredient(req.params.id),
catalogDB.listRelationsForIngredient(req.params.id),
catalogDB.listIngredientRevisions(req.params.id, { limit: 50 }),
diff --git a/server/routes/catalog.test.js b/server/routes/catalog.test.js
index 0e5544316c..75a8daf639 100644
--- a/server/routes/catalog.test.js
+++ b/server/routes/catalog.test.js
@@ -276,6 +276,27 @@ describe.skipIf(!dbReady)('GET /api/catalog/ingredients/:id/details — batched
const r = await request(makeApp()).get(`/api/catalog/ingredients/cat-chr-does-not-exist-${NONCE}/details`);
expect(r.status).toBe(404);
});
+
+ it('omits dangling "Appears in" refs whose target was soft-deleted (#1812)', async () => {
+ const liveUni = `details-live-uni-${NONCE}`;
+ const deadUni = `details-dead-uni-${NONCE}`;
+ await query('INSERT INTO universes (id, name) VALUES ($1, $2)', [liveUni, `Live Uni ${NONCE}`]);
+ // Soft-delete this one so its ref becomes dangling.
+ await query('INSERT INTO universes (id, name, deleted, deleted_at) VALUES ($1, $2, TRUE, NOW())', [deadUni, `Dead Uni ${NONCE}`]);
+ const ing = await catalogDB.createIngredient({ type: 'character', name: `Dangling Probe ${NONCE}` });
+ createdIngredientIds.add(ing.id);
+ await catalogDB.linkIngredientToRef(ing.id, 'universe', liveUni, 'cast-character');
+ await catalogDB.linkIngredientToRef(ing.id, 'universe', deadUni, 'reference');
+
+ const r = await request(makeApp()).get(`/api/catalog/ingredients/${ing.id}/details`);
+ expect(r.status).toBe(200);
+ const refIds = r.body.refs.map((ref) => ref.refId);
+ expect(refIds).toContain(liveUni); // live target → chip stays
+ expect(refIds).not.toContain(deadUni); // dangling target → chip dropped
+
+ await query('DELETE FROM catalog_ingredient_refs WHERE ref_id = ANY($1)', [[liveUni, deadUni]]).catch(() => {});
+ await query('DELETE FROM universes WHERE id = ANY($1)', [[liveUni, deadUni]]).catch(() => {});
+ });
});
describe.skipIf(!dbReady)('GET /api/catalog/facets + ingredient filters (#1762)', () => {
diff --git a/server/services/catalogDB.facets.db.test.js b/server/services/catalogDB.facets.db.test.js
index 3bafc94ac0..9bd030b9a2 100644
--- a/server/services/catalogDB.facets.db.test.js
+++ b/server/services/catalogDB.facets.db.test.js
@@ -133,6 +133,32 @@ describe.skipIf(!dbReady)('catalogDB facets + album filters (#1762)', () => {
expect(raw.items.map((i) => i.id)).not.toContain(orphan.id);
});
+ it('classifies creative-director refs as homing: live → linked, soft-deleted → orphaned (#1812)', async () => {
+ const cdId = `cd-${nonce}`;
+ await query('INSERT INTO creative_director_projects (id, data) VALUES ($1, $2::jsonb)', [cdId, '{}']);
+ const cdLinked = await catalogDB.createIngredient({ type: 'object', name: `CDLinked ${nonce}` });
+ createdIngredientIds.add(cdLinked.id);
+ await catalogDB.linkIngredientToRef(cdLinked.id, 'creative-director', cdId, 'reference');
+
+ // While the CD project is live, the ingredient is LINKED — not unlinked (it
+ // has a homing ref) and not orphaned (the target resolves).
+ let unlinked = await catalogDB.listIngredients({ unlinked: true, limit: 1000 });
+ expect(unlinked.items.map((i) => i.id)).not.toContain(cdLinked.id);
+ let orphaned = await catalogDB.listIngredients({ orphaned: true, limit: 1000 });
+ expect(orphaned.items.map((i) => i.id)).not.toContain(cdLinked.id);
+
+ // Soft-delete the CD project → the ref dangles → the ingredient is ORPHANED
+ // (surfaces in the Orphaned album for re-linking), still not unlinked.
+ await query('UPDATE creative_director_projects SET deleted = TRUE, deleted_at = NOW() WHERE id = $1', [cdId]);
+ orphaned = await catalogDB.listIngredients({ orphaned: true, limit: 1000 });
+ expect(orphaned.items.map((i) => i.id)).toContain(cdLinked.id);
+ unlinked = await catalogDB.listIngredients({ unlinked: true, limit: 1000 });
+ expect(unlinked.items.map((i) => i.id)).not.toContain(cdLinked.id);
+
+ await query('DELETE FROM catalog_ingredient_refs WHERE ref_id = $1', [cdId]).catch(() => {});
+ await query('DELETE FROM creative_director_projects WHERE id = $1', [cdId]).catch(() => {});
+ });
+
it('getCatalogFacets aggregates type/universe/series/tag facets + bucket counts', async () => {
const linked = await catalogDB.createIngredient({ type: 'character', name: `FacetLinked ${nonce}`, tags: [TAG] });
const seriesLinked = await catalogDB.createIngredient({ type: 'character', name: `FacetSeries ${nonce}` });
diff --git a/server/services/catalogDB.js b/server/services/catalogDB.js
index 4b85de97d2..376fb0a9ae 100644
--- a/server/services/catalogDB.js
+++ b/server/services/catalogDB.js
@@ -24,6 +24,7 @@ import { resolveImageInputPath } from '../lib/fileUtils.js';
import { chunkRawText } from '../lib/catalogChunking.js';
import { sanitizeCharacter, sanitizePlace, sanitizeObject } from '../lib/storyBible.js';
import { getInstanceId } from './instances.js';
+import { resolveRefs } from './catalogRefResolver.js';
// Story-bible sanitizers keyed by catalog type, for the registry
// `extractionShape: 'bible'` types ONLY (character/place/object). The catalog
@@ -700,22 +701,38 @@ const THUMBNAIL_KEY_SUBQUERY = `(
LIMIT 1
) AS thumbnail_key`;
-// SQL predicate matching ingredients that have at least one LIVE universe/series
-// ref (target row still resolves). Hardcodes the universe/series live clauses —
-// both are `deleted = FALSE` in REF_TARGET_TABLES (catalogRefResolver.js); kept
-// inline rather than imported because each kind probes a different target table.
-const HAS_LIVE_UNIVERSE_SERIES_REF = `EXISTS (
+// Ref kinds that "home" an ingredient — i.e. drive the linked / unlinked (Raw) /
+// orphaned bucket classification + the Orphaned album. universe/series define
+// album membership; creative-director joined this set in #1812 so a CD project's
+// soft-delete surfaces its ex-cast as orphaned (recoverable) rather than leaving
+// dangling chips. issue/work refs CONSUME ingredients but don't home them, so
+// they stay out. Each kind soft-deletes its target (`deleted = FALSE` =
+// live in REF_TARGET_TABLES, catalogRefResolver.js).
+const HOMING_REF_KINDS = ['universe', 'series', 'creative-director'];
+const HOMING_REF_KINDS_SQL = HOMING_REF_KINDS.map((k) => `'${k}'`).join(', ');
+
+// EXISTS predicate (over the `r` alias) that the named ref points at a LIVE
+// target of its kind. One source of truth for both HAS_LIVE_HOMING_REF and the
+// facets bucket's live_count FILTER — keep the two call sites in sync by reusing
+// this rather than re-inlining the per-kind clauses.
+const liveHomingTargetSql = (r) => `(
+ (${r}.ref_kind = 'universe' AND EXISTS (SELECT 1 FROM universes u WHERE u.id = ${r}.ref_id AND u.deleted = false))
+ OR (${r}.ref_kind = 'series' AND EXISTS (SELECT 1 FROM pipeline_series s WHERE s.id = ${r}.ref_id AND s.deleted = false))
+ OR (${r}.ref_kind = 'creative-director' AND EXISTS (SELECT 1 FROM creative_director_projects p WHERE p.id = ${r}.ref_id AND p.deleted = false)))`;
+
+// SQL predicate matching ingredients that have at least one LIVE homing ref
+// (target row still resolves).
+const HAS_LIVE_HOMING_REF = `EXISTS (
SELECT 1 FROM catalog_ingredient_refs r
WHERE r.ingredient_id = catalog_ingredients.id AND r.deleted = false
- AND ((r.ref_kind = 'universe' AND EXISTS (SELECT 1 FROM universes u WHERE u.id = r.ref_id AND u.deleted = false))
- OR (r.ref_kind = 'series' AND EXISTS (SELECT 1 FROM pipeline_series s WHERE s.id = r.ref_id AND s.deleted = false))))`;
+ AND ${liveHomingTargetSql('r')})`;
-// At least one universe/series ref row exists (live OR dangling) — distinguishes
+// At least one homing ref row exists (live OR dangling) — distinguishes
// "orphaned" (has a ref, none resolve) from "unlinked" (no ref at all).
-const HAS_ANY_UNIVERSE_SERIES_REF = `EXISTS (
+const HAS_ANY_HOMING_REF = `EXISTS (
SELECT 1 FROM catalog_ingredient_refs r
WHERE r.ingredient_id = catalog_ingredients.id AND r.deleted = false
- AND r.ref_kind IN ('universe', 'series'))`;
+ AND r.ref_kind IN (${HOMING_REF_KINDS_SQL}))`;
export async function listIngredients({ ids, type, tag, query: q, refKind = null, refId = null, unlinked = false, orphaned = false, limit = 50, offset = 0, includeEmbedding = false, embeddingMissing = false, staleEmbeddingModel = null } = {}) {
const conditions = ['deleted = false'];
@@ -767,11 +784,11 @@ export async function listIngredients({ ids, type, tag, query: q, refKind = null
params.push(refKind, refId);
} else if (unlinked) {
// "Unsorted / Raw": no universe/series ref at all.
- conditions.push(`NOT ${HAS_ANY_UNIVERSE_SERIES_REF}`);
+ conditions.push(`NOT ${HAS_ANY_HOMING_REF}`);
} else if (orphaned) {
// "Orphaned": has a universe/series ref, but none resolve to a live target.
- conditions.push(HAS_ANY_UNIVERSE_SERIES_REF);
- conditions.push(`NOT ${HAS_LIVE_UNIVERSE_SERIES_REF}`);
+ conditions.push(HAS_ANY_HOMING_REF);
+ conditions.push(`NOT ${HAS_LIVE_HOMING_REF}`);
}
}
if (embeddingMissing) {
@@ -1029,6 +1046,21 @@ export async function listRefsForIngredient(ingredientId) {
return result.rows.map(rowToRef);
}
+// Like listRefsForIngredient, but drops refs whose TARGET no longer resolves to
+// a live record (#1812). A ref row stays live (`deleted = false`) when its
+// universe/series/creative-director/issue/work target is soft-deleted — that's
+// intentional (the orphan is recoverable via the Orphaned album) — but the
+// detail page's "Appears in" panel must not render a chip that deep-links to a
+// 404'd target. Resolution goes through the shared resolver (REF_TARGET_TABLES),
+// so every ref kind is filtered uniformly. resolveRefs preserves input order and
+// de-dupes its target probes, so the filter is a positional zip.
+export async function listLiveRefsForIngredient(ingredientId) {
+ const refs = await listRefsForIngredient(ingredientId);
+ if (refs.length === 0) return refs;
+ const resolved = await resolveRefs(refs);
+ return refs.filter((_, i) => resolved[i]?.resolved === true);
+}
+
export async function listIngredientsForRef(refKind, refId) {
const result = await query(
`SELECT i.*, r.role, r.created_at AS ref_created_at
@@ -1828,9 +1860,12 @@ export async function getCatalogFacets() {
query(`SELECT tag, COUNT(*)::int AS count
FROM (SELECT unnest(tags) AS tag FROM catalog_ingredients WHERE deleted = false) t
GROUP BY tag ORDER BY count DESC, tag`),
- // Per-ingredient bucket classification. ref_count = live universe/series ref
- // ROWS; live_count = those whose target still resolves. unlinked = ref_count 0;
- // orphaned = ref_count > 0 but live_count 0; linked = live_count > 0.
+ // Per-ingredient bucket classification. ref_count = live homing ref ROWS
+ // (universe/series/creative-director); live_count = those whose target still
+ // resolves. unlinked = ref_count 0; orphaned = ref_count > 0 but live_count 0;
+ // linked = live_count > 0. Same homing-ref set + live predicate as the
+ // listIngredients orphaned/unlinked filters, so the bucket counts and the
+ // album listings can't drift.
query(`SELECT
COUNT(*) FILTER (WHERE ref_count = 0)::int AS unlinked,
COUNT(*) FILTER (WHERE ref_count > 0 AND live_count = 0)::int AS orphaned,
@@ -1838,13 +1873,10 @@ export async function getCatalogFacets() {
FROM (
SELECT i.id,
COUNT(r.ref_id) AS ref_count,
- COUNT(r.ref_id) FILTER (WHERE
- (r.ref_kind = 'universe' AND EXISTS (SELECT 1 FROM universes u WHERE u.id = r.ref_id AND u.deleted = false))
- OR (r.ref_kind = 'series' AND EXISTS (SELECT 1 FROM pipeline_series s WHERE s.id = r.ref_id AND s.deleted = false))
- ) AS live_count
+ COUNT(r.ref_id) FILTER (WHERE ${liveHomingTargetSql('r')}) AS live_count
FROM catalog_ingredients i
LEFT JOIN catalog_ingredient_refs r
- ON r.ingredient_id = i.id AND r.deleted = false AND r.ref_kind IN ('universe', 'series')
+ ON r.ingredient_id = i.id AND r.deleted = false AND r.ref_kind IN (${HOMING_REF_KINDS_SQL})
WHERE i.deleted = false
GROUP BY i.id
) sub`),
diff --git a/server/services/catalogRefResolver.js b/server/services/catalogRefResolver.js
index ebd6785001..e4bda9744b 100644
--- a/server/services/catalogRefResolver.js
+++ b/server/services/catalogRefResolver.js
@@ -23,16 +23,17 @@
import { query } from '../lib/db.js';
// ref_kind → the DB table its ref_id points at, plus the predicate that makes a
-// row a LIVE target. universes/pipeline/writers-room soft-delete (deleted
-// column); creative_director_projects hard-deletes (row absence = gone), so it
-// has no liveClause. This map is the single source of truth for the resolver —
-// adding a new referenceable record kind means adding one row here.
+// row a LIVE target. All five target kinds soft-delete (a `deleted` column;
+// creative_director_projects gained one in #1564 so its deletion federates), so
+// a live target is `deleted = FALSE` in every case. This map is the single
+// source of truth for the resolver — adding a new referenceable record kind
+// means adding one row here.
export const REF_TARGET_TABLES = Object.freeze({
universe: { table: 'universes', liveClause: 'deleted = FALSE' },
series: { table: 'pipeline_series', liveClause: 'deleted = FALSE' },
issue: { table: 'pipeline_issues', liveClause: 'deleted = FALSE' },
work: { table: 'writers_room_works', liveClause: 'deleted = FALSE' },
- 'creative-director': { table: 'creative_director_projects', liveClause: null },
+ 'creative-director': { table: 'creative_director_projects', liveClause: 'deleted = FALSE' },
});
/** The ref kinds this resolver can resolve (those with a known target table). */
diff --git a/server/services/catalogRefResolver.test.js b/server/services/catalogRefResolver.test.js
index f1ac0ccea3..6f0cd33f95 100644
--- a/server/services/catalogRefResolver.test.js
+++ b/server/services/catalogRefResolver.test.js
@@ -113,12 +113,18 @@ describe.skipIf(!dbReady)('catalog ref resolver — live resolution + dangling r
expect(out).toMatchObject({ resolved: false, reason: 'missing-target' });
});
- it('a creative-director target resolves by row existence (hard-delete kind)', async () => {
+ it('a creative-director target resolves only while live (soft-delete kind, #1564)', 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);
+ // An absent row never resolves…
const [gone] = await resolver.resolveRefs([{ refKind: 'creative-director', refId: 'cd-rt-gone' }]);
expect(gone.resolved).toBe(false);
+ // …and a SOFT-deleted CD project must not resolve either (the resolver's
+ // liveClause was stale `null` before #1812, wrongly treating CD as live).
+ await query(`UPDATE creative_director_projects SET deleted = TRUE, deleted_at = NOW() WHERE id = 'cd-rt-1'`);
+ const [softGone] = await resolver.resolveRefs([{ refKind: 'creative-director', refId: 'cd-rt-1' }]);
+ expect(softGone).toMatchObject({ resolved: false, reason: 'missing-target' });
});
it('listDanglingRefs reports only refs whose live target is missing', async () => {