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(catalog-sync): friendlify legacy universe tags on inbound sync

[._.]/ Adam Eivy4078ce241dd3
diff --git a/server/services/catalogSync.js b/server/services/catalogSync.js
index 7a7e4217e8..94f0a8ceb1 100644
--- a/server/services/catalogSync.js
+++ b/server/services/catalogSync.js
@@ -44,8 +44,11 @@ import {
upsertRelationFromPeer,
upsertTagFromPeer,
upsertMediaFromPeer,
+ updateIngredient,
} from './catalogDB.js';
import { compareSchemaVersions, PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';
+import { friendlifyUniverseTags, LEGACY_UNIVERSE_MARKER_TAG } from '../lib/catalogUniverseTags.js';
+import { canonicalTagKey } from '../lib/catalogTypes.js';
const CURSOR_KEYS = ['scraps', 'ingredients', 'sources', 'refs', 'relations', 'tags', 'media'];
@@ -183,6 +186,40 @@ export async function applyRemoteChanges(envelope = {}) {
}
};
+ // Legacy universe tags (`from-universe` + `universe:<id>`) friendlify on
+ // inbound sync: an older peer that syncs an ingredient AFTER our one-time boot
+ // repair (repairUniverseTags.js) already ran would otherwise reintroduce the
+ // raw machine tags via LWW, and the boot repair's marker means it never runs
+ // again to clean them up. Rewriting them to the friendly universe NAME here
+ // makes the repair self-heal on every sync instead of only at boot. The
+ // universe name map is built lazily — and only when a row actually carries the
+ // marker — so an envelope with no legacy rows never issues the universe query.
+ let universeNameMap = null;
+ const ensureUniverseNameMap = async () => {
+ if (universeNameMap) return universeNameMap;
+ const { listUniverses } = await import('./universeBuilder.js');
+ const universes = await listUniverses({ includeDeleted: true });
+ universeNameMap = new Map();
+ for (const u of universes) {
+ if (u?.id && typeof u.name === 'string' && u.name.trim()) {
+ universeNameMap.set(u.id, u.name.trim());
+ }
+ }
+ return universeNameMap;
+ };
+ const friendlifyIngredientTagsOnSync = async (ing, res) => {
+ if (!res?.applied) return; // LWW skip → local row is newer, leave it alone
+ const hasMarker = Array.isArray(ing.tags) && ing.tags.some(
+ (t) => typeof t === 'string' && t.trim().toLowerCase() === LEGACY_UNIVERSE_MARKER_TAG);
+ if (!hasMarker) return;
+ const map = await ensureUniverseNameMap();
+ const { tags, changed } = friendlifyUniverseTags(ing.tags, (id) => map.get(id) || null, canonicalTagKey);
+ if (!changed) return;
+ // source: 'sync' keeps the rewrite out of user-facing revision-diff noise,
+ // matching the boot repair (repairUniverseTags.js).
+ await updateIngredient(ing.id, { tags }, { source: 'sync', actor: 'universe-tag-repair-on-sync' });
+ };
+
// Tags first — they carry a `parent_id` self-FK (handled by the parent-less
// retry in upsertTagFromPeer) and are referenced by the freeform tag arrays
// on ingredients, so we want the canonical rows present before the ingredient
@@ -202,7 +239,7 @@ export async function applyRemoteChanges(envelope = {}) {
await applyKind({
items: envelope.ingredients, upsertFn: upsertIngredientFromPeer, tally: stats.ingredients, lww: true,
- errLabel: 'ingredient', idFor: (i) => i?.id,
+ errLabel: 'ingredient', idFor: (i) => i?.id, onApplied: friendlifyIngredientTagsOnSync,
});
await applyKind({
diff --git a/server/services/catalogSync.test.js b/server/services/catalogSync.test.js
index 60d626b5bb..088bc7f669 100644
--- a/server/services/catalogSync.test.js
+++ b/server/services/catalogSync.test.js
@@ -28,6 +28,7 @@ vi.mock('./catalogDB.js', () => ({
upsertRelationFromPeer: vi.fn(),
upsertTagFromPeer: vi.fn(),
upsertMediaFromPeer: vi.fn(),
+ updateIngredient: vi.fn(),
}));
vi.mock('../lib/schemaVersions.js', async () => {
@@ -35,7 +36,15 @@ vi.mock('../lib/schemaVersions.js', async () => {
return actual;
});
+// universeBuilder is dynamically imported by the friendlify-on-sync path; mock
+// it so the legacy-universe-tag tests resolve names without a Postgres-backed
+// listUniverses. Default to no universes; tests override per-case.
+vi.mock('./universeBuilder.js', () => ({
+ listUniverses: vi.fn(async () => []),
+}));
+
const catalogDB = await import('./catalogDB.js');
+const universeBuilder = await import('./universeBuilder.js');
const {
applyRemoteChanges,
getChangesSince,
@@ -354,3 +363,92 @@ describe('countAppliedFromStats', () => {
})).toBe(1);
});
});
+
+describe('applyRemoteChanges — legacy universe tag friendlify on inbound sync', () => {
+ const ingredient = (tags) => ({
+ id: 'i-hero', type: 'character', name: 'Hero', tags, createdAt: 't', updatedAt: 't',
+ });
+
+ it('rewrites legacy machine tags to the friendly universe name when applied', async () => {
+ catalogDB.upsertIngredientFromPeer.mockResolvedValueOnce({ applied: true, isInsert: true });
+ universeBuilder.listUniverses.mockResolvedValueOnce([{ id: 'u-1', name: 'My Universe' }]);
+
+ const stats = await applyRemoteChanges({
+ ingredients: [ingredient(['hero', 'from-universe', 'universe:u-1'])],
+ });
+
+ expect(stats.ingredients.inserted).toBe(1);
+ expect(catalogDB.updateIngredient).toHaveBeenCalledTimes(1);
+ expect(catalogDB.updateIngredient).toHaveBeenCalledWith(
+ 'i-hero',
+ { tags: ['hero', 'My Universe'] },
+ { source: 'sync', actor: 'universe-tag-repair-on-sync' },
+ );
+ expect(stats.errors).toHaveLength(0);
+ });
+
+ it('leaves an all-unresolvable universe row untouched (no UPDATE) so a later sync can retry', async () => {
+ catalogDB.upsertIngredientFromPeer.mockResolvedValueOnce({ applied: true, isInsert: true });
+ universeBuilder.listUniverses.mockResolvedValueOnce([]); // u-2 not present locally
+
+ await applyRemoteChanges({
+ ingredients: [ingredient(['hero', 'from-universe', 'universe:u-2'])],
+ });
+
+ // friendlifyUniverseTags returns changed=false when EVERY id is unresolvable
+ // (it keeps the marker + id tag flagged for a future retry rather than
+ // burning a no-op write), so no UPDATE fires this pass.
+ expect(catalogDB.updateIngredient).not.toHaveBeenCalled();
+ });
+
+ it('friendlifies the resolvable ids and keeps the marker when only some ids resolve', async () => {
+ catalogDB.upsertIngredientFromPeer.mockResolvedValueOnce({ applied: true, isInsert: true });
+ universeBuilder.listUniverses.mockResolvedValueOnce([{ id: 'u-1', name: 'My Universe' }]);
+
+ await applyRemoteChanges({
+ ingredients: [ingredient(['hero', 'from-universe', 'universe:u-1', 'universe:u-2'])],
+ });
+
+ expect(catalogDB.updateIngredient).toHaveBeenCalledTimes(1);
+ const [, patch] = catalogDB.updateIngredient.mock.calls[0];
+ expect(patch.tags).toContain('My Universe'); // u-1 resolved → friendly name
+ expect(patch.tags).toContain('universe:u-2'); // u-2 unresolved → id kept
+ expect(patch.tags).toContain('from-universe'); // marker kept (an id still unresolved)
+ });
+
+ it('leaves a user-supplied universe:* tag untouched when there is no marker', async () => {
+ catalogDB.upsertIngredientFromPeer.mockResolvedValueOnce({ applied: true, isInsert: true });
+
+ await applyRemoteChanges({
+ ingredients: [ingredient(['hero', 'universe:marvel'])], // thematic user tag, no marker
+ });
+
+ expect(catalogDB.updateIngredient).not.toHaveBeenCalled();
+ expect(universeBuilder.listUniverses).not.toHaveBeenCalled(); // never built the map
+ });
+
+ it('does NOT friendlify when the ingredient upsert was an LWW skip', async () => {
+ catalogDB.upsertIngredientFromPeer.mockResolvedValueOnce({ applied: false }); // local newer
+
+ await applyRemoteChanges({
+ ingredients: [ingredient(['hero', 'from-universe', 'universe:u-1'])],
+ });
+
+ expect(catalogDB.updateIngredient).not.toHaveBeenCalled();
+ });
+
+ it('isolates a friendlify failure as a post-apply error, not an ingredient failure', async () => {
+ catalogDB.upsertIngredientFromPeer.mockResolvedValueOnce({ applied: true, isInsert: true });
+ universeBuilder.listUniverses.mockResolvedValueOnce([{ id: 'u-1', name: 'My Universe' }]);
+ catalogDB.updateIngredient.mockRejectedValueOnce(new Error('write failed'));
+
+ const stats = await applyRemoteChanges({
+ ingredients: [ingredient(['hero', 'from-universe', 'universe:u-1'])],
+ });
+
+ expect(stats.ingredients.inserted).toBe(1); // the upsert itself succeeded
+ expect(stats.ingredients.failed).toBe(0);
+ expect(stats.errors).toHaveLength(1);
+ expect(stats.errors[0].kind).toBe('ingredient-postapply');
+ });
+});