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: project catalog restores into universe canon (#7180)

[._.]/ Adam Eivyd121fc106b9c
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index 821561bd68..c0c98e75c1 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -351,6 +351,14 @@ router.post('/ingredients/:id/revisions/:revisionId/restore', asyncHandler(async
);
if (!updated) throw new ServerError('Ingredient not found', { status: 404 });
res.json(updated);
+ // A restore changes the same mirrored name/payload fields as an ordinary
+ // PATCH, so refresh every linked universe after the Catalog write succeeds.
+ // Keep this best-effort and post-response: the restore is already durable,
+ // and a failed universe cache update must not turn it into a failed request
+ // or escape as an unhandled rejection.
+ projectToCanon(req.params.id, updated).catch((err) => {
+ console.error(`🔁 catalog→canon projection failed for ${req.params.id}: ${err.message}`);
+ });
}));
router.delete('/ingredients/:id', asyncHandler(async (req, res) => {
diff --git a/server/routes/catalogParsedBodies.test.js b/server/routes/catalogParsedBodies.test.js
index a6af637650..61f1bfb1a6 100644
--- a/server/routes/catalogParsedBodies.test.js
+++ b/server/routes/catalogParsedBodies.test.js
@@ -14,6 +14,8 @@ import { errorMiddleware } from '../lib/errorHandler.js';
const mocks = vi.hoisted(() => ({
createIngredient: vi.fn(),
getIngredient: vi.fn(),
+ getIngredientRevision: vi.fn(),
+ listRefsForIngredient: vi.fn(),
updateIngredient: vi.fn(),
linkIngredientToRef: vi.fn(),
unlinkIngredientFromRef: vi.fn(),
@@ -22,11 +24,14 @@ const mocks = vi.hoisted(() => ({
embedIngredient: vi.fn(),
embedBatch: vi.fn(),
ingredientEmbedSeed: vi.fn((entry) => entry),
+ updateUniverse: vi.fn(),
}));
vi.mock('../services/catalogDB.js', () => ({
createIngredient: mocks.createIngredient,
getIngredient: mocks.getIngredient,
+ getIngredientRevision: mocks.getIngredientRevision,
+ listRefsForIngredient: mocks.listRefsForIngredient,
updateIngredient: mocks.updateIngredient,
linkIngredientToRef: mocks.linkIngredientToRef,
unlinkIngredientFromRef: mocks.unlinkIngredientFromRef,
@@ -34,7 +39,7 @@ vi.mock('../services/catalogDB.js', () => ({
commitScrap: mocks.commitScrap,
}));
vi.mock('../services/catalogSync.js', () => ({}));
-vi.mock('../services/catalogCanonProjection.js', () => ({ projectToCanon: vi.fn(async () => {}) }));
+vi.mock('../services/universeBuilder.js', () => ({ updateUniverse: mocks.updateUniverse }));
vi.mock('../services/embeddings.js', () => ({
embedIngredient: mocks.embedIngredient,
embedBatch: mocks.embedBatch,
@@ -55,11 +60,14 @@ beforeEach(() => {
vi.clearAllMocks();
mocks.createIngredient.mockImplementation(async (body) => ({ id: 'ing-1', ...body }));
mocks.getIngredient.mockResolvedValue({ id: 'ing-1', name: 'Before', payload: {} });
+ mocks.getIngredientRevision.mockResolvedValue(null);
+ mocks.listRefsForIngredient.mockResolvedValue([]);
mocks.updateIngredient.mockImplementation(async (id, patch) => ({ id, ...patch }));
mocks.getScrap.mockResolvedValue({ id: 'scrap-1' });
mocks.commitScrap.mockResolvedValue([]);
mocks.embedIngredient.mockResolvedValue({});
mocks.embedBatch.mockResolvedValue([]);
+ mocks.updateUniverse.mockResolvedValue(null);
});
describe('Catalog parsed write bodies', () => {
@@ -122,6 +130,115 @@ describe('Catalog parsed write bodies', () => {
);
});
+ it('creates, edits, and restores a linked character through Catalog and universe canon', async () => {
+ let ingredient;
+ let canon = { characters: [] };
+ const revisions = [];
+ const snapshot = (source, actor = null) => revisions.push({
+ id: `rev-${revisions.length + 1}`,
+ ingredientId: ingredient.id,
+ name: ingredient.name,
+ payload: structuredClone(ingredient.payload),
+ tags: [...ingredient.tags],
+ source,
+ actor,
+ });
+ mocks.createIngredient.mockImplementation(async (body) => {
+ ingredient = { id: 'ing-1', ...body, updatedAt: '2026-09-12T00:00:00.000Z' };
+ snapshot('user');
+ return ingredient;
+ });
+ mocks.linkIngredientToRef.mockImplementation(async () => {
+ canon.characters = [{
+ id: 'canon-1', ingredientId: ingredient.id, name: ingredient.name,
+ ...ingredient.payload, createdAt: '2026-09-12T00:00:00.000Z',
+ }];
+ });
+ mocks.listRefsForIngredient.mockResolvedValue([
+ { refKind: 'universe', refId: 'universe-1' },
+ ]);
+ mocks.updateIngredient.mockImplementation(async (id, patch, context = {}) => {
+ ingredient = { ...ingredient, ...patch, id, updatedAt: new Date().toISOString() };
+ snapshot(context.source || 'user', context.actor);
+ return ingredient;
+ });
+ mocks.getIngredientRevision.mockImplementation(async (id) => revisions.find((r) => r.id === id));
+ mocks.updateUniverse.mockImplementation(async (_id, mutator) => {
+ const patch = mutator(canon);
+ if (!patch) return null;
+ canon = { ...canon, ...patch };
+ return canon;
+ });
+
+ const created = await request(makeApp()).post('/api/catalog/ingredients').send({
+ type: 'character', name: 'Earlier Name',
+ payload: { schemaVersion: 0, description: 'Earlier description' },
+ tags: ['earlier'],
+ });
+ expect(created.status).toBe(201);
+ await request(makeApp()).post('/api/catalog/ingredients/ing-1/link').send({
+ refKind: 'universe', refId: 'universe-1', role: 'canon-character',
+ });
+ const edited = await request(makeApp()).patch('/api/catalog/ingredients/ing-1').send({
+ name: 'Newer Name', payload: { schemaVersion: 1, description: 'Newer description', staleField: 'remove' },
+ });
+ expect(edited.status).toBe(200);
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(canon.characters[0]).toMatchObject({ name: 'Newer Name', staleField: 'remove' });
+
+ const restored = await request(makeApp())
+ .post('/api/catalog/ingredients/ing-1/revisions/rev-1/restore')
+ .send({ source: 'user', actor: ' editor ' });
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(restored.status).toBe(200);
+ expect(restored.body.payload).toEqual({ schemaVersion: 0, description: 'Earlier description' });
+ expect(canon.characters[0]).toMatchObject({
+ id: 'canon-1', ingredientId: 'ing-1', name: 'Earlier Name',
+ description: 'Earlier description', createdAt: '2026-09-12T00:00:00.000Z',
+ });
+ expect(canon.characters[0]).not.toHaveProperty('staleField');
+ expect(revisions).toHaveLength(3);
+ expect(revisions.at(-1)).toMatchObject({
+ ingredientId: 'ing-1', name: 'Earlier Name',
+ payload: { schemaVersion: 0, description: 'Earlier description' },
+ source: 'user', actor: 'editor',
+ });
+ });
+
+ it('does not write or project a missing or wrong-owner revision', async () => {
+ for (const revision of [null, { id: 'rev-1', ingredientId: 'ing-other' }]) {
+ vi.clearAllMocks();
+ mocks.getIngredientRevision.mockResolvedValue(revision);
+
+ const response = await request(makeApp())
+ .post('/api/catalog/ingredients/ing-1/revisions/rev-1/restore')
+ .send({});
+
+ expect(response.status).toBe(404);
+ expect(mocks.updateIngredient).not.toHaveBeenCalled();
+ expect(mocks.listRefsForIngredient).not.toHaveBeenCalled();
+ }
+ });
+
+ it('keeps a completed restore successful when canon projection rejects', async () => {
+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});
+ mocks.getIngredientRevision.mockResolvedValue({
+ id: 'rev-1', ingredientId: 'ing-1', name: 'Earlier', payload: { schemaVersion: 1 }, tags: [],
+ });
+ mocks.updateIngredient.mockResolvedValue({ id: 'ing-1', name: 'Earlier', payload: { schemaVersion: 1 } });
+ mocks.listRefsForIngredient.mockRejectedValue(new Error('universe lookup failed'));
+
+ const response = await request(makeApp())
+ .post('/api/catalog/ingredients/ing-1/revisions/rev-1/restore')
+ .send({});
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(response.status).toBe(200);
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('universe lookup failed'));
+ log.mockRestore();
+ });
+
it('embeds and commits the same parsed scrap drafts', async () => {
mocks.embedBatch.mockResolvedValue([{ embedding: null, model: null }]);
const response = await request(makeApp())
diff --git a/server/services/catalogCanonProjection.js b/server/services/catalogCanonProjection.js
index a37ecf2573..7cfeb33b5b 100644
--- a/server/services/catalogCanonProjection.js
+++ b/server/services/catalogCanonProjection.js
@@ -106,8 +106,11 @@ export async function projectToCanon(ingredientId, updatedIngredient, deps = {})
for (const universeId of universeIds) {
stats.universes++;
- // Mutator form: merge the catalog payload into every embedded entry that
- // carries this ingredientId, across all canon arrays. `silent: true`
+ // Mutator form: replace the mirrored payload on every embedded entry that
+ // carries this ingredientId, across all canon arrays. Preserve only the
+ // canon entry's control fields: merging onto the whole entry would retain
+ // fields removed by an edit or revision restore and let stale canon data
+ // leak back into Catalog on the next reverse projection. `silent: true`
// suppresses the per-universe peer-sync fan-out so a catalog edit that
// touches N universes doesn't emit N recordUpdated events. `guardToken`
// threads the originating ingredientId so updateUniverse's synchronous
@@ -121,7 +124,10 @@ export async function projectToCanon(ingredientId, updatedIngredient, deps = {})
patch[arrayKey] = list.map((e) => {
if (e?.ingredientId !== ingredientId) return e;
touched = true;
- return { ...e, ...payload, name, ingredientId, updatedAt };
+ const controlFields = Object.fromEntries(
+ NON_PAYLOAD_KEYS.filter((key) => e[key] !== undefined).map((key) => [key, e[key]]),
+ );
+ return { ...controlFields, ...payload, name, ingredientId, updatedAt };
});
}
return touched ? patch : null;
diff --git a/server/services/catalogCanonProjection.test.js b/server/services/catalogCanonProjection.test.js
index 641a38fdc9..c37e1ac80e 100644
--- a/server/services/catalogCanonProjection.test.js
+++ b/server/services/catalogCanonProjection.test.js
@@ -63,11 +63,18 @@ describe.skipIf(!runDb)('catalogCanonProjection', () => {
await catalogDB.linkIngredientToRef(ing.id, 'universe', uB, 'canon-character');
const seenUniverses = [];
+ const projected = [];
const updateUniverse = vi.fn(async (universeId, mutator) => {
seenUniverses.push(universeId);
// Simulate the embedded entry carrying this ingredientId so the mutator
// produces a patch (returns null otherwise → counted as skipped).
- const patch = mutator({ characters: [{ id: 'e1', ingredientId: ing.id, name: 'old' }] });
+ const patch = mutator({
+ characters: [{
+ id: 'e1', ingredientId: ing.id, name: 'old',
+ createdAt: '2026-01-01T00:00:00.000Z', staleField: 'remove me',
+ }],
+ });
+ projected.push(patch.characters[0]);
return patch; // truthy → counted as "written"
});
@@ -75,6 +82,11 @@ describe.skipIf(!runDb)('catalogCanonProjection', () => {
expect(stats.universes).toBe(2);
expect(stats.written).toBe(2);
expect(seenUniverses.sort()).toEqual([uA, uB].sort());
+ expect(projected[0]).toMatchObject({
+ id: 'e1', ingredientId: ing.id, name: 'Renamed', role: 'Hero',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ });
+ expect(projected[0]).not.toHaveProperty('staleField');
// Guard set drains — no leaked in-flight token.
expect(_inFlightSize()).toBe(0);
});