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: friendlify legacy universe tags before the peer upsert instead of a second UPDATE (#3942)

[._.]/ Adam Eivyc2ad19061aa4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7c566d46e7..f756d9246b 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -79,3 +79,4 @@
- Saving a universe no longer issues one database read per canon entry. `projectToCatalog` — which runs synchronously inside `updateUniverse` to keep each catalog row in step with its embedded character/place/object entry — called `getIngredient` once per entry just to compare timestamps, so a universe with 50 canon items cost 50 single-row `SELECT`s before the first write, on the request the user is waiting on. The freshness lookup is now a single batched query (`getIngredientTimestamps`, `WHERE id = ANY($1)`, two columns rather than the whole jsonb row), with the loop-break guard applied before the batch so a guarded ingredient is never fetched at all. The LWW rule is unchanged (an entry at least as fresh as its row wins; an older one is skipped), missing rows still count as skipped instead of being confused with stale ones, and a per-entry write failure is still logged and skipped without aborting the rest of the pass.
- Unsaved Quota Burn edits are no longer lost silently when you navigate away. The page has no Save button — edits persist on a 500ms trailing edge — and the dismount flush that catches everything typed inside that window swallowed its own failure with `.catch(() => {})`, so leaving the page while the header still read "Saving changes…" dropped a pasted work prompt or a changed interval for good, with no toast and nothing on screen having said so. A failed flush now raises an error toast naming what happened and keeps the patch in tab-scoped `sessionStorage`; the next visit that successfully reads a plan replays it through the normal save path, so the edits come back on screen AND get re-sent to the server instead of waiting for the user to retype the field. A visit whose own read failed leaves the stash alone for the visit after it, and a stash that is not a patch object is ignored rather than replayed into a 400.
- Clearing a Quota Burn number box no longer discards the edit without saying so. `NumberField` held an uncommitted draft so an empty box could not commit `Number('') === 0` into a 400, but on blur it simply dropped the draft and snapped the input back to the stored value — a user who cleared "Check every (minutes)" or "Reserve (%)" and clicked away saw the old number reappear with nothing on screen explaining why. An empty, non-numeric or out-of-range draft now stays on screen next to an inline error naming what the field accepts ("Must be between 5 and 720"), wired up with `aria-invalid`/`aria-describedby`; the error clears the moment the draft is committable again, and only a committable draft is released back to the stored value. Out-of-range numbers are also no longer committed mid-typing, so a 721-minute interval is caught in the field rather than by the server.
+- Applying an inbound catalog sync envelope no longer writes each legacy-tagged ingredient twice. The friendlify-on-sync repair — which rewrites an older peer's raw `from-universe` / `universe:<id>` tags to the friendly universe name — ran as a follow-up `updateIngredient` after `upsertIngredientFromPeer` had already written the row, so an envelope carrying N such ingredients cost 2N queries and left a redundant `catalog_ingredient_revisions` entry for every one of them. The rewrite now happens on the row before it is upserted, so it lands cleaned in a single write with no extra revision history. Behavior is otherwise unchanged: the universe name map is still built lazily and only once per apply, a row whose universe is not resolvable locally still lands with its machine tags intact for a later pass, an LWW skip still touches nothing, and a failure to build the map is isolated per row (reported as `ingredient-prepare`) with the raw row still applied.
diff --git a/server/services/catalogSync.js b/server/services/catalogSync.js
index 89bde53902..63706f8257 100644
--- a/server/services/catalogSync.js
+++ b/server/services/catalogSync.js
@@ -44,7 +44,6 @@ 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';
@@ -171,11 +170,19 @@ export async function applyRemoteChanges(envelope = {}) {
// malformed row can't abort the batch. Two stats shapes: LWW kinds
// (tags/scraps/ingredients) read `{ applied, isInsert }` from the upsert into
// inserted/updated/skipped; tuple-unique kinds (sources/refs/relations/media)
- // have no result and tally `applied`. `onApplied(item, res)` runs after a
- // successful upsert in its OWN guard, so a post-apply side effect can't be
- // miscounted as an upsert failure.
- const applyKind = async ({ items, upsertFn, tally, lww, errLabel, idFor, onApplied }) => {
- for (const item of items || []) {
+ // have no result and tally `applied`. `prepare(item)` may return a REPLACEMENT
+ // row to upsert (used to clean legacy tags in-place so the row lands in its
+ // final shape in ONE write); `onApplied(item, res)` runs after a successful
+ // upsert. Both run in their OWN guard, so a hook failure can't be miscounted
+ // as an upsert failure — a failed `prepare` falls back to the raw row rather
+ // than dropping it.
+ const applyKind = async ({ items, upsertFn, tally, lww, errLabel, idFor, prepare, onApplied }) => {
+ for (const raw of items || []) {
+ let item = raw;
+ if (prepare) {
+ try { item = (await prepare(raw)) || raw; }
+ catch (err) { recordFailure(`${errLabel}-prepare`, idFor(raw), err); }
+ }
let res;
try {
res = await upsertFn(item);
@@ -210,6 +217,13 @@ export async function applyRemoteChanges(envelope = {}) {
// boot repair, whichever fires first. 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.
+ //
+ // The rewrite happens BEFORE the upsert (not as a follow-up UPDATE) so the row
+ // is written once, in its cleaned state: an envelope of N legacy rows costs N
+ // queries instead of 2N and leaves no duplicate `catalog_ingredient_revisions`
+ // entry per synced row. An LWW skip needs no special case — the local row is
+ // newer, so the (rewritten) peer row is discarded by the upsert's WHERE guard
+ // exactly as the raw one would have been.
let universeNameMap = null;
const ensureUniverseNameMap = async () => {
if (universeNameMap) return universeNameMap;
@@ -223,17 +237,14 @@ export async function applyRemoteChanges(envelope = {}) {
}
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(
+ const friendlifyIngredientTagsBeforeApply = async (ing) => {
+ const hasMarker = Array.isArray(ing?.tags) && ing.tags.some(
(t) => typeof t === 'string' && t.trim().toLowerCase() === LEGACY_UNIVERSE_MARKER_TAG);
- if (!hasMarker) return;
+ if (!hasMarker) return ing;
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' });
+ if (!changed) return ing; // nothing resolvable yet — keep the machine tags for a later pass
+ return { ...ing, tags };
};
// Tags first — they carry a `parent_id` self-FK (handled by the parent-less
@@ -266,7 +277,7 @@ export async function applyRemoteChanges(envelope = {}) {
await applyKind({
items: envelope.ingredients, upsertFn: upsertIngredientFromPeer, tally: stats.ingredients, lww: true,
- errLabel: 'ingredient', idFor: (i) => i?.id, onApplied: friendlifyIngredientTagsOnSync,
+ errLabel: 'ingredient', idFor: (i) => i?.id, prepare: friendlifyIngredientTagsBeforeApply,
});
await applyKind({
diff --git a/server/services/catalogSync.test.js b/server/services/catalogSync.test.js
index 23f46d37d5..ff1af6d041 100644
--- a/server/services/catalogSync.test.js
+++ b/server/services/catalogSync.test.js
@@ -390,7 +390,9 @@ describe('applyRemoteChanges — legacy universe tag friendlify on inbound sync'
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 () => {
+ const tagsUpserted = (call = 0) => catalogDB.upsertIngredientFromPeer.mock.calls[call][0].tags;
+
+ it('rewrites legacy machine tags to the friendly universe name in the upsert itself', async () => {
catalogDB.upsertIngredientFromPeer.mockResolvedValueOnce({ applied: true, isInsert: true });
universeBuilder.listUniverses.mockResolvedValueOnce([{ id: 'u-1', name: 'My Universe' }]);
@@ -399,16 +401,26 @@ describe('applyRemoteChanges — legacy universe tag friendlify on inbound sync'
});
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' },
- );
+ // ONE write per row: the cleaned tags ride the upsert, no follow-up UPDATE
+ // (which would double the query count and add a revision row per synced item).
+ expect(catalogDB.upsertIngredientFromPeer).toHaveBeenCalledTimes(1);
+ expect(tagsUpserted()).toEqual(['hero', 'My Universe']);
+ expect(catalogDB.updateIngredient).not.toHaveBeenCalled();
expect(stats.errors).toHaveLength(0);
});
- it('leaves an all-unresolvable universe row untouched (no UPDATE) so a later sync can retry', async () => {
+ it('does not mutate the caller-supplied envelope row when rewriting its tags', async () => {
+ catalogDB.upsertIngredientFromPeer.mockResolvedValueOnce({ applied: true, isInsert: true });
+ universeBuilder.listUniverses.mockResolvedValueOnce([{ id: 'u-1', name: 'My Universe' }]);
+ const row = ingredient(['hero', 'from-universe', 'universe:u-1']);
+
+ await applyRemoteChanges({ ingredients: [row] });
+
+ expect(row.tags).toEqual(['hero', 'from-universe', 'universe:u-1']);
+ expect(tagsUpserted()).toEqual(['hero', 'My Universe']);
+ });
+
+ it('upserts an all-unresolvable universe row verbatim so a later sync can retry', async () => {
catalogDB.upsertIngredientFromPeer.mockResolvedValueOnce({ applied: true, isInsert: true });
universeBuilder.listUniverses.mockResolvedValueOnce([]); // u-2 not present locally
@@ -417,8 +429,9 @@ describe('applyRemoteChanges — legacy universe tag friendlify on inbound sync'
});
// 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.
+ // (it keeps the marker + id tag flagged for a future retry), so the row lands
+ // with its machine tags intact.
+ expect(tagsUpserted()).toEqual(['hero', 'from-universe', 'universe:u-2']);
expect(catalogDB.updateIngredient).not.toHaveBeenCalled();
});
@@ -430,11 +443,10 @@ describe('applyRemoteChanges — legacy universe tag friendlify on inbound sync'
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)
+ const tags = tagsUpserted();
+ expect(tags).toContain('My Universe'); // u-1 resolved → friendly name
+ expect(tags).toContain('universe:u-2'); // u-2 unresolved → id kept
+ expect(tags).toContain('from-universe'); // marker kept (an id still unresolved)
});
it('leaves a user-supplied universe:* tag untouched when there is no marker', async () => {
@@ -444,32 +456,55 @@ describe('applyRemoteChanges — legacy universe tag friendlify on inbound sync'
ingredients: [ingredient(['hero', 'universe:marvel'])], // thematic user tag, no marker
});
+ expect(tagsUpserted()).toEqual(['hero', 'universe:marvel']);
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 () => {
+ it('issues no extra write when the ingredient upsert is an LWW skip', async () => {
catalogDB.upsertIngredientFromPeer.mockResolvedValueOnce({ applied: false }); // local newer
+ universeBuilder.listUniverses.mockResolvedValueOnce([{ id: 'u-1', name: 'My Universe' }]);
- await applyRemoteChanges({
+ const stats = await applyRemoteChanges({
ingredients: [ingredient(['hero', 'from-universe', 'universe:u-1'])],
});
+ // The upsert's own LWW WHERE guard discards the rewritten row exactly as it
+ // would the raw one — so a skip costs one query and touches nothing.
+ expect(stats.ingredients.skipped).toBe(1);
+ expect(catalogDB.upsertIngredientFromPeer).toHaveBeenCalledTimes(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 });
+ it('builds the universe name map ONCE across a multi-row envelope', async () => {
+ catalogDB.upsertIngredientFromPeer.mockResolvedValue({ applied: true, isInsert: true });
universeBuilder.listUniverses.mockResolvedValueOnce([{ id: 'u-1', name: 'My Universe' }]);
- catalogDB.updateIngredient.mockRejectedValueOnce(new Error('write failed'));
+
+ await applyRemoteChanges({
+ ingredients: [
+ { ...ingredient(['from-universe', 'universe:u-1']), id: 'i-1' },
+ { ...ingredient(['from-universe', 'universe:u-1']), id: 'i-2' },
+ ],
+ });
+
+ expect(universeBuilder.listUniverses).toHaveBeenCalledTimes(1);
+ expect(catalogDB.upsertIngredientFromPeer).toHaveBeenCalledTimes(2);
+ expect(tagsUpserted(0)).toEqual(['My Universe']);
+ expect(tagsUpserted(1)).toEqual(['My Universe']);
+ });
+
+ it('isolates a friendlify failure as a prepare error and still applies the raw row', async () => {
+ catalogDB.upsertIngredientFromPeer.mockResolvedValueOnce({ applied: true, isInsert: true });
+ universeBuilder.listUniverses.mockRejectedValueOnce(new Error('universe read 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.inserted).toBe(1); // the upsert still ran, with raw tags
expect(stats.ingredients.failed).toBe(0);
+ expect(tagsUpserted()).toEqual(['hero', 'from-universe', 'universe:u-1']);
expect(stats.errors).toHaveLength(1);
- expect(stats.errors[0].kind).toBe('ingredient-postapply');
+ expect(stats.errors[0].kind).toBe('ingredient-prepare');
});
});