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

feat: remove cast/places/objects entries from a universe's canon buckets

[._.]/ Adam Eivy94488a7f4d33
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 637a5362f4..114d135918 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -158,3 +158,5 @@
- **[issue-3507] Opening the Brain graph's search box no longer walks every record on disk.** The graph search index returns nothing but a name and a type per node, but it was building that list by loading the *full* body of every person, project, idea, admin item and memory entry — plus every Daily Log day — and then discarding the summaries, tags and status it had just parsed. Since Brain keeps one file per record, focusing a search input meant thousands of file reads for a dropdown of labels. The index now reads the same in-memory field projections unified search uses, so it costs a scan of memory rather than a walk of the disk, and a Daily Log entry contributes only "is this day non-empty?" instead of its whole text — the biggest body in the Brain never enters the cache at all. The two graph views that genuinely need bodies (the overview and a node's neighborhood) still load them; only the label list changed, and it derives its labels and its skip rules from the same helpers the full-record path uses so the two cannot drift. Nodes come back in the same order as before: the projections are read unranked, so the memory entries in the dropdown stay in store order rather than silently re-sorting themselves newest-first.
- **[issue-3485] Three.js model generation can now be narrowed to a subject family, so the model is judged against a checklist it did not write itself.** The assembly-coverage gate has always carried an honest limit: it proves a spec built everything it promised, never that it promised enough — a component nobody noticed is never inventoried, never specified, and passes every check clean. Picking one of five coarse families (character, vehicle, weapon, building, device) on the create form or the workspace splices a curated checklist into the generation prompt — the components a reconstruction of that family is usually judged on, the material zones worth separating, the axes to judge the result on, and the orbit views that expose the usual failures — and lets the coverage gate warn on a required component the spec never mentions anywhere. That warning feeds the unsteered refinement pass, so "you never accounted for the trigger guard" becomes something the next run is actually told. The checklist is deliberately framed as a floor rather than a ceiling, in the prompt and in the panel: it names the limitations escape hatch for a component the reference genuinely does not show, and it says outright that a spec inventorying only the checklist has under-observed its reference — a thin taxonomy that teaches the model to stop early would be worse than none. Family is optional and defaults to General, which splices nothing at all: an existing model, and anyone who does not pick a family, gets the byte-identical prompt that shipped before this. The workspace renders the chosen family's checklist under the coverage panel with each component marked accounted-for or not, so the orbit views worth checking are next to the preview you would check them in. The field is additive on the record, so no migration is needed and a model generated before this reads back as General. A family id this build does not ship — a record written by a build with a larger taxonomy, then downgraded or restored from a backup — degrades to no checklist everywhere rather than failing the record: the picker shows General instead of pinning itself to a value it has no option for, and the server coerces rather than rejecting the refine request, which would otherwise have left that model permanently un-refinable.
+
+- **Canon entries can be removed from a universe's Cast, Places and Objects buckets.** Every other bucket on a universe page — the Other category variations, the Composite sheets — has always carried a trailing X to drop an entry you no longer want, but the three canon trunks had no way to remove anything at all: an entry pulled in by an over-eager prose extraction, added from the Catalog by mistake, or simply written out of the world was stuck in the universe forever. All five buckets now behave the same way, with the same X in the same place on the card. Removal is deliberately narrow and says so in the button's tooltip and the confirming toast: the entry leaves *this universe's canon list* and nothing else is touched. Its rendered reference images and character reference sheets stay in the gallery, where they remain previewable and re-attachable to another entry, and the shared Catalog ingredient an entry may be linked to is left alone — that row is a universe-independent record other universes and series can embed, so deleting canon must not delete it. Locked entries are removable, because the lock exists to stop AI refine/differentiate passes from rewriting an entry, not to stop the user from deciding it does not belong. The removal goes through its own endpoint that filters the array inside the universe's write queue rather than composing the surviving list on the client and PATCHing it back from a possibly-stale read — the existing PATCH path already shields rendered images and reference-sheet pointers against that race, but not a sibling entry's pinned primary image, its lock state, or a description a refine rewrote while you were clicking. The card disappears on click and is restored, whole and in place, if the write fails. Because a universe merges across machines as a whole record by last-write-wins, the removal propagates to your peers on the next sync without any tombstone, and neither the catalog projection nor the boot reconciler — both of which only ever read canon and write outward — can put the entry back.
diff --git a/client/src/components/pipeline/CanonCard.jsx b/client/src/components/pipeline/CanonCard.jsx
index 569524e078..0381ae984e 100644
--- a/client/src/components/pipeline/CanonCard.jsx
+++ b/client/src/components/pipeline/CanonCard.jsx
@@ -11,7 +11,7 @@
*/
import { useEffect, useRef, useState } from 'react';
-import { Loader2, ImagePlus, ImageUp, WandSparkles, Lock, Unlock, Shirt, Plus, Trash2, ChevronDown, ChevronRight, Star, Square, BookOpen, ScanText } from 'lucide-react';
+import { Loader2, ImagePlus, ImageUp, WandSparkles, Lock, Unlock, Shirt, Plus, Trash2, X, ChevronDown, ChevronRight, Star, Square, BookOpen, ScanText } from 'lucide-react';
import useMediaJobProgress from '../../hooks/useMediaJobProgress';
import useRowDraft from '../../hooks/useRowDraft';
import useFieldDraft from '../../hooks/useFieldDraft';
@@ -396,6 +396,12 @@ export default function CanonCard({
// Shape: { castList } — the universe-wide character list feeds the
// attachment target picker in ObjectAttachmentsEditor.
objectExtensions = null,
+ // `(entryId) => void` — drop this entry from its canon bucket. Same contract
+ // (and same X-button affordance) as removing a category variation or a
+ // composite sheet: the entry leaves the universe bucket, while its rendered
+ // images and any linked Catalog ingredient are left alone. Null in the
+ // pipeline/series view (NounsStage), which has no removal channel.
+ onRemove = null,
}) {
const description = kind.descFor(entry);
const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : [];
@@ -649,6 +655,21 @@ export default function CanonCard({
{togglingLock ? <Loader2 size={14} className="animate-spin" /> : (locked ? <Lock size={14} /> : <Unlock size={14} />)}
</button>
) : null}
+ {onRemove ? (
+ // Trailing X, matching the variation + composite-sheet cards so every
+ // universe bucket removes the same way. Deliberately NOT lock-gated:
+ // the lock protects the entry from AI rewrites, not from the user
+ // deciding it doesn't belong in this universe.
+ <button
+ type="button"
+ onClick={() => onRemove(entry.id)}
+ className="p-1 text-gray-400 hover:text-port-error rounded"
+ title={`Remove ${entry.name} from this universe's canon — rendered images and any Catalog entry are kept`}
+ aria-label={`Remove ${entry.name}`}
+ >
+ <X size={14} />
+ </button>
+ ) : null}
</div>
);
diff --git a/client/src/components/universe/KindSectionContext.jsx b/client/src/components/universe/KindSectionContext.jsx
index 0a6657d0f1..d14a8b76cb 100644
--- a/client/src/components/universe/KindSectionContext.jsx
+++ b/client/src/components/universe/KindSectionContext.jsx
@@ -23,7 +23,7 @@
* onRender, onRenderAll, onRenderCleanPlate, onJobCompleted, onJobFailed,
* onPreview, onRefine, onExpandCharacter, onSheetCompleted, onSheetDeleted,
* onToggleLock, onBulkLock, onPatchEntry, onDescribeImages,
- * onCorrectFromImage, onPickFromCatalog, onAddEntry
+ * onCorrectFromImage, onPickFromCatalog, onAddEntry, onRemoveEntry
*/
import { createContext, useContext } from 'react';
diff --git a/client/src/components/universe/UniverseCanonSection.add.test.jsx b/client/src/components/universe/UniverseCanonSection.add.test.jsx
index f7780e00e5..ce41afc222 100644
--- a/client/src/components/universe/UniverseCanonSection.add.test.jsx
+++ b/client/src/components/universe/UniverseCanonSection.add.test.jsx
@@ -26,6 +26,7 @@ vi.mock('../../services/apiUniverseBuilder', () => ({
getUniverseCanonUsage: vi.fn(),
setUniverseCanonLock: vi.fn(),
setUniverseCanonLockAll: vi.fn(),
+ removeUniverseCanonEntry: vi.fn(),
expandUniverseCharacter: vi.fn(),
}));
diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsx
index b438ac3b0b..8bf0f6f7e3 100644
--- a/client/src/components/universe/UniverseCanonSection.jsx
+++ b/client/src/components/universe/UniverseCanonSection.jsx
@@ -29,6 +29,7 @@ import {
getUniverseCanonUsage,
setUniverseCanonLock,
setUniverseCanonLockAll,
+ removeUniverseCanonEntry,
expandUniverseCharacter,
} from '../../services/apiUniverseBuilder';
import { generateImage } from '../../services/apiSystem';
@@ -647,6 +648,45 @@ export default function UniverseCanonSection({
return !!updated;
}, [universe, universeId, onUniverseChange, mountedRef, creatingKindKey]);
+ // Remove one entry from a canon bucket. Mirrors the X button on category
+ // variations / composite sheets: the entry leaves this universe's canon and
+ // nothing else is touched — the server drops it from the array only, leaving
+ // its rendered images, reference sheets, and any linked Catalog ingredient
+ // in place. Optimistic so the card disappears on click; reverts on failure.
+ const handleRemoveEntry = useCallback(async (kind, entryId) => {
+ const latest = latestUniverseRef.current;
+ if (!latest) return;
+ const kindKey = kind.key;
+ const list = getKindList(latest, kindKey);
+ const target = list.find((e) => e?.id === entryId);
+ if (!target) return;
+ const capturedId = universeId;
+ onUniverseChange({ ...latest, [kindKey]: list.filter((e) => e !== target) });
+ const result = await removeUniverseCanonEntry(universeId, kind.apiKind, entryId, { silent: true })
+ .catch((err) => { toast.error(err.message || `Remove ${kind.singular} failed`); return null; });
+ const stillCurrent = mountedRef.current && currentUniverseIdRef.current === capturedId;
+ if (!stillCurrent) return;
+ if (!result) {
+ // Revert the optimistic removal off the pre-removal snapshot — the same
+ // one-liner as `handleCreateEntry` / `handlePickFromCatalog`, and safe
+ // for the same documented reason (canon edits are user-driven one at a
+ // time). Restores the entry at its original position for free.
+ onUniverseChange({ ...latest, [kindKey]: list });
+ return;
+ }
+ if (result.universe) onUniverseChange(result.universe);
+ // Drop the removed entry's usage rows locally instead of refetching:
+ // `/canon-usage` re-scans every issue's prose across every linked series,
+ // and removing an entry can't change any SURVIVING entry's usage.
+ setUsage((prev) => {
+ const rows = prev?.[kindKey];
+ if (!rows || !(entryId in rows)) return prev;
+ const { [entryId]: _dropped, ...rest } = rows;
+ return { ...prev, [kindKey]: rest };
+ });
+ toast.success(`Removed ${target.name || kind.singular} from canon — images and catalog entry kept`);
+ }, [universeId, onUniverseChange, mountedRef]);
+
// Inline-edit channel for canon fields the user types/picks directly
// (setting intExt + timeOfDay chips, primaryImageRef pinning, wardrobe
// edits). Optimistic — UI updates before the server roundtrip so chip
@@ -736,6 +776,7 @@ export default function UniverseCanonSection({
catalogLinking,
onAddEntry: (payload) => handleCreateEntry(kind, payload),
creating: creatingKindKey === kind.key,
+ onRemoveEntry: (entryId) => handleRemoveEntry(kind, entryId),
});
return (
@@ -920,7 +961,7 @@ function KindSection() {
onBulkLock, bulkLocking, fullList, castList = [],
externalPendingByEntryId = null, compact = false, onRenderAll = null,
renderingAll = false, onPickFromCatalog = null, catalogLinking = false,
- onAddEntry = null, creating = false,
+ onAddEntry = null, creating = false, onRemoveEntry = null,
} = useKindSection();
// Universe-only character wiring — `null` for non-character kinds so
// CanonCard's gate stays `kind === 'characters' && characterExtensions`.
@@ -1100,6 +1141,7 @@ function KindSection() {
? { ...characterExtensions, expanding: expandingId === entry.id }
: null}
objectExtensions={objectExtensions}
+ onRemove={onRemoveEntry}
/>
))}
</ul>
diff --git a/client/src/components/universe/UniverseCanonSection.picker.test.jsx b/client/src/components/universe/UniverseCanonSection.picker.test.jsx
index bb7d0f6373..bdfe7166ac 100644
--- a/client/src/components/universe/UniverseCanonSection.picker.test.jsx
+++ b/client/src/components/universe/UniverseCanonSection.picker.test.jsx
@@ -26,6 +26,7 @@ vi.mock('../../services/apiUniverseBuilder', () => ({
getUniverseCanonUsage: vi.fn(),
setUniverseCanonLock: vi.fn(),
setUniverseCanonLockAll: vi.fn(),
+ removeUniverseCanonEntry: vi.fn(),
expandUniverseCharacter: vi.fn(),
}));
diff --git a/client/src/components/universe/UniverseCanonSection.remove.test.jsx b/client/src/components/universe/UniverseCanonSection.remove.test.jsx
new file mode 100644
index 0000000000..24575b6477
--- /dev/null
+++ b/client/src/components/universe/UniverseCanonSection.remove.test.jsx
@@ -0,0 +1,170 @@
+/**
+ * Tests for the per-entry Remove (X) affordance on UniverseCanonSection.
+ *
+ * The contract mirrors the X button that already exists on category
+ * variations + composite sheets: one click drops the entry from THIS
+ * universe's canon bucket and nothing else. In particular it must go through
+ * the dedicated DELETE endpoint (never a wholesale `updateUniverse` PATCH of
+ * the array, which would clobber a concurrent render-completion imageRefs[]
+ * append on a sibling) and it must not touch the gallery or the Catalog.
+ *
+ * The harness below owns the universe in real state rather than passing a
+ * frozen prop, because the revert path reads the LIVE draft (via the
+ * component's `latestUniverseRef`) to decide whether the optimistic removal
+ * still needs undoing. A vi.fn() that swallows the change would make the
+ * revert look like a no-op for the wrong reason.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { useState } from 'react';
+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+
+vi.mock('../../services/apiCatalog', () => ({
+ listCatalogIngredients: vi.fn(),
+ linkCatalogIngredient: vi.fn(),
+ unlinkCatalogIngredient: vi.fn(),
+}));
+
+vi.mock('../../services/apiUniverseBuilder', () => ({
+ extractUniverseCanon: vi.fn(),
+ refineUniverseCharacter: vi.fn(),
+ differentiateUniverseCast: vi.fn(),
+ updateUniverse: vi.fn(),
+ getUniverseCanonUsage: vi.fn(),
+ setUniverseCanonLock: vi.fn(),
+ setUniverseCanonLockAll: vi.fn(),
+ removeUniverseCanonEntry: vi.fn(),
+ expandUniverseCharacter: vi.fn(),
+}));
+
+vi.mock('../../services/apiSystem', () => ({ generateImage: vi.fn() }));
+
+vi.mock('../ui/Toast', () => ({
+ default: { success: vi.fn(), error: vi.fn(), info: vi.fn() },
+}));
+
+import UniverseCanonSection from './UniverseCanonSection';
+import {
+ removeUniverseCanonEntry, updateUniverse, getUniverseCanonUsage,
+} from '../../services/apiUniverseBuilder';
+import { unlinkCatalogIngredient } from '../../services/apiCatalog';
+
+const ALEX = {
+ id: 'chr-1',
+ name: 'Alex',
+ physicalDescription: 'jacket',
+ imageRefs: ['alex.png'],
+ primaryImageRef: 'alex.png',
+ ingredientId: 'ing-alex',
+ locked: false,
+};
+const BLAIR = { id: 'chr-2', name: 'Blair', physicalDescription: 'scarf', locked: false };
+
+const baseUniverse = (over = {}) => ({
+ id: 'uni-1',
+ name: 'Test World',
+ characters: [],
+ places: [],
+ objects: [],
+ ...over,
+});
+
+// Stateful host so `onUniverseChange` actually swaps the rendered draft.
+function Harness({ initial, onChange, kindFilter }) {
+ const [universe, setUniverse] = useState(baseUniverse(initial));
+ return (
+ <UniverseCanonSection
+ universe={universe}
+ universeId="uni-1"
+ onUniverseChange={(next) => { onChange?.(next); setUniverse(next); }}
+ imageCfg={{}}
+ kindFilter={kindFilter || 'characters'}
+ />
+ );
+}
+
+const renderSection = async ({ universe, onChange, kindFilter } = {}) => {
+ const result = render(
+ <MemoryRouter>
+ <Harness initial={universe} onChange={onChange} kindFilter={kindFilter} />
+ </MemoryRouter>,
+ );
+ // Settle the mount-time canon-usage fetch before the test interacts.
+ await act(async () => {});
+ return result;
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getUniverseCanonUsage.mockResolvedValue({});
+});
+
+describe('UniverseCanonSection — remove entry', () => {
+ it('calls the canon DELETE endpoint with the kind + entry id, touching nothing else', async () => {
+ removeUniverseCanonEntry.mockResolvedValue({
+ universe: baseUniverse({ characters: [BLAIR] }),
+ entry: ALEX,
+ });
+ await renderSection({ universe: { characters: [ALEX, BLAIR] } });
+
+ fireEvent.click(screen.getByRole('button', { name: /remove alex/i }));
+
+ await waitFor(() => expect(removeUniverseCanonEntry).toHaveBeenCalled());
+ expect(removeUniverseCanonEntry).toHaveBeenCalledWith(
+ 'uni-1', 'character', 'chr-1', expect.objectContaining({ silent: true }),
+ );
+ // Never the wholesale-array PATCH, and never a catalog mutation — the
+ // entry's rendered image + catalog ingredient both survive.
+ expect(updateUniverse).not.toHaveBeenCalled();
+ expect(unlinkCatalogIngredient).not.toHaveBeenCalled();
+ expect(screen.queryByText('Alex')).not.toBeInTheDocument();
+ expect(screen.getByText('Blair')).toBeInTheDocument();
+ });
+
+ it('drops the card optimistically, before the request resolves', async () => {
+ let resolveRemove;
+ removeUniverseCanonEntry.mockReturnValue(new Promise((res) => { resolveRemove = res; }));
+ const onChange = vi.fn();
+ await renderSection({ universe: { characters: [ALEX, BLAIR] }, onChange });
+
+ fireEvent.click(screen.getByRole('button', { name: /remove alex/i }));
+
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange.mock.calls[0][0].characters.map((c) => c.id)).toEqual(['chr-2']);
+ expect(screen.queryByText('Alex')).not.toBeInTheDocument();
+
+ await act(async () => {
+ resolveRemove({ universe: baseUniverse({ characters: [BLAIR] }), entry: ALEX });
+ });
+ expect(screen.queryByText('Alex')).not.toBeInTheDocument();
+ });
+
+ it('restores the entry, whole and in place, when the request fails', async () => {
+ removeUniverseCanonEntry.mockRejectedValue(new Error('nope'));
+ const onChange = vi.fn();
+ await renderSection({ universe: { characters: [ALEX, BLAIR] }, onChange });
+
+ fireEvent.click(screen.getByRole('button', { name: /remove alex/i }));
+
+ await waitFor(() => expect(onChange).toHaveBeenCalledTimes(2));
+ const restored = onChange.mock.calls[1][0].characters;
+ expect(restored.map((c) => c.id)).toEqual(['chr-1', 'chr-2']);
+ // Restored whole — the image refs + catalog backlink round-trip intact.
+ expect(restored[0]).toEqual(ALEX);
+ expect(screen.getByText('Alex')).toBeInTheDocument();
+ });
+
+ it('offers Remove on locked entries — the lock guards AI rewrites, not removal', async () => {
+ await renderSection({ universe: { characters: [{ ...ALEX, locked: true }] } });
+ expect(screen.getByRole('button', { name: /remove alex/i })).toBeEnabled();
+ });
+
+ it.each([
+ ['places', { id: 'plc-1', name: 'The Vault', description: 'a room' }],
+ ['objects', { id: 'obj-1', name: 'The Key', description: 'brass' }],
+ ])('renders a Remove button for %s too', async (kindKey, entry) => {
+ await renderSection({ kindFilter: kindKey, universe: { [kindKey]: [entry] } });
+ expect(screen.getByRole('button', { name: new RegExp(`remove ${entry.name}`, 'i') }))
+ .toBeInTheDocument();
+ });
+});
diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.js
index 19cdfc32ba..51b6e10c80 100644
--- a/client/src/services/apiUniverseBuilder.js
+++ b/client/src/services/apiUniverseBuilder.js
@@ -348,7 +348,7 @@ export const getUniverseSeriesNames = (universeId) =>
// Toggle the `locked` flag on a single canon entry. Locked entries are
// protected from AI rewrite paths (refine returns 409; differentiate skips
// them at apply time; re-extract appends evidence only). `kind` must be
-// 'character' | 'setting' | 'object' (the singular BIBLE_KIND values).
+// 'character' | 'place' | 'object' (the singular BIBLE_KIND values).
export const setUniverseCanonLock = (universeId, kind, entryId, locked, options = {}) =>
request(`/universe-builder/${encodeURIComponent(universeId)}/canon/${encodeURIComponent(kind)}/${encodeURIComponent(entryId)}/lock`, {
method: 'PATCH',
@@ -356,6 +356,16 @@ export const setUniverseCanonLock = (universeId, kind, entryId, locked, options
...options,
});
+// Remove one canon entry from its universe bucket. Returns
+// `{ universe, entry }`. Scoped to the canon array ONLY — the entry's rendered
+// images / reference sheets stay in the gallery and the shared Catalog
+// ingredient it may point at is left untouched.
+export const removeUniverseCanonEntry = (universeId, kind, entryId, options = {}) =>
+ request(`/universe-builder/${encodeURIComponent(universeId)}/canon/${encodeURIComponent(kind)}/${encodeURIComponent(entryId)}`, {
+ method: 'DELETE',
+ ...options,
+ });
+
// Bulk lock/unlock every canon entry of a single kind. Returns
// `{ universe, kind, locked, changed, total }`.
export const setUniverseCanonLockAll = (universeId, kind, locked, options = {}) =>
diff --git a/server/routes/universeBuilder/canon.js b/server/routes/universeBuilder/canon.js
index b8bc94b3de..85804e0675 100644
--- a/server/routes/universeBuilder/canon.js
+++ b/server/routes/universeBuilder/canon.js
@@ -104,6 +104,18 @@ router.patch('/:id/canon/:kind/:entryId/lock', asyncHandler(async (req, res) =>
res.json(result);
}));
+// Remove ONE canon entry from its bucket. Scoped to the universe's canon
+// array only — rendered images, character reference sheets, and the shared
+// Catalog ingredient the entry may point at are all left intact (see
+// `removeCanonEntry`). Mirrors the X button on category variations /
+// composite sheets, which likewise only drop the bucket entry.
+router.delete('/:id/canon/:kind/:entryId', asyncHandler(async (req, res) => {
+ const { kind } = validateRequest(lockParamsSchema, req.params);
+ const result = await canonSvc.removeCanonEntry(req.params.id, kind, req.params.entryId)
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
// Bulk lock/unlock every canon entry of a single kind. Powers the
// "Lock all / Unlock all" buttons in the Universe Builder canon section.
router.patch('/:id/canon/:kind/lock-all', asyncHandler(async (req, res) => {
diff --git a/server/routes/universeBuilder/index.test.js b/server/routes/universeBuilder/index.test.js
index d5599f6080..ddc663d82f 100644
--- a/server/routes/universeBuilder/index.test.js
+++ b/server/routes/universeBuilder/index.test.js
@@ -50,9 +50,17 @@ const applyCanonImageCorrectionMock = vi.fn(async (_universeId, kind, entryId, b
universe: { id: _universeId },
entry: { id: entryId, [kind === 'character' ? 'physicalDescription' : 'description']: body.description, primaryImageRef: body.imageFilename },
}));
+const removeCanonEntryMock = vi.fn(async (universeId, kind, entryId) => ({
+ universe: { id: universeId, characters: [], places: [], objects: [] },
+ entry: { id: entryId, name: 'Alex', imageRefs: ['alex.png'], ingredientId: 'ing-alex' },
+}));
vi.mock('../../services/universeCanon.js', async () => {
const actual = await vi.importActual('../../services/universeCanon.js');
- return { ...actual, applyCanonImageCorrection: (...args) => applyCanonImageCorrectionMock(...args) };
+ return {
+ ...actual,
+ applyCanonImageCorrection: (...args) => applyCanonImageCorrectionMock(...args),
+ removeCanonEntry: (...args) => removeCanonEntryMock(...args),
+ };
});
const expandEntityFromImagesMock = vi.fn(async () => ({ fields: { pronouns: 'she/her' }, updatedFields: ['pronouns'], llm: { provider: 'mock', model: null } }));
vi.mock('../../services/universeVisionExpand.js', async () => {
@@ -1398,6 +1406,31 @@ describe('universe-builder routes', () => {
});
});
+ describe('DELETE /:id/canon/:kind/:entryId', () => {
+ it('removes the entry from its canon bucket and returns the removed record', async () => {
+ removeCanonEntryMock.mockClear();
+ const res = await request(buildApp())
+ .delete('/api/universe-builder/uni-1/canon/character/chr-1');
+ expect(res.status).toBe(200);
+ expect(removeCanonEntryMock).toHaveBeenCalledWith('uni-1', 'character', 'chr-1');
+ // The response carries the entry whole — the route must not scrub its
+ // image refs or catalog backlink on the way out, because removal is
+ // scoped to the canon array and leaves both stores alone.
+ expect(res.body.entry).toEqual(expect.objectContaining({
+ id: 'chr-1', imageRefs: ['alex.png'], ingredientId: 'ing-alex',
+ }));
+ expect(res.body.universe.characters).toEqual([]);
+ });
+
+ it('rejects an unknown kind before invoking the service', async () => {
+ removeCanonEntryMock.mockClear();
+ const res = await request(buildApp())
+ .delete('/api/universe-builder/uni-1/canon/monster/chr-1');
+ expect(res.status).toBe(400);
+ expect(removeCanonEntryMock).not.toHaveBeenCalled();
+ });
+ });
+
describe('POST /refine-prompts (style-reference image)', () => {
it('resolves the image filename to an absolute path before the service', async () => {
const res = await request(buildApp())
diff --git a/server/services/universeCanon.js b/server/services/universeCanon.js
index 0fad965f80..c06df20d48 100644
--- a/server/services/universeCanon.js
+++ b/server/services/universeCanon.js
@@ -15,6 +15,19 @@ import { runPromptRefine } from './pipeline/refineHelpers.js';
import { ServerError } from '../lib/errorHandler.js';
import { shortId } from '../lib/fileUtils.js';
+// Every per-entry canon operation below is addressed by singular kind
+// ('character' | 'place' | 'object') and rejects anything else the same way.
+// The routes already validate the enum via `lockParamsSchema`, so this only
+// defends direct service callers — but it's the difference between a 400 and
+// an undefined `BIBLE_FIELD[kind]` silently reading the wrong array.
+const assertCanonKind = (kind) => {
+ if (BIBLE_KINDS.includes(kind)) return;
+ throw new ServerError(
+ `Invalid canon kind "${kind}" — expected one of: ${BIBLE_KINDS.join(', ')}`,
+ { status: 400, code: 'UNIVERSE_CANON_INVALID_KIND' },
+ );
+};
+
export const peerForPrompt = (entry) => ({
id: entry.id,
name: entry.name,
@@ -514,12 +527,7 @@ export async function differentiateUniverseCast(universeId, options = {}) {
// protected from AI rewrite paths — see `mergeExtractedBible` (evidence-only
// append) and the refine/differentiate runtime guards.
export async function setCanonEntryLock(universeId, kind, entryId, locked) {
- if (!BIBLE_KINDS.includes(kind)) {
- throw new ServerError(
- `Invalid canon kind "${kind}" — expected one of: ${BIBLE_KINDS.join(', ')}`,
- { status: 400, code: 'UNIVERSE_CANON_INVALID_KIND' },
- );
- }
+ assertCanonKind(kind);
const field = BIBLE_FIELD[kind];
let found = false;
// Mutator form (same as setCanonKindLockAll) so the flip is computed from
@@ -561,12 +569,7 @@ export async function setCanonEntryLock(universeId, kind, entryId, locked) {
* and apply) can't be clobbered by a stale read.
*/
export async function applyCanonImageCorrection(universeId, kind, entryId, { description, imageFilename } = {}) {
- if (!BIBLE_KINDS.includes(kind)) {
- throw new ServerError(
- `Invalid canon kind "${kind}" — expected one of: ${BIBLE_KINDS.join(', ')}`,
- { status: 400, code: 'UNIVERSE_CANON_INVALID_KIND' },
- );
- }
+ assertCanonKind(kind);
const trimmedDescription = typeof description === 'string' ? description.trim().slice(0, DESC_LIMIT[kind]) : '';
if (!trimmedDescription) {
throw new ServerError('A corrected description is required', { status: 400, code: 'VALIDATION_ERROR' });
@@ -614,12 +617,7 @@ export async function applyCanonImageCorrection(universeId, kind, entryId, { des
* carries enough info for a toast like "Locked 7 characters").
*/
export async function setCanonKindLockAll(universeId, kind, locked) {
- if (!BIBLE_KINDS.includes(kind)) {
- throw new ServerError(
- `Invalid canon kind "${kind}" — expected one of: ${BIBLE_KINDS.join(', ')}`,
- { status: 400, code: 'UNIVERSE_CANON_INVALID_KIND' },
- );
- }
+ assertCanonKind(kind);
const field = BIBLE_FIELD[kind];
let changed = 0;
let total = 0;
@@ -643,6 +641,53 @@ export async function setCanonKindLockAll(universeId, kind, locked) {
return { universe: updated, kind, locked, changed, total };
}
+/**
+ * Remove ONE canon entry from a universe's characters/places/objects bucket.
+ *
+ * Deliberately narrow: this drops the entry from the universe's canon array
+ * and NOTHING else. It does NOT
+ * - delete the entry's rendered `imageRefs[]` / `primaryImageRef` files or
+ * its character reference-sheet PNGs (they stay in the gallery, reachable
+ * from Media, and re-attachable to another entry), and
+ * - delete or unlink the shared Catalog ingredient an entry may point at via
+ * `ingredientId` (the catalog row is a universe-independent record; other
+ * universes and series may embed the same ingredient).
+ * Clearing the removed character's in-memory pending sheet-render slot (so an
+ * in-flight sheet render doesn't stamp a pointer onto an entry that's gone) is
+ * NOT done here — `updateUniverse` diffs the character ids across every
+ * canon-touching write and runs that cascade generically.
+ *
+ * Uses the mutator form so the filter runs against the freshest persisted
+ * state inside `updateUniverse`'s write queue. A read-modify-write split
+ * (getUniverse → PATCH the filtered array) would replace the whole array via
+ * PATCHABLE_SCALARS from a stale read, clobbering whatever landed on a SIBLING
+ * entry in between. `preserveImageRefsById` + `mergePreservedSheetPointers`
+ * already shield `imageRefs[]` and sheet pointers on that path — but NOT
+ * `primaryImageRef`, `locked`, or a concurrent refine's rewritten description,
+ * so the stale-read window is real for those.
+ *
+ * Returns `{ universe, entry }` where `entry` is the removed record.
+ */
+export async function removeCanonEntry(universeId, kind, entryId) {
+ assertCanonKind(kind);
+ const field = BIBLE_FIELD[kind];
+ let removed = null;
+ const updated = await updateUniverse(universeId, (cur) => {
+ const list = Array.isArray(cur[field]) ? cur[field] : [];
+ removed = list.find((e) => e.id === entryId);
+ if (!removed) return null;
+ return { [field]: list.filter((e) => e !== removed) };
+ });
+ if (!removed) {
+ throw new ServerError(
+ `Canon ${kind} ${entryId} not found in universe`,
+ { status: 404, code: 'UNIVERSE_CANON_NOT_FOUND' },
+ );
+ }
+ console.log(`🗑️ Removed canon ${kind} "${removed.name}" from universe ${shortId(universeId)} (assets + catalog untouched)`);
+ return { universe: updated, entry: removed };
+}
+
/**
* Strip a filename from every `imageRefs[]` across every universe's
* characters/places/objects, and from every top-level `styleReferences[]`
diff --git a/server/services/universeCanon.test.js b/server/services/universeCanon.test.js
index 8b3a352b98..2d5d939b30 100644
--- a/server/services/universeCanon.test.js
+++ b/server/services/universeCanon.test.js
@@ -123,6 +123,69 @@ describe('universeCanon — setCanonEntryLock', () => {
});
});
+describe('universeCanon — removeCanonEntry', () => {
+ it('drops only the target entry, persists, and scrubs neither its image refs nor its catalog link', async () => {
+ // Removal is scoped to the canon array: it must not purge imageRefs (the
+ // files stay in the gallery) or the shared catalog ingredient the entry
+ // points at. Asserting on the RETURNED entry proves the service hands back
+ // the record whole rather than a stripped shell; the sibling assertions
+ // prove no cross-entry ref purge ran.
+ const w = await seedUniverseWithCharacters([
+ { name: 'Alex', physicalDescription: 'jacket', imageRefs: ['alex-a.png', 'alex-b.png'], primaryImageRef: 'alex-a.png', ingredientId: 'ing-alex' },
+ { name: 'Blair', physicalDescription: 'scarf', imageRefs: ['blair.png'], ingredientId: 'ing-blair' },
+ ]);
+ const target = w.characters.find((c) => c.name === 'Alex');
+ const { entry, universe } = await canonSvc.removeCanonEntry(w.id, 'character', target.id);
+ expect(entry.name).toBe('Alex');
+ expect(entry.imageRefs).toEqual(['alex-a.png', 'alex-b.png']);
+ expect(entry.primaryImageRef).toBe('alex-a.png');
+ expect(entry.ingredientId).toBe('ing-alex');
+ expect(universe.characters.map((c) => c.name)).toEqual(['Blair']);
+ const survivor = universe.characters[0];
+ expect(survivor.imageRefs).toEqual(['blair.png']);
+ expect(survivor.ingredientId).toBe('ing-blair');
+ // Persisted: a fresh read no longer carries the removed entry.
+ const reread = (await svc.listUniverses())[0];
+ expect(reread.characters.map((c) => c.name)).toEqual(['Blair']);
+ });
+
+ it('removes a locked entry — the lock guards AI rewrites, not user removal', async () => {
+ const w = await seedUniverseWithCharacters([
+ { name: 'Alex', physicalDescription: 'jacket', locked: true },
+ ]);
+ const target = w.characters[0];
+ const { universe } = await canonSvc.removeCanonEntry(w.id, 'character', target.id);
+ expect(universe.characters).toEqual([]);
+ });
+
+ it('removes from the places and objects buckets too', async () => {
+ const seeded = await seedUniverseWithCharacters([]);
+ const w = await svc.updateUniverse(seeded.id, {
+ places: [{ name: 'The Vault', slugline: 'INT. THE VAULT', description: 'a room' }],
+ objects: [{ name: 'The Key', description: 'brass' }],
+ });
+ const afterPlace = await canonSvc.removeCanonEntry(w.id, 'place', w.places[0].id);
+ expect(afterPlace.universe.places).toEqual([]);
+ expect(afterPlace.universe.objects).toHaveLength(1);
+ const afterObject = await canonSvc.removeCanonEntry(w.id, 'object', w.objects[0].id);
+ expect(afterObject.universe.objects).toEqual([]);
+ });
+
+ it('rejects unknown kind with a 400-coded ServerError', async () => {
+ const w = await seedUniverseWithCharacters([{ name: 'Alex', physicalDescription: 'jacket' }]);
+ await expect(
+ canonSvc.removeCanonEntry(w.id, 'monster', w.characters[0].id),
+ ).rejects.toMatchObject({ status: 400, code: 'UNIVERSE_CANON_INVALID_KIND' });
+ });
+
+ it('rejects unknown entry with a 404-coded ServerError', async () => {
+ const w = await seedUniverseWithCharacters([{ name: 'Alex', physicalDescription: 'jacket' }]);
+ await expect(
+ canonSvc.removeCanonEntry(w.id, 'character', 'chr-not-real'),
+ ).rejects.toMatchObject({ status: 404, code: 'UNIVERSE_CANON_NOT_FOUND' });
+ });
+});
+
describe('universeCanon — applyCanonImageCorrection', () => {
it('overwrites the descriptor field and pins the image as primaryImageRef', async () => {
const w = await seedUniverseWithCharacters([