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

federate user-type edits and deletes correctly (LWW timestamps + delete tombstones)

[._.]/ Adam Eivy439ad200ef02
diff --git a/client/src/lib/catalogTypes.js b/client/src/lib/catalogTypes.js
index 1d43bda509..7da31dad77 100644
--- a/client/src/lib/catalogTypes.js
+++ b/client/src/lib/catalogTypes.js
@@ -303,10 +303,16 @@ export const CATALOG_BADGE_BY_ID = Object.freeze(
* non-empty key wins), trimmed + ellipsised to `max` chars. When `typeId` is
* unknown/absent, falls back to a broad union of every type's keys so a row of
* unknown type still renders a snippet.
+ *
+ * `resolveType` (optional) lets a caller pass the MERGED registry resolver
+ * (`useCatalogTypes().getType`) so a user-defined type's custom
+ * `snippetFallbackKeys` (e.g. a `creed` key) are honored — the static `BY_ID`
+ * only knows the built-ins. Falls back to the static lookup when omitted.
*/
-export function payloadSnippet(payload, typeId, max = 120) {
+export function payloadSnippet(payload, typeId, max = 120, resolveType = null) {
if (!payload || typeof payload !== 'object') return '';
- const keys = BY_ID[typeId]?.snippetFallbackKeys || UNION_SNIPPET_KEYS;
+ const typeDef = (resolveType && resolveType(typeId)) || BY_ID[typeId];
+ const keys = typeDef?.snippetFallbackKeys || UNION_SNIPPET_KEYS;
let raw = '';
for (const k of keys) {
if (payload[k]) { raw = payload[k]; break; }
diff --git a/client/src/pages/Catalog.jsx b/client/src/pages/Catalog.jsx
index 6a40602bca..53aa18371a 100644
--- a/client/src/pages/Catalog.jsx
+++ b/client/src/pages/Catalog.jsx
@@ -332,8 +332,8 @@ export default function Catalog() {
</span>
))}
</span>
- {payloadSnippet(it.payload, it.type) ? (
- <span className="text-xs text-gray-400 line-clamp-3">{payloadSnippet(it.payload, it.type)}</span>
+ {payloadSnippet(it.payload, it.type, 120, getType) ? (
+ <span className="text-xs text-gray-400 line-clamp-3">{payloadSnippet(it.payload, it.type, 120, getType)}</span>
) : null}
</Link>
<div className="absolute top-2 right-2">
diff --git a/server/lib/catalogTypes.js b/server/lib/catalogTypes.js
index ce36e952eb..3f13dac2a1 100644
--- a/server/lib/catalogTypes.js
+++ b/server/lib/catalogTypes.js
@@ -275,14 +275,17 @@ let activeUserTypes = [];
* Replace the active user-type set from a settings `catalogUserTypes` array.
* Called at boot (after settings load) and on every settings-update event so
* the in-process registry tracks the persisted definitions without a restart.
- * Skips entries that fail to normalize, collide with a system id, or duplicate
- * an earlier user id.
+ * Skips entries that fail to normalize, collide with a system id, duplicate an
+ * earlier user id, or carry a `deletedAt` tombstone (a soft-deleted type is
+ * retained in the persisted slice so the deletion federates, but it must not
+ * appear in the active registry).
*/
export function setUserCatalogTypes(list = []) {
const taken = new Set();
const out = [];
const seen = new Set();
for (const raw of Array.isArray(list) ? list : []) {
+ if (raw?.deletedAt) continue; // tombstone — persisted but not active
const normalized = normalizeUserType(raw, taken);
if (!normalized) continue;
if (SYSTEM_TYPE_IDS.has(normalized.id) || seen.has(normalized.id)) continue;
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index 5fbd9cc117..cc5fe29fe8 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -100,6 +100,16 @@ export const catalogUserTypeSchema = z.object({
label: z.string().trim().min(1).max(80),
primaryContentKey: userTypeIdentifier,
fields: z.array(userTypeField).max(40),
+ // Mutation timestamp — drives the cross-peer LWW merge (a newer mutation
+ // wins). Stamped server-side on every create/edit; clients don't send it.
+ updatedAt: z.string().datetime().optional(),
+ // Soft-delete tombstone. A deleted user type is KEPT in the slice with
+ // `deletedAt` set rather than physically removed, so the deletion FEDERATES
+ // to peers instead of a peer resurrecting it on the next sync. Filtered out
+ // of the active registry. LWW compares the later of {updatedAt, deletedAt}:
+ // a delete newer than a peer's edit wins, and an edit newer than the delete
+ // revives the type.
+ deletedAt: z.string().datetime().nullable().optional(),
}).strict();
// The whole `catalogUserTypes` settings slice: ≤64 user types, unique ids, and
@@ -509,10 +519,13 @@ export const catalogSyncMediaSchema = z.object({
// drives the LWW window; absent → treated as createdAt for the comparison.
export const catalogSyncUserTypeSchema = z.object({
id: z.string().min(1).max(32),
- label: z.string().max(80),
+ label: z.string().max(80).optional(), // a pure tombstone may omit label
primaryContentKey: z.string().max(64).optional(),
fields: z.array(z.unknown()).max(40).optional(),
updatedAt: z.string().optional(),
+ // A deletion tombstone rides the wire so a delete federates instead of a
+ // peer resurrecting the type. Null/absent = live.
+ deletedAt: z.string().nullable().optional(),
}).passthrough();
export const catalogSyncEnvelopeSchema = z.object({
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index c4f8edceca..79631872cf 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -730,13 +730,29 @@ router.get('/types', asyncHandler(async (req, res) => {
res.json({ types: getActiveCatalogTypes() });
}));
+// Strip any client-supplied sync-control fields and stamp a fresh server-side
+// `updatedAt` — the LWW federation merge relies on this timestamp being set by
+// the writer, never trusted from the client. Clears any tombstone so a write
+// always revives (an edit newer than a delete wins).
+const stampUserType = (body) => {
+ const { deletedAt: _d, updatedAt: _u, ...rest } = body;
+ return { ...rest, updatedAt: new Date().toISOString(), deletedAt: null };
+};
+
router.post('/types', asyncHandler(async (req, res) => {
const body = validateRequest(catalogUserTypeSchema, req.body);
const current = await readUserTypes();
- if (current.some((t) => t.id === body.id)) {
+ // A LIVE type with this id already exists → conflict. A tombstoned id (or a
+ // fresh id) is fine: POST revives the tombstone / creates anew, replacing the
+ // slot in place so the unique-id invariant holds.
+ const idx = current.findIndex((t) => t.id === body.id);
+ if (idx !== -1 && !current[idx].deletedAt) {
throw new ServerError(`Catalog type "${body.id}" already exists`, { status: 409 });
}
- const next = [...current, body];
+ const stamped = stampUserType(body);
+ const next = idx === -1
+ ? [...current, stamped]
+ : current.map((t, i) => (i === idx ? stamped : t));
// Validate the whole slice (unique-id + system-collision refinements) before
// persisting — a system-id collision (e.g. "character") is rejected here.
validateRequest(catalogUserTypesSettingsSchema, next);
@@ -751,10 +767,11 @@ router.patch('/types/:id', asyncHandler(async (req, res) => {
// full user-type (id is immutable — the path wins over any body id).
const merged = validateRequest(catalogUserTypeSchema, { ...req.body, id: req.params.id });
const current = await readUserTypes();
- const idx = current.findIndex((t) => t.id === req.params.id);
+ // Editing a tombstoned (deleted) type is a 404 — it must be re-created via POST.
+ const idx = current.findIndex((t) => t.id === req.params.id && !t.deletedAt);
if (idx === -1) throw new ServerError(`Catalog type "${req.params.id}" not found`, { status: 404 });
const next = [...current];
- next[idx] = merged;
+ next[idx] = stampUserType(merged);
validateRequest(catalogUserTypesSettingsSchema, next);
await updateSettings({ catalogUserTypes: next });
setUserCatalogTypes(next);
@@ -764,7 +781,7 @@ router.patch('/types/:id', asyncHandler(async (req, res) => {
router.delete('/types/:id', asyncHandler(async (req, res) => {
const current = await readUserTypes();
- const idx = current.findIndex((t) => t.id === req.params.id);
+ const idx = current.findIndex((t) => t.id === req.params.id && !t.deletedAt);
if (idx === -1) throw new ServerError(`Catalog type "${req.params.id}" not found`, { status: 404 });
// Refuse to delete a type that still has ingredients of that type unless the
// caller explicitly forces it (`?force=true`) — otherwise those rows become
@@ -782,7 +799,16 @@ router.delete('/types/:id', asyncHandler(async (req, res) => {
);
}
}
- const next = current.filter((t) => t.id !== req.params.id);
+ // Soft-delete: KEEP the entry with a `deletedAt` tombstone (and a fresh
+ // `updatedAt`) so the deletion federates to peers via the catalogTypes sync
+ // block. A physical removal would let a peer that still has the definition
+ // resurrect it on the next pull. setUserCatalogTypes filters tombstones out
+ // of the active registry, so the type disappears from the UI immediately.
+ const deletedAt = new Date().toISOString();
+ const next = current.map((t, i) => (
+ i === idx ? { ...t, deletedAt, updatedAt: deletedAt } : t
+ ));
+ validateRequest(catalogUserTypesSettingsSchema, next);
await updateSettings({ catalogUserTypes: next });
setUserCatalogTypes(next);
console.log(`🧩 Catalog: deleted user type "${req.params.id}"${force ? ' (forced)' : ''}`);
diff --git a/server/routes/catalogTypes.test.js b/server/routes/catalogTypes.test.js
index 628a640331..25c7ea5957 100644
--- a/server/routes/catalogTypes.test.js
+++ b/server/routes/catalogTypes.test.js
@@ -114,11 +114,16 @@ describe('PATCH /api/catalog/types/:id', () => {
});
describe('DELETE /api/catalog/types/:id', () => {
- it('deletes an unused type', async () => {
+ it('soft-deletes an unused type (tombstone kept so the delete federates, gone from the registry)', async () => {
store = { catalogUserTypes: [{ id: 'faction', label: 'Faction', primaryContentKey: 'creed', fields: [] }] };
const res = await request(makeApp()).delete('/api/catalog/types/faction');
expect(res.status).toBe(200);
- expect(store.catalogUserTypes).toHaveLength(0);
+ // The entry is RETAINED with a deletedAt tombstone (so the deletion syncs
+ // to peers) but no longer appears in the active registry response.
+ expect(store.catalogUserTypes).toHaveLength(1);
+ expect(store.catalogUserTypes[0].deletedAt).toBeTruthy();
+ expect(res.body.types.some((t) => t.id === 'faction')).toBe(false);
+ expect(getActiveCatalogType('faction')).toBeUndefined();
});
it('refuses to delete a type with ingredients (409) unless ?force=true', async () => {
@@ -126,12 +131,31 @@ describe('DELETE /api/catalog/types/:id', () => {
ingredientsForType = [{ id: 'cat-fac-1' }];
const refused = await request(makeApp()).delete('/api/catalog/types/faction');
expect(refused.status).toBe(409);
- // Slice untouched on the refused delete.
+ // Slice untouched on the refused delete (still live, no tombstone).
expect(store.catalogUserTypes).toHaveLength(1);
- // Forced delete drops the definition anyway.
+ expect(store.catalogUserTypes[0].deletedAt).toBeFalsy();
+ // Forced delete tombstones the definition anyway.
const forced = await request(makeApp()).delete('/api/catalog/types/faction?force=true');
expect(forced.status).toBe(200);
- expect(store.catalogUserTypes).toHaveLength(0);
+ expect(store.catalogUserTypes[0].deletedAt).toBeTruthy();
+ expect(forced.body.types.some((t) => t.id === 'faction')).toBe(false);
+ });
+
+ it('404s a DELETE on an already-tombstoned type', async () => {
+ store = { catalogUserTypes: [{ id: 'faction', label: 'Faction', primaryContentKey: 'creed', fields: [], deletedAt: '2026-01-01T00:00:00.000Z' }] };
+ const res = await request(makeApp()).delete('/api/catalog/types/faction');
+ expect(res.status).toBe(404);
+ });
+
+ it('POST revives a tombstoned id (replaces the slot, clears the tombstone)', async () => {
+ store = { catalogUserTypes: [{ id: 'faction', label: 'Old', primaryContentKey: 'creed', fields: [], deletedAt: '2026-01-01T00:00:00.000Z' }] };
+ const res = await request(makeApp())
+ .post('/api/catalog/types')
+ .send({ id: 'faction', label: 'Reborn', primaryContentKey: 'creed', fields: [] });
+ expect(res.status).toBe(201);
+ expect(store.catalogUserTypes).toHaveLength(1);
+ expect(store.catalogUserTypes[0].deletedAt).toBeNull();
+ expect(getActiveCatalogType('faction')?.label).toBe('Reborn');
});
it('404s an unknown id', async () => {
diff --git a/server/services/catalogSync.js b/server/services/catalogSync.js
index 8eda3ccc80..cc8cd876ff 100644
--- a/server/services/catalogSync.js
+++ b/server/services/catalogSync.js
@@ -327,15 +327,24 @@ export async function applyUserTypesFromPeer(incoming = []) {
const byId = new Map(local.map((t) => [t.id, t]));
let applied = 0;
let skipped = 0;
- const updatedOf = (t) => (typeof t?.updatedAt === 'string' ? t.updatedAt : '');
+ // The LWW clock is the LATER of {updatedAt, deletedAt} — a deletion is a
+ // mutation too, so a delete newer than a peer's edit wins (no resurrection)
+ // and an edit newer than the delete revives. A tombstone the peer sends is
+ // stored verbatim (kept in the slice, filtered out of the active registry by
+ // setUserCatalogTypes) so the deletion keeps federating onward.
+ const clockOf = (t) => {
+ const u = typeof t?.updatedAt === 'string' ? t.updatedAt : '';
+ const d = typeof t?.deletedAt === 'string' ? t.deletedAt : '';
+ return d > u ? d : u;
+ };
for (const peer of incoming) {
const id = typeof peer?.id === 'string' ? peer.id.trim() : '';
// Skip a malformed entry or one colliding with a built-in system id —
// system types always win and are never represented in this slice.
if (!id || INGREDIENT_TYPE_IDS.includes(id)) { skipped++; continue; }
const existing = byId.get(id);
- // LWW on updatedAt: adopt when no local copy, or the peer is at-or-newer.
- if (!existing || updatedOf(peer) >= updatedOf(existing)) {
+ // LWW: adopt when no local copy, or the peer's clock is at-or-newer.
+ if (!existing || clockOf(peer) >= clockOf(existing)) {
byId.set(id, { ...peer, id });
applied++;
} else {
diff --git a/server/services/catalogSync.userTypes.test.js b/server/services/catalogSync.userTypes.test.js
index 59d5c00488..b320a3178b 100644
--- a/server/services/catalogSync.userTypes.test.js
+++ b/server/services/catalogSync.userTypes.test.js
@@ -87,6 +87,33 @@ describe('applyRemoteChanges — catalogTypes LWW merge', () => {
expect(store.catalogUserTypes ?? []).toHaveLength(0);
});
+ it('a peer deletion tombstone wins LWW and does NOT resurrect the type', async () => {
+ // Local has a live type (edited 2026-01-01); peer deleted it (2026-06-01).
+ store = { catalogUserTypes: [{ id: 'faction', label: 'Live', primaryContentKey: 'x', fields: [], updatedAt: '2026-01-01' }] };
+ const stats = await applyRemoteChanges({
+ portosMeta: meta,
+ catalogTypes: [{ id: 'faction', label: 'Live', primaryContentKey: 'x', fields: [], updatedAt: '2026-01-01', deletedAt: '2026-06-01' }],
+ });
+ expect(stats.catalogTypes.applied).toBe(1);
+ // Tombstone RETAINED (the delete keeps federating) but absent from the registry.
+ expect(store.catalogUserTypes).toHaveLength(1);
+ expect(store.catalogUserTypes[0].deletedAt).toBe('2026-06-01');
+ expect(getActiveCatalogType('faction')).toBeUndefined();
+ });
+
+ it('a local edit newer than a peer tombstone keeps the type alive', async () => {
+ store = { catalogUserTypes: [{ id: 'faction', label: 'Reborn', primaryContentKey: 'x', fields: [], updatedAt: '2026-06-01', deletedAt: null }] };
+ setUserCatalogTypes(store.catalogUserTypes);
+ const stats = await applyRemoteChanges({
+ portosMeta: meta,
+ catalogTypes: [{ id: 'faction', label: 'Old', primaryContentKey: 'x', fields: [], updatedAt: '2025-01-01', deletedAt: '2026-01-01' }],
+ });
+ // Peer tombstone (clock 2026-01-01) is older than the local live edit → skipped.
+ expect(stats.catalogTypes.skipped).toBe(1);
+ expect(store.catalogUserTypes[0].deletedAt).toBeFalsy();
+ expect(getActiveCatalogType('faction')?.label).toBe('Reborn');
+ });
+
it('rejects with 412 when the sender is ahead on the catalog schema', async () => {
await expect(applyRemoteChanges({
portosMeta: { schemaVersions: { catalog: PORTOS_SCHEMA_VERSIONS.catalog + 1 } },