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

add catalog ingredient revision history with inline diff and restore

[._.]/ Adam Eivye17f10491f9c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 16a88bb2c6..b520a3a88c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -13,6 +13,8 @@
## Added
+- **[catalog-ingredient-revisions] Catalog ingredients now keep an edit history with inline diff + restore.** Every time a catalog ingredient's name, payload, or tags change — a manual detail-page save, an ingest commit, or a future AI refinement pass — a revision row is recorded, and a new "Revision history" panel on the ingredient detail page lists them newest-first with a source badge (user / extract / refine / sync) and a relative timestamp. Expand any revision to see a field-by-field diff against the current saved state, and click "Restore" on an older revision to roll back (the restore is itself recorded as a new revision, so it's auditable and reversible). Backed by a new append-only `catalog_ingredient_revisions` Postgres table (foreign-keyed to `catalog_ingredients` with ON DELETE CASCADE); retention is capped at the most recent 50 revisions per ingredient (configurable via the `CATALOG_REVISION_RETENTION` env var) so history can't grow unbounded from rapid edits. The history is local audit data — it is intentionally NOT federated (the synced ingredient row already last-write-wins-merges the latest state across peers), so the catalog sync wire version is unchanged.
+
- **[catalog-ingredient-relations] Catalog ingredients can now link to each other — the catalog is a graph, not a flat list.** A new "Relations" panel on each ingredient detail page lets you connect one ingredient to another via the existing Ingredient Picker — a character to the place they *live in*, a scene to the cast that *appears in* it, a concept *referenced by* an object, and so on (kinds: appears-in, lives-in, created-by, parent-of, variant-of, references, related-to). Edges are directed: the panel shows both outbound relations (this ingredient → other, editable here) and inbound ones (other → this ingredient, read-only because the other end owns them, rendered with the inverse label). Backed by a new `catalog_ingredient_relations` Postgres table with both ids foreign-keyed to `catalog_ingredients` (ON DELETE CASCADE) and soft-delete tombstones from day one, so unlinks propagate to federated peers instead of silently vanishing. The edges ride the existing catalog sync envelope as a new `relations` block (`PORTOS_SCHEMA_VERSIONS.catalog` bumped to 4 — a peer on an older catalog schema gets a clean 412 rather than silently dropping every relation). `POST`/`DELETE /api/catalog/ingredients/:id/relations` and `GET …/relations` are Zod-validated; self-edges are rejected.
- **[catalog-pipeline-series-cast] "Cast (from Catalog)" panel on Series, Issue, and Writers Room pages.** A new reusable panel surfaces every catalog ingredient linked to the active series / issue / work bible — drawn from the existing `catalog_ingredient_refs` table — and lets you attach more via the existing Ingredient Picker or unlink with a click. Series records carry no embedded `characters[]` array, so the cast is purely additive and replicates through the existing catalog sync. The panel lives in the Series bible sidebar above "Canon", at the top of the active stage scroll on Issue (visible across every stage tab), and above the work editor in Writers Room when a work is selected.
- **[catalog-bulk-import] Bulk-ingest endpoint for the Catalog.** A new "Bulk Import" panel on `/catalog/ingest` accepts JSON, CSV (`type,name,description,tags` header), or simple markdown (`## <Type>: <Name>` headings with paragraph body and optional `tags:` line) and creates ingredients directly — no per-row review screen. Each row is re-validated against the same Zod schema the single-create endpoint uses, so one bad row rolls back the entire batch; vector embeddings run in parallel before the transaction (same as the scrap-commit path), so bulk-imported rows are search-ready immediately rather than waiting for the embeddings backfill. `POST /api/catalog/bulk-import` is Zod-validated (2 MB payload cap), stamps optional `defaults.tags` plus an optional `universe`/`series`/`work`/`issue` ref onto every row in the same transaction, and surfaces parser warnings (e.g. `## Plce: …` typos in markdown that don't match a known type) in the response so users notice typos that would otherwise be silently skipped.
diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsx
index d881583820..1f2bb2c1b3 100644
--- a/client/src/pages/CatalogIngredient.jsx
+++ b/client/src/pages/CatalogIngredient.jsx
@@ -5,9 +5,9 @@
* pipeline series / issues / writers-room). Full-width page; owns its scroll.
*/
-import { useEffect, useState } from 'react';
+import { useCallback, useEffect, useState } from 'react';
import { useNavigate, useParams, Link } from 'react-router-dom';
-import { Sparkles, Save, Trash2, ArrowLeft, Loader2, ExternalLink, Plus, X } from 'lucide-react';
+import { Sparkles, Save, Trash2, ArrowLeft, Loader2, ExternalLink, Plus, X, History, RotateCcw } from 'lucide-react';
import toast from '../components/ui/Toast';
import {
getCatalogIngredient,
@@ -16,10 +16,13 @@ import {
listCatalogIngredientRelations,
linkCatalogIngredientRelation,
unlinkCatalogIngredientRelation,
+ listCatalogIngredientRevisions,
+ restoreCatalogIngredientRevision,
} from '../services/apiCatalog';
import IngredientPicker from '../components/IngredientPicker';
import TagPicker from '../components/TagPicker';
import { getCatalogType, CATALOG_BADGE_BY_ID, RELATION_KINDS, getRelationKind } from '../lib/catalogTypes';
+import { timeAgo } from '../utils/formatters';
// Per-type editor field list + badge color now come from the shared registry
// (`client/src/lib/catalogTypes.js`). Each editor entry is `[key, label, kind]`
@@ -61,6 +64,14 @@ export default function CatalogIngredient() {
// the ingredient record so the panel can refresh independently after add/
// remove without re-fetching the whole detail payload.
const [relations, setRelations] = useState({ outbound: [], inbound: [] });
+ const [revisions, setRevisions] = useState([]);
+
+ const refreshRevisions = useCallback(() => {
+ if (!id) return;
+ listCatalogIngredientRevisions(id, { limit: 50, silent: true })
+ .then((r) => setRevisions(Array.isArray(r?.items) ? r.items : []))
+ .catch(() => { /* history is non-critical — leave the panel empty */ });
+ }, [id]);
useEffect(() => {
let cancelled = false;
@@ -78,6 +89,7 @@ export default function CatalogIngredient() {
setTags(Array.isArray(r.tags) ? r.tags : []);
setPayload(r.payload && typeof r.payload === 'object' ? { ...r.payload } : {});
setLoading(false);
+ refreshRevisions();
})
.catch((err) => {
if (cancelled) return;
@@ -85,7 +97,7 @@ export default function CatalogIngredient() {
navigate('/catalog');
});
return () => { cancelled = true; };
- }, [id, navigate]);
+ }, [id, navigate, refreshRevisions]);
useEffect(() => {
let cancelled = false;
@@ -162,6 +174,22 @@ export default function CatalogIngredient() {
// collapse), so reflect the persisted set back into the chips.
if (Array.isArray(updated.tags)) setTags(updated.tags);
toast.success('Saved');
+ refreshRevisions();
+ };
+
+ const handleRestore = async (revisionId) => {
+ if (!record) return;
+ const updated = await restoreCatalogIngredientRevision(record.id, revisionId, {}, { silent: true })
+ .catch((err) => { toast.error(err?.message || 'Restore failed'); return null; });
+ if (!updated) return;
+ // Re-apply the restored state into the editable form so the page reflects
+ // the rollback without a full reload.
+ setRecord((prev) => ({ ...prev, ...updated }));
+ setName(updated.name || '');
+ setTags(Array.isArray(updated.tags) ? updated.tags : []);
+ setPayload(updated.payload && typeof updated.payload === 'object' ? { ...updated.payload } : {});
+ toast.success('Restored');
+ refreshRevisions();
};
const confirmDelete = async () => {
@@ -287,6 +315,13 @@ export default function CatalogIngredient() {
onAdd={handleAddRelation}
onRemove={handleRemoveRelation}
/>
+
+ <RevisionsPanel
+ revisions={revisions}
+ current={record}
+ fields={fields}
+ onRestore={handleRestore}
+ />
</div>
</section>
);
@@ -443,3 +478,126 @@ function RefsPanel({ refsByKind }) {
</section>
);
}
+
+const SOURCE_BADGE = {
+ user: 'bg-port-accent/20 text-port-accent border-port-accent/40',
+ extract: 'bg-purple-500/20 text-purple-300 border-purple-500/40',
+ refine: 'bg-port-warning/20 text-port-warning border-port-warning/40',
+ sync: 'bg-port-success/20 text-port-success border-port-success/40',
+};
+
+// Build the label set for diffing: the editor fields plus name + tags. Used to
+// render a field-by-field "what changed" diff between a revision and the
+// currently-saved record.
+function diffRevisionAgainstCurrent(revision, current, fields) {
+ const out = [];
+ const curName = current?.name || '';
+ if ((revision.name || '') !== curName) {
+ out.push({ key: '__name', label: 'Name', from: revision.name || '', to: curName });
+ }
+ const curTags = (current?.tags || []).join(', ');
+ const revTags = (revision.tags || []).join(', ');
+ if (revTags !== curTags) {
+ out.push({ key: '__tags', label: 'Tags', from: revTags, to: curTags });
+ }
+ const curPayload = current?.payload || {};
+ const revPayload = revision.payload || {};
+ for (const [key, label] of fields.map(([k, l]) => [k, l])) {
+ const from = revPayload[key] ?? '';
+ const to = curPayload[key] ?? '';
+ if (String(from) !== String(to)) out.push({ key, label, from: String(from), to: String(to) });
+ }
+ return out;
+}
+
+function RevisionsPanel({ revisions, current, fields, onRestore }) {
+ const [openId, setOpenId] = useState(null);
+ const [restoring, setRestoring] = useState(null);
+
+ const list = Array.isArray(revisions) ? revisions : [];
+
+ const handleRestore = async (id) => {
+ setRestoring(id);
+ await onRestore(id);
+ setRestoring(null);
+ };
+
+ return (
+ <section className="bg-port-card border border-port-border rounded-lg p-4">
+ <h2 className="text-sm font-semibold text-white mb-3 flex items-center gap-2">
+ <History size={15} className="text-port-accent" aria-hidden="true" /> Revision history
+ {list.length > 0 && <span className="text-xs text-gray-500 font-normal">({list.length})</span>}
+ </h2>
+ {list.length === 0 ? (
+ <p className="text-xs text-gray-500">No revisions recorded yet.</p>
+ ) : (
+ <ul className="space-y-1.5">
+ {list.map((rev, i) => {
+ const open = openId === rev.id;
+ const isLatest = i === 0;
+ const diff = open ? diffRevisionAgainstCurrent(rev, current, fields) : [];
+ const badge = SOURCE_BADGE[rev.source] || 'bg-gray-500/20 text-gray-300 border-gray-500/40';
+ return (
+ <li key={rev.id} className="border border-port-border rounded bg-port-bg">
+ <div className="flex items-center justify-between gap-2 px-2.5 py-1.5">
+ <button
+ type="button"
+ onClick={() => setOpenId(open ? null : rev.id)}
+ className="flex items-center gap-2 min-w-0 text-left flex-1 hover:opacity-90"
+ aria-expanded={open}
+ >
+ <span className={`text-[10px] uppercase tracking-wider px-1.5 py-0.5 rounded border ${badge}`}>
+ {rev.source}
+ </span>
+ <span className="text-xs text-gray-300 truncate">{rev.name || '(untitled)'}</span>
+ {rev.actor && <span className="text-[10px] text-gray-500 truncate">· {rev.actor}</span>}
+ <span className="text-[10px] text-gray-500 whitespace-nowrap ml-auto">{timeAgo(rev.createdAt)}</span>
+ </button>
+ {!isLatest && (
+ <button
+ type="button"
+ onClick={() => handleRestore(rev.id)}
+ disabled={restoring === rev.id}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-[11px] border border-port-border text-gray-400 hover:text-white disabled:opacity-50"
+ title="Restore this revision"
+ >
+ {restoring === rev.id
+ ? <Loader2 size={11} className="animate-spin" />
+ : <RotateCcw size={11} aria-hidden="true" />} Restore
+ </button>
+ )}
+ {isLatest && (
+ <span className="text-[10px] text-gray-500 px-1 whitespace-nowrap">current</span>
+ )}
+ </div>
+ {open && (
+ <div className="px-2.5 pb-2 pt-0.5 border-t border-port-border">
+ {diff.length === 0 ? (
+ <p className="text-[11px] text-gray-500 mt-1.5">Identical to the current saved state.</p>
+ ) : (
+ <dl className="mt-1.5 space-y-1.5">
+ {diff.map((d) => (
+ <div key={d.key} className="text-[11px]">
+ <dt className="text-gray-500 uppercase tracking-wider text-[9px] mb-0.5">{d.label}</dt>
+ <dd className="grid grid-cols-1 sm:grid-cols-2 gap-1">
+ <span className="px-1.5 py-0.5 rounded bg-port-error/10 text-port-error/90 break-words">
+ {d.from || <em className="text-gray-600">empty</em>}
+ </span>
+ <span className="px-1.5 py-0.5 rounded bg-port-success/10 text-port-success/90 break-words">
+ {d.to || <em className="text-gray-600">empty</em>}
+ </span>
+ </dd>
+ </div>
+ ))}
+ </dl>
+ )}
+ </div>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </section>
+ );
+}
diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.js
index d8ab54c558..585c1d2997 100644
--- a/client/src/services/apiCatalog.js
+++ b/client/src/services/apiCatalog.js
@@ -73,6 +73,20 @@ export const updateCatalogIngredient = (id, patch, options) =>
export const deleteCatalogIngredient = (id, options) =>
request(`/catalog/ingredients/${enc(id)}`, { method: 'DELETE', ...options });
+// --- Revision history ---------------------------------------------------
+
+export const listCatalogIngredientRevisions = (id, { limit, offset, ...options } = {}) => {
+ const params = new URLSearchParams();
+ if (limit) params.set('limit', String(limit));
+ if (offset) params.set('offset', String(offset));
+ return request(`/catalog/ingredients/${enc(id)}/revisions${params.toString() ? `?${params}` : ''}`, options);
+};
+
+export const restoreCatalogIngredientRevision = (id, revisionId, body = {}, options) =>
+ request(`/catalog/ingredients/${enc(id)}/revisions/${enc(revisionId)}/restore`, {
+ method: 'POST', body: JSON.stringify(body), ...options,
+ });
+
// --- Linking (catalog ↔ universe/series/work) ---------------------------
export const linkCatalogIngredient = (id, body, options) =>
diff --git a/server/lib/README.md b/server/lib/README.md
index 6f440ab947..6680410696 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -26,7 +26,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `validation.js` | Catch-all Zod schemas + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`). Most route inputs validate through here. |
| `appleHealthValidation.js` | Apple Health import payloads. |
| `brainValidation.js` | Brain/memory route schemas (search, ingest, edit). |
-| `catalogValidation.js` | Creative ingredients catalog route schemas (scraps, ingredients, links, relations, tags, sync envelope). |
+| `catalogValidation.js` | Creative ingredients catalog route schemas (scraps, ingredients, links, relations, tags, revisions, sync envelope). |
| `digitalTwinValidation.js` | Digital twin document/category schemas. |
| `genomeValidation.js` | Genome upload + search schemas. |
| `identityValidation.js` | Identity section + chronotype + scheduling schemas. |
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index 64f96f3cfd..d58c1997fc 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -61,10 +61,34 @@ export const catalogIngredientCreateSchema = z.object({
tags,
}).strict();
+// Revision-history sources, mirrored from the catalog_ingredient_revisions
+// DB CHECK constraint. The PATCH route accepts an optional `source`/`actor` so
+// AI-driven callers (story-builder refine) can label their edits; a manual
+// detail-page save omits them and the DB layer defaults to 'user'.
+export const REVISION_SOURCES = Object.freeze(['user', 'extract', 'refine', 'sync']);
+const revisionSource = z.enum(REVISION_SOURCES).optional();
+const revisionActor = z.string().trim().min(1).max(120).optional();
+
export const catalogIngredientPatchSchema = z.object({
name: z.string().trim().min(1).max(BIBLE_LIMITS.NAME_MAX).optional(),
payload,
tags,
+ source: revisionSource,
+ actor: revisionActor,
+}).strict();
+
+// /ingredients/:id/revisions — paginated history list. Newest first.
+export const catalogRevisionQuerySchema = z.object({
+ limit: z.coerce.number().int().min(1).max(200).optional(),
+ offset: z.coerce.number().int().min(0).optional(),
+}).strict();
+
+// /ingredients/:id/revisions/:revisionId/restore — re-applies a prior
+// revision's name/payload/tags. Optional `source`/`actor` label the NEW
+// revision the restore itself produces (defaults to 'user').
+export const catalogRevisionRestoreSchema = z.object({
+ source: revisionSource,
+ actor: revisionActor,
}).strict();
export const catalogIngredientQuerySchema = z.object({
diff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.js
index 112236ccb1..602e626d0d 100644
--- a/server/lib/db.catalogDdlParity.test.js
+++ b/server/lib/db.catalogDdlParity.test.js
@@ -30,6 +30,7 @@ const CATALOG_TABLES = [
'catalog_ingredient_refs',
'catalog_ingredient_relations',
'catalog_tags',
+ 'catalog_ingredient_revisions',
];
// Strip line comments + collapse whitespace so column lists compare cleanly.
diff --git a/server/lib/db.js b/server/lib/db.js
index fe46ea083c..810b1ef837 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -272,6 +272,27 @@ export async function ensureSchema() {
`CREATE INDEX IF NOT EXISTS idx_catalog_tags_parent ON catalog_tags (parent_id)`,
`CREATE INDEX IF NOT EXISTS idx_catalog_tags_sync_seq ON catalog_tags (sync_sequence)`,
+ // Append-only revision history for catalog_ingredients (local audit, not
+ // federated). Written by catalogDB.updateIngredient on every content change
+ // + a seed row on create; pruned to the last CATALOG_REVISION_RETENTION per
+ // ingredient at the app layer. No sync_sequence — revisions stay local; the
+ // synced ingredient row already LWW-merges the latest state across peers.
+ // Mirrors the catalog_ingredient_revisions block in init-db.sql (parity is
+ // asserted by db.catalogDdlParity.test.js).
+ `CREATE TABLE IF NOT EXISTS catalog_ingredient_revisions (
+ id TEXT PRIMARY KEY,
+ ingredient_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ payload JSONB NOT NULL DEFAULT '{}'::jsonb,
+ tags TEXT[] DEFAULT '{}',
+ source VARCHAR(16) NOT NULL DEFAULT 'user'
+ CHECK (source IN ('user', 'extract', 'refine', 'sync')),
+ actor VARCHAR(120),
+ created_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_ing_revisions_ingredient
+ ON catalog_ingredient_revisions (ingredient_id, created_at DESC)`,
+
`CREATE OR REPLACE FUNCTION update_catalog_ingredient_timestamp()
RETURNS TRIGGER AS $$
DECLARE
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index 28ae493e46..c85a79da1c 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -23,6 +23,8 @@ import {
catalogMigrationRerunSchema,
catalogBulkImportSchema,
catalogExportQuerySchema,
+ catalogRevisionQuerySchema,
+ catalogRevisionRestoreSchema,
} from '../lib/catalogValidation.js';
import { parseBulkPayload, bundleToMarkdown, toYamlString } from '../lib/catalogBulkParsers.js';
import { embedIngredient, embedBatch, ingredientEmbedSeed } from '../services/embeddings.js';
@@ -117,7 +119,7 @@ router.post('/scraps/:id/commit', asyncHandler(async (req, res) => {
tags: draft.tags || [],
embedding: e?.embedding ?? null,
embeddingModel: e?.model ?? null,
- }, { client });
+ }, { client, source: 'extract' });
await catalogDB.linkIngredientToSource(ing.id, scrap.id, draft.span || null, { client });
out.push(ing);
}
@@ -177,17 +179,62 @@ router.post('/ingredients', asyncHandler(async (req, res) => {
router.patch('/ingredients/:id', asyncHandler(async (req, res) => {
validateRequest(catalogIngredientPatchSchema, req.body);
+ // `source`/`actor` are revision-history metadata, not ingredient columns —
+ // strip them from the DB patch and forward as the revision context instead.
+ const { source, actor, ...fieldPatch } = req.body;
// Re-embed only when name or payload changes — tag-only edits skip embed.
let embeddingPatch = {};
- if (req.body.name !== undefined || req.body.payload !== undefined) {
+ if (fieldPatch.name !== undefined || fieldPatch.payload !== undefined) {
const current = await catalogDB.getIngredient(req.params.id);
if (!current) throw new ServerError('Ingredient not found', { status: 404 });
embeddingPatch = await embedIngredient({
- name: req.body.name ?? current.name,
- payload: req.body.payload ?? current.payload,
+ name: fieldPatch.name ?? current.name,
+ payload: fieldPatch.payload ?? current.payload,
});
}
- const updated = await catalogDB.updateIngredient(req.params.id, { ...req.body, ...embeddingPatch });
+ const updated = await catalogDB.updateIngredient(
+ req.params.id,
+ { ...fieldPatch, ...embeddingPatch },
+ { source, actor },
+ );
+ if (!updated) throw new ServerError('Ingredient not found', { status: 404 });
+ res.json(updated);
+}));
+
+// Revision history for one ingredient (newest first). Local audit trail — see
+// catalog_ingredient_revisions in init-db.sql; not federated.
+router.get('/ingredients/:id/revisions', asyncHandler(async (req, res) => {
+ const params = validateRequest(catalogRevisionQuerySchema, req.query);
+ // 404 the history when the ingredient itself is gone, so the UI doesn't
+ // render an empty list for a deleted/never-existed id.
+ const ing = await catalogDB.getIngredient(req.params.id);
+ if (!ing) throw new ServerError('Ingredient not found', { status: 404 });
+ res.json(await catalogDB.listIngredientRevisions(req.params.id, {
+ limit: params.limit ?? 50,
+ offset: params.offset ?? 0,
+ }));
+}));
+
+// Restore a prior revision: re-applies its name/payload/tags via
+// updateIngredient (which itself records a NEW revision for the restore, so the
+// restore is auditable and itself reversible). The restored revision must
+// belong to the path ingredient.
+router.post('/ingredients/:id/revisions/:revisionId/restore', asyncHandler(async (req, res) => {
+ const body = validateRequest(catalogRevisionRestoreSchema, req.body || {});
+ const revision = await catalogDB.getIngredientRevision(req.params.revisionId);
+ if (!revision || revision.ingredientId !== req.params.id) {
+ throw new ServerError('Revision not found', { status: 404 });
+ }
+ // Drop the per-record payload.schemaVersion marker — createIngredient/
+ // updateIngredient re-stamp it from the registry, and a restore should land
+ // the CURRENT marker, not the (possibly older) one the revision captured.
+ const { schemaVersion, ...restoredPayload } = revision.payload || {};
+ const embeddingPatch = await embedIngredient({ name: revision.name, payload: restoredPayload });
+ const updated = await catalogDB.updateIngredient(
+ req.params.id,
+ { name: revision.name, payload: restoredPayload, tags: revision.tags, ...embeddingPatch },
+ { source: body.source || 'user', actor: body.actor },
+ );
if (!updated) throw new ServerError('Ingredient not found', { status: 404 });
res.json(updated);
}));
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index f075d6c177..1e1d284599 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -297,6 +297,37 @@ CREATE INDEX IF NOT EXISTS idx_catalog_tags_label ON catalog_tags (label);
CREATE INDEX IF NOT EXISTS idx_catalog_tags_parent ON catalog_tags (parent_id);
CREATE INDEX IF NOT EXISTS idx_catalog_tags_sync_seq ON catalog_tags (sync_sequence);
+-- Append-only revision history for catalog_ingredients. A row is written by
+-- catalogDB.updateIngredient whenever name/payload/tags actually change (and a
+-- seed row on create), so the detail page can show "what changed" and offer a
+-- Restore button. `source` records WHO/WHAT drove the change ('user' edit,
+-- 'extract' ingest commit, 'refine' AI pass, 'sync' peer apply); `actor` is an
+-- optional free label (agent run id, provider name). Keyed (ingredient_id,
+-- created_at) for the per-ingredient timeline query. Retention is capped at the
+-- last N per ingredient by the app layer (CATALOG_REVISION_RETENTION, default
+-- 50) -- older rows are pruned on each write to bound growth.
+--
+-- LOCAL audit history: revisions do NOT carry a sync_sequence and are NOT
+-- federated. Each install records its own edit timeline; the synced
+-- catalog_ingredients row already LWW-merges the latest state across peers, so
+-- replicating per-edit history would multiply rows without a restore use case
+-- on the receiving peer. (If revisions ever need to federate, add a
+-- sync_sequence BIGSERIAL + a getChangesSince path and bump
+-- PORTOS_SCHEMA_VERSIONS.catalog.)
+CREATE TABLE IF NOT EXISTS catalog_ingredient_revisions (
+ id TEXT PRIMARY KEY,
+ ingredient_id TEXT NOT NULL REFERENCES catalog_ingredients(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ payload JSONB NOT NULL DEFAULT '{}'::jsonb,
+ tags TEXT[] DEFAULT '{}',
+ source VARCHAR(16) NOT NULL DEFAULT 'user'
+ CHECK (source IN ('user', 'extract', 'refine', 'sync')),
+ actor VARCHAR(120),
+ created_at TIMESTAMPTZ DEFAULT NOW()
+);
+CREATE INDEX IF NOT EXISTS idx_catalog_ing_revisions_ingredient
+ ON catalog_ingredient_revisions (ingredient_id, created_at DESC);
+
-- Auto-update updated_at and bump sync_sequence on content/metadata changes.
-- Mirrors update_memory_timestamp's pattern: skip the bump on no-content-change
-- so cosmetic touches don't trigger sync. Respects explicit updated_at (used by
diff --git a/server/services/catalogDB.js b/server/services/catalogDB.js
index 2f7ddf8b0f..6dfdb337d7 100644
--- a/server/services/catalogDB.js
+++ b/server/services/catalogDB.js
@@ -29,6 +29,24 @@ function newScrapId() {
return `cat-scrap-${randomUUID()}`;
}
+function newRevisionId() {
+ return `cat-rev-${randomUUID()}`;
+}
+
+// Cap on how many revision rows we keep per ingredient. Configurable via
+// CATALOG_REVISION_RETENTION (env) so an install that wants a deeper audit
+// trail can raise it; default 50 bounds unbounded growth from AI refine loops
+// or rapid manual edits. A non-positive / non-numeric value falls back to 50.
+export const CATALOG_REVISION_RETENTION = (() => {
+ const raw = parseInt(process.env.CATALOG_REVISION_RETENTION, 10);
+ return Number.isInteger(raw) && raw > 0 ? raw : 50;
+})();
+
+// The four revision sources, mirrored from the DB CHECK constraint. 'user' is
+// the default (manual detail-page edit); 'extract' for ingest commits, 'refine'
+// for AI refinement passes, 'sync' for peer-apply changes.
+const REVISION_SOURCES = new Set(['user', 'extract', 'refine', 'sync']);
+
function rowToScrap(row) {
if (!row) return null;
@@ -120,6 +138,20 @@ function rowToTag(row) {
};
}
+function rowToRevision(row) {
+ if (!row) return null;
+ return {
+ id: row.id,
+ ingredientId: row.ingredient_id,
+ name: row.name,
+ payload: row.payload || {},
+ tags: row.tags || [],
+ source: row.source,
+ actor: row.actor ?? null,
+ createdAt: row.created_at.toISOString(),
+ };
+}
+
export async function createScrap({ title, rawText, sourceKind = 'paste', metadata = {}, embedding = null, embeddingModel = null } = {}) {
if (!rawText) throw new Error('rawText is required');
@@ -218,7 +250,7 @@ export async function deleteScrap(id, { hard = false } = {}) {
// block throws). Absent, falls through to the pool-level `query` as before.
// See `POST /api/catalog/scraps/:id/commit` for the scrap-commit batch that
// needs every per-draft ingredient + source-link to commit-or-rollback together.
-export async function createIngredient({ id: explicitId, type, name, payload = {}, tags = [], embedding = null, embeddingModel = null } = {}, { client } = {}) {
+export async function createIngredient({ id: explicitId, type, name, payload = {}, tags = [], embedding = null, embeddingModel = null } = {}, { client, source = 'user', actor = null } = {}) {
if (!type || !getCatalogType(type)) throw new Error(`Invalid ingredient type: ${type}`);
if (!name || !String(name).trim()) throw new Error('name is required');
@@ -258,7 +290,13 @@ export async function createIngredient({ id: explicitId, type, name, payload = {
originInstanceId,
],
);
- return rowToIngredient(result.rows[0]);
+ const created = rowToIngredient(result.rows[0]);
+ // Seed an initial revision so the history list shows the original state and a
+ // restore can always return to "as created". Runs on the same transaction
+ // client when one was supplied (scrap-commit batch) so a mid-batch rollback
+ // drops the seed revision alongside its ingredient.
+ await recordIngredientRevision(created, { source, actor, client });
+ return created;
}
export async function getIngredient(id) {
@@ -269,7 +307,11 @@ export async function getIngredient(id) {
return rowToIngredient(result.rows[0]);
}
-export async function updateIngredient(id, patch = {}) {
+// `{ source, actor }` drive the revision-history row written on a content
+// change. `source` is one of user|extract|refine|sync (default 'user'); `actor`
+// is an optional free label (agent run id, provider). Embedding-only patches
+// (the backfill path) carry no name/payload/tags and so record NO revision.
+export async function updateIngredient(id, patch = {}, { source = 'user', actor = null } = {}) {
const fields = [];
const params = [];
let idx = 1;
@@ -309,7 +351,79 @@ export async function updateIngredient(id, patch = {}) {
`UPDATE catalog_ingredients SET ${fields.join(', ')} WHERE id = $${idx} AND deleted = false RETURNING *`,
params,
);
- return rowToIngredient(result.rows[0]);
+ const updated = rowToIngredient(result.rows[0]);
+
+ // Record a revision only when a USER-facing field (name/payload/tags) was
+ // part of this patch AND the row actually exists/updated. Embedding/model-
+ // only patches skip history entirely. `payload.schemaVersion` is stripped
+ // from the stored revision diff-by-content check below, but we snapshot the
+ // committed payload verbatim so a restore round-trips the exact stored shape.
+ const touchedContent =
+ patch.name !== undefined || patch.payload !== undefined || patch.tags !== undefined;
+ if (updated && touchedContent) {
+ await recordIngredientRevision(updated, { source, actor });
+ }
+ return updated;
+}
+
+/**
+ * Insert one revision row capturing the committed state of an ingredient, then
+ * prune the ingredient's history to the most-recent CATALOG_REVISION_RETENTION
+ * rows. Called from updateIngredient (content changes) and createIngredient's
+ * seed path. `{ client }` runs the insert on a caller transaction when present.
+ */
+export async function recordIngredientRevision(ingredient, { source = 'user', actor = null, client } = {}) {
+ if (!ingredient?.id) return null;
+ const src = REVISION_SOURCES.has(source) ? source : 'user';
+ const exec = client ? client.query.bind(client) : query;
+ const result = await exec(
+ `INSERT INTO catalog_ingredient_revisions
+ (id, ingredient_id, name, payload, tags, source, actor)
+ VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7)
+ RETURNING *`,
+ [
+ newRevisionId(),
+ ingredient.id,
+ ingredient.name,
+ JSON.stringify(ingredient.payload || {}),
+ ingredient.tags || [],
+ src,
+ actor ? String(actor).slice(0, 120) : null,
+ ],
+ );
+ // Prune to the retention cap. Keep the newest N by created_at (tie-break on
+ // id so a same-millisecond burst prunes deterministically). DELETE the rest.
+ await exec(
+ `DELETE FROM catalog_ingredient_revisions
+ WHERE ingredient_id = $1
+ AND id NOT IN (
+ SELECT id FROM catalog_ingredient_revisions
+ WHERE ingredient_id = $1
+ ORDER BY created_at DESC, id DESC
+ LIMIT $2
+ )`,
+ [ingredient.id, CATALOG_REVISION_RETENTION],
+ );
+ return rowToRevision(result.rows[0]);
+}
+
+export async function listIngredientRevisions(ingredientId, { limit = 50, offset = 0 } = {}) {
+ const result = await query(
+ `SELECT * FROM catalog_ingredient_revisions
+ WHERE ingredient_id = $1
+ ORDER BY created_at DESC, id DESC
+ LIMIT $2 OFFSET $3`,
+ [ingredientId, Math.min(Math.max(limit, 1), 200), Math.max(offset, 0)],
+ );
+ return { items: result.rows.map(rowToRevision), nextOffset: offset + result.rows.length };
+}
+
+export async function getIngredientRevision(revisionId) {
+ const result = await query(
+ `SELECT * FROM catalog_ingredient_revisions WHERE id = $1`,
+ [revisionId],
+ );
+ return rowToRevision(result.rows[0]);
}
export async function deleteIngredient(id, { hard = false } = {}) {
diff --git a/server/services/catalogDB.test.js b/server/services/catalogDB.test.js
index 5a669ed7a0..783c701512 100644
--- a/server/services/catalogDB.test.js
+++ b/server/services/catalogDB.test.js
@@ -15,6 +15,24 @@ const captured = { sql: null, params: null };
vi.mock('../lib/db.js', () => ({
query: vi.fn(async (sql, params) => {
+ // createIngredient/reviveDeletedIngredient now also write + prune a
+ // revision row, so the fake must dispatch on the statement: only capture
+ // the catalog_ingredients write the assertions read, and no-op the
+ // revision INSERT / prune DELETE.
+ const s = sql.trim();
+ if (/^INSERT INTO catalog_ingredient_revisions/i.test(s)) {
+ const [id, ingredient_id, name] = params;
+ return {
+ rows: [{
+ id, ingredient_id, name, payload: JSON.parse(params[3]),
+ tags: params[4] || [], source: params[5], actor: params[6] ?? null,
+ created_at: new Date(),
+ }],
+ };
+ }
+ if (/^DELETE FROM catalog_ingredient_revisions/i.test(s)) {
+ return { rows: [] };
+ }
captured.sql = sql;
captured.params = params;
// Echo a row shaped like catalog_ingredients so rowToIngredient works.
diff --git a/server/services/catalogDBRevisions.test.js b/server/services/catalogDBRevisions.test.js
new file mode 100644
index 0000000000..e2d7f53bbd
--- /dev/null
+++ b/server/services/catalogDBRevisions.test.js
@@ -0,0 +1,178 @@
+/**
+ * Unit tests for the catalog ingredient revision-history layer:
+ * - createIngredient seeds an initial revision (source-labeled);
+ * - updateIngredient writes a revision only when name/payload/tags change,
+ * NOT on embedding-only patches;
+ * - recordIngredientRevision prunes to CATALOG_REVISION_RETENTION;
+ * - restore-friendly read helpers (list/get) translate rows.
+ *
+ * Postgres is mocked with a SQL-dispatching fake — we capture the INSERTs and
+ * assert on them, so the suite runs without a live database. The DDL/integration
+ * round-trip is covered by db.catalogDdlParity.test.js + the live-DB suite.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const calls = [];
+
+function fakeIngredientRow(params) {
+ // params shape from createIngredient INSERT: [id, type, name, payloadJson, tags, emb, embModel, origin]
+ const [id, type, name, payloadJson, tags] = params;
+ return {
+ id, type, name,
+ payload: JSON.parse(payloadJson),
+ tags: tags || [],
+ embedding: null, embedding_model: null, origin_instance_id: params[7],
+ created_at: new Date(), updated_at: new Date(),
+ deleted: false, deleted_at: null, sync_sequence: 1,
+ };
+}
+
+function fakeRevisionRow(params) {
+ // params from revision INSERT: [id, ingredient_id, name, payloadJson, tags, source, actor]
+ const [id, ingredient_id, name, payloadJson, tags, source, actor] = params;
+ return {
+ id, ingredient_id, name,
+ payload: JSON.parse(payloadJson),
+ tags: tags || [],
+ source, actor: actor ?? null,
+ created_at: new Date(),
+ };
+}
+
+vi.mock('../lib/db.js', () => ({
+ query: vi.fn(async (sql, params) => {
+ calls.push({ sql, params });
+ const s = sql.trim();
+ if (/^INSERT INTO catalog_ingredient_revisions/i.test(s)) {
+ return { rows: [fakeRevisionRow(params)] };
+ }
+ if (/^DELETE FROM catalog_ingredient_revisions/i.test(s)) {
+ return { rows: [] };
+ }
+ if (/^SELECT \* FROM catalog_ingredient_revisions WHERE id =/i.test(s)) {
+ return { rows: [] }; // overridden per-test where needed
+ }
+ if (/^SELECT \* FROM catalog_ingredient_revisions/i.test(s)) {
+ return { rows: [] };
+ }
+ if (/^INSERT INTO catalog_ingredients/i.test(s)) {
+ return { rows: [fakeIngredientRow(params)] };
+ }
+ if (/^UPDATE catalog_ingredients/i.test(s)) {
+ // updateIngredient builds RETURNING *; echo a plausible row. The last
+ // param is the id; reconstruct a minimal row from the SET values we know.
+ const id = params[params.length - 1];
+ return {
+ rows: [{
+ id, type: 'idea', name: 'updated',
+ payload: { schemaVersion: 1 }, tags: [],
+ embedding: null, embedding_model: null, origin_instance_id: 'inst-test',
+ created_at: new Date(), updated_at: new Date(),
+ deleted: false, deleted_at: null, sync_sequence: 2,
+ }],
+ };
+ }
+ if (/^SELECT \* FROM catalog_ingredients WHERE id =/i.test(s)) {
+ return { rows: [] };
+ }
+ return { rows: [] };
+ }),
+ withTransaction: vi.fn(),
+ pgvectorToArray: vi.fn(() => null),
+ arrayToPgvector: vi.fn((a) => a),
+}));
+
+vi.mock('./instances.js', () => ({
+ getInstanceId: vi.fn(async () => 'inst-test'),
+}));
+
+const db = await import('../lib/db.js');
+const {
+ createIngredient,
+ updateIngredient,
+ recordIngredientRevision,
+ CATALOG_REVISION_RETENTION,
+} = await import('./catalogDB.js');
+
+const revisionInserts = () => calls.filter((c) => /^INSERT INTO catalog_ingredient_revisions/i.test(c.sql.trim()));
+const revisionDeletes = () => calls.filter((c) => /^DELETE FROM catalog_ingredient_revisions/i.test(c.sql.trim()));
+
+beforeEach(() => {
+ calls.length = 0;
+});
+
+describe('createIngredient — seeds an initial revision', () => {
+ it('writes one revision row labeled with the supplied source', async () => {
+ await createIngredient({ type: 'idea', name: 'Spark', payload: { summary: 'x' } }, { source: 'extract', actor: 'agent-7' });
+ const ins = revisionInserts();
+ expect(ins.length).toBe(1);
+ // params: [id, ingredient_id, name, payloadJson, tags, source, actor]
+ expect(ins[0].params[5]).toBe('extract');
+ expect(ins[0].params[6]).toBe('agent-7');
+ expect(ins[0].params[0]).toMatch(/^cat-rev-/);
+ });
+
+ it('defaults the seed revision source to user', async () => {
+ await createIngredient({ type: 'idea', name: 'Plain' });
+ expect(revisionInserts()[0].params[5]).toBe('user');
+ });
+});
+
+describe('updateIngredient — records a revision only on content change', () => {
+ it('records a revision when payload changes', async () => {
+ await updateIngredient('cat-idea-1', { payload: { summary: 'new' } });
+ expect(revisionInserts().length).toBe(1);
+ });
+
+ it('records a revision when name changes', async () => {
+ await updateIngredient('cat-idea-1', { name: 'Renamed' });
+ expect(revisionInserts().length).toBe(1);
+ });
+
+ it('records a revision when tags change', async () => {
+ await updateIngredient('cat-idea-1', { tags: ['noir'] });
+ expect(revisionInserts().length).toBe(1);
+ });
+
+ it('does NOT record a revision on an embedding-only patch', async () => {
+ await updateIngredient('cat-idea-1', { embedding: [0.1, 0.2], embeddingModel: 'm' });
+ expect(revisionInserts().length).toBe(0);
+ });
+
+ it('labels the revision with the supplied source/actor', async () => {
+ await updateIngredient('cat-idea-1', { name: 'X' }, { source: 'refine', actor: 'run-99' });
+ const ins = revisionInserts();
+ expect(ins[0].params[5]).toBe('refine');
+ expect(ins[0].params[6]).toBe('run-99');
+ });
+
+ it('coerces an unknown source back to user', async () => {
+ await recordIngredientRevision(
+ { id: 'cat-idea-1', name: 'n', payload: {}, tags: [] },
+ { source: 'bogus' },
+ );
+ expect(revisionInserts()[0].params[5]).toBe('user');
+ });
+});
+
+describe('recordIngredientRevision — retention prune', () => {
+ it('issues a prune DELETE with the retention cap', async () => {
+ await recordIngredientRevision({ id: 'cat-idea-9', name: 'n', payload: {}, tags: [] }, {});
+ const del = revisionDeletes();
+ expect(del.length).toBe(1);
+ // DELETE params: [ingredient_id, retention]
+ expect(del[0].params[0]).toBe('cat-idea-9');
+ expect(del[0].params[1]).toBe(CATALOG_REVISION_RETENTION);
+ });
+
+ it('truncates a very long actor to 120 chars', async () => {
+ const longActor = 'a'.repeat(300);
+ await recordIngredientRevision({ id: 'cat-idea-1', name: 'n', payload: {}, tags: [] }, { actor: longActor });
+ expect(revisionInserts()[0].params[6].length).toBe(120);
+ });
+
+ it('defaults retention to 50', () => {
+ expect(CATALOG_REVISION_RETENTION).toBe(50);
+ });
+});