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

Merge remote-tracking branch 'origin/main' into pr-558

[._.]/ Adam Eivy083f4ab603db
diff --cc .changelog/NEXT.md
index 595fc52b8a,de618cd637..0d09d1fd46
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@@ -13,14 -14,9 +14,17 @@@
## Added
+- **[catalog-federation-orchestrator] The creative catalog now auto-replicates between peers.** The catalog sync routes existed but nothing pulled from peers — orphan ingredients (ideas / scenes / concepts not attached to a universe) and the universe→ingredient ref links stayed local. The sync orchestrator now runs `catalog` as a delta-based PostgreSQL category alongside Memory: on every peer-online event and on the background interval it pulls `GET /api/catalog/sync` (the seven independent per-kind BIGSERIAL cursors: scraps / ingredients / sources / refs / relations / tags / media) and applies each batch locally with the same last-writer-wins + per-row isolation + schema-version gate as direct sync. A peer ahead on the `catalog` schema records a gap on the Instances page (the existing SchemaGapBadge) and pauses draining instead of looping. Toggle it per peer under Instances → Sync Categories → "Catalog"; Postgres-only (a non-Postgres peer simply never enables it).
+- **[catalog-bundled-universe-push] Universe peer-pushes now carry their catalog enrichments.** When peer A pushes a universe to peer B, the push bundles the `catalog_ingredients` rows referenced by that universe's canon plus the universe→ingredient ref links. Previously only the embedded canon replicated, so the receiver re-derived a strictly-lossy view on first backfill — the `tags`, vector `embedding`, and `payload.summary`-style enrichments that live only in the catalog row were dropped. The bundle ships the full enriched rows (including tombstoned ref rows so unlinks propagate), applied through the same catalog-sync path; it rides only universe pushes (never series / mediaCollection), skips tombstone pushes, and is gated by `PORTOS_SCHEMA_VERSIONS.catalog` so a receiver on an older catalog schema rejects a forward-shaped bundle with a clean 409 rather than corrupting local rows. Postgres-only and best-effort — a bundle failure never fails the universe push.
+
+- **[catalog-ingredient-media-refs] Catalog ingredients can now carry typed media attachments — a portrait, mood/reference images, and more.** A new "Media" panel on each ingredient detail page lets you set one portrait (rendered large at the head) and attach additional reference images, scoped to your existing media gallery via a "Pick from gallery" picker or by dragging a gallery image onto the panel. Each attachment stores a `media_key` *reference* into your media library (the bytes are never duplicated into the catalog), so a federated peer that receives an ingredient gets its media-key list and matches it against its own library — keys whose asset hasn't arrived yet show a "missing" badge (via the same syncing-asset surface used elsewhere) instead of a broken image. Backed by a new `catalog_ingredient_media` Postgres table (kinds: portrait / reference / audio / video / document) with soft-delete tombstones from day one, so detaches propagate to peers; the rows ride the catalog sync envelope as a new `media` block (`PORTOS_SCHEMA_VERSIONS.catalog` bumped to 6 — a peer on an older catalog schema gets a clean 412 rather than silently dropping every attachment). `POST/DELETE /api/catalog/ingredients/:id/media`, `POST …/media/portrait`, and `GET …/media` + `…/media/missing` are Zod-validated; attaching rejects a key that doesn't resolve against the local library with a 422. Voice-memo capture is intentionally left as a clean seam for the separate source-kinds work.
+
+- **[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-writers-room-version-refs] Writers Room draft versions now record which catalog ingredients they reference.** Saving a draft scans the prose against the cast linked to that work in the Catalog (characters / places / objects / etc.) and stamps the matched ingredient ids onto the version snapshot. The Versions drawer renders those references as chips under each version, so you can see at a glance which cast a given draft actually mentions. The scan is best-effort — a catalog hiccup never blocks a save — and a client may pass an explicit `referencedIngredientIds[]` to skip the server scan.
+ - **[catalog-universe-builder-picker] "Pick from Catalog" on Universe Builder canon panels.** Each Characters / Places / Objects section in Universe Builder (Bible + Cast/Places/Objects tabs) now has a "Pick from Catalog" button next to "Render all" / bulk-lock. It opens the shared Ingredient Picker scoped to that type; picking an ingredient copies its payload into a new embedded canon entry, stamps the catalog row's id onto the entry as `ingredientId`, and links the ingredient back to the universe (`catalog_ingredient_refs`, role `canon-character` / `canon-place` / `canon-object`) so the "Appears in" panel populates. The `ingredientId` stamp ties the embedded entry to its durable catalog row and lets the boot-time bible→catalog backfill recreate the SAME catalog id on every federated peer instead of minting a divergent one. Already-linked ingredients are excluded from the picker so you can't double-add the same character.
+ - **[meatspace-workouts-read-path] Logged workouts are now visible in MeatSpace.** The server exposes `GET/POST /api/meatspace/workouts`, the client API wraps it, and the MeatSpace Health tab lists recent workouts that were logged by voice, palette, or API.
- **[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.
- **[catalog-export-bundle] Export a catalog slice as a portable bundle.** `GET /api/catalog/export?refKind=universe|series|issue|work&refId=…&format=json|markdown|yaml` walks the ref table for the target, hydrates each ingredient + its scraps + ref-links, and returns an `attachment` bundle. Pairs with bulk import for round-trip portability (export → edit → re-import) — useful for sharing a universe's cast outside peer-sync or seeding a fresh install from a community pack. Relations and media-ref hydration ship with their own PLAN items.
diff --cc client/src/components/CatalogCastPanel.jsx
index 3a1c20a6fe,965a224118..8de11be77e
--- a/client/src/components/CatalogCastPanel.jsx
+++ b/client/src/components/CatalogCastPanel.jsx
@@@ -131,11 -145,12 +137,12 @@@ export default function CatalogCastPane
<ul className="space-y-2">
{rows.map((row) => {
const { ingredient, role } = row;
- const badge = TYPE_BADGE[ingredient.type] || 'bg-gray-500/20 text-gray-300 border-gray-500/40';
+ const badge = CATALOG_BADGE_BY_ID[ingredient.type] || 'bg-gray-500/20 text-gray-300 border-gray-500/40';
const text = snippet(ingredient.payload);
+ const rowBusy = busyId === `${ingredient.id}:${role || ''}`;
return (
<li
- key={ingredient.id}
+ key={`${ingredient.id}:${role || ''}`}
className="flex items-start gap-3 p-2.5 rounded border border-port-border bg-port-bg/40"
>
<div className="flex-1 min-w-0">
diff --cc server/routes/catalog.js
index d8c1d4515b,9c79eea8fe..01f1c4ca58
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@@ -26,11 -21,9 +26,12 @@@ import
catalogMigrationRerunSchema,
catalogBulkImportSchema,
catalogExportQuerySchema,
+ catalogRevisionQuerySchema,
+ catalogRevisionRestoreSchema,
+ REF_KINDS,
} from '../lib/catalogValidation.js';
import { parseBulkPayload, bundleToMarkdown, toYamlString } from '../lib/catalogBulkParsers.js';
+import { resolveImageInputPath } from '../lib/fileUtils.js';
import { embedIngredient, embedBatch, ingredientEmbedSeed } from '../services/embeddings.js';
import { extractIngredients } from '../services/catalogExtraction.js';
import { migrateBibleToCatalog } from '../scripts/migrateBibleToCatalog.js';
diff --cc server/services/catalogDB.registry.test.js
index 0000000000,0000000000..783c701512
new file mode 100644
--- /dev/null
+++ b/server/services/catalogDB.registry.test.js
@@@ -1,0 -1,0 +1,121 @@@
++/**
++ * Unit tests for the catalog DB layer's registry-driven behavior:
++ * - `createIngredient` stamps `payload.schemaVersion` from the registry;
++ * - it overwrites an incoming (stale/peer) schemaVersion with the LOCAL one;
++ * - the minted id uses the registry's per-type prefix;
++ * - an unknown type throws before touching the DB.
++ *
++ * Postgres is mocked — we capture the INSERT params and assert on them, so the
++ * suite runs without a live database.
++ */
++
++import { describe, it, expect, vi, beforeEach } from 'vitest';
++
++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.
++ const [id, type, name] = params;
++ const payload = JSON.parse(params[3]);
++ return {
++ rows: [{
++ id, type, name, payload, tags: params[4] || [],
++ 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,
++ }],
++ };
++ }),
++ withTransaction: vi.fn(),
++ pgvectorToArray: vi.fn(() => null),
++ arrayToPgvector: vi.fn((a) => a),
++}));
++
++vi.mock('./instances.js', () => ({
++ getInstanceId: vi.fn(async () => 'inst-test'),
++}));
++
++import { createIngredient, reviveDeletedIngredient } from './catalogDB.js';
++import { currentPayloadSchemaVersion } from '../lib/catalogTypes.js';
++
++beforeEach(() => {
++ captured.sql = null;
++ captured.params = null;
++});
++
++describe('createIngredient — payload schemaVersion stamping', () => {
++ it('stamps the registry-current payload schemaVersion', async () => {
++ const ing = await createIngredient({ type: 'character', name: 'Echo', payload: { physicalDescription: 'tall' } });
++ const stored = JSON.parse(captured.params[3]);
++ expect(stored.schemaVersion).toBe(currentPayloadSchemaVersion('character'));
++ expect(stored.physicalDescription).toBe('tall');
++ // The returned record carries the stamped payload too.
++ expect(ing.payload.schemaVersion).toBe(currentPayloadSchemaVersion('character'));
++ });
++
++ it('overwrites an incoming (stale) schemaVersion with the local one', async () => {
++ await createIngredient({ type: 'idea', name: 'Spark', payload: { summary: 'x', schemaVersion: 99 } });
++ const stored = JSON.parse(captured.params[3]);
++ expect(stored.schemaVersion).toBe(currentPayloadSchemaVersion('idea'));
++ expect(stored.schemaVersion).not.toBe(99);
++ });
++
++ it('stamps even when no payload is supplied', async () => {
++ await createIngredient({ type: 'scene', name: 'Open' });
++ const stored = JSON.parse(captured.params[3]);
++ expect(stored.schemaVersion).toBe(currentPayloadSchemaVersion('scene'));
++ });
++});
++
++describe('createIngredient — registry-derived id prefix + type guard', () => {
++ it('mints an id with the registry per-type prefix', async () => {
++ const ing = await createIngredient({ type: 'place', name: 'Dock' });
++ expect(ing.id).toMatch(/^cat-plc-/);
++ });
++
++ it('preserves an explicit id (peer backfill) without minting', async () => {
++ const ing = await createIngredient({ id: 'cat-chr-bible-abc', type: 'character', name: 'Echo' });
++ expect(ing.id).toBe('cat-chr-bible-abc');
++ });
++
++ it('throws on an unknown type before touching the DB', async () => {
++ await expect(createIngredient({ type: 'wardrobe', name: 'Cape' })).rejects.toThrow(/Invalid ingredient type/);
++ expect(captured.params).toBeNull();
++ });
++});
++
++describe('reviveDeletedIngredient — registry guard + payload stamping', () => {
++ it('validates the type against the registry (not a stale prefix map)', async () => {
++ await expect(reviveDeletedIngredient('cat-x-1', { type: 'wardrobe', name: 'Cape' }))
++ .rejects.toThrow(/invalid type/);
++ expect(captured.params).toBeNull();
++ });
++
++ it('re-stamps the payload schemaVersion on revive', async () => {
++ await reviveDeletedIngredient('cat-chr-1', { type: 'character', name: 'Echo', payload: { role: 'lead' } });
++ const stored = JSON.parse(captured.params[3]);
++ expect(stored.schemaVersion).toBe(currentPayloadSchemaVersion('character'));
++ expect(stored.role).toBe('lead');
++ });
++});
diff --cc server/services/catalogExtraction.js
index b811bcd2cd,78dbcdbfb3..76558c1d49
--- a/server/services/catalogExtraction.js
+++ b/server/services/catalogExtraction.js
@@@ -21,21 -21,9 +21,22 @@@ import { randomUUID } from 'crypto'
import { extractBible } from '../lib/bibleExtractor.js';
import { runStagedLLM } from '../lib/stageRunner.js';
import { BIBLE_KINDS, BIBLE_FIELD, BIBLE_LIMITS } from '../lib/storyBible.js';
+import { CATALOG_TYPES } from '../lib/catalogTypes.js';
import { catalogEvents } from './catalogEvents.js';
+ import { listIngredientsForRef } from './catalogDB.js';
+// Light-shape ingredient type ids, sourced from the shared registry
+// (`extractionShape === 'light'`). Adding a light type to `catalogTypes.js`
+// flows through the draft scaffolding without a manual edit here. Order
+// matches the registry → matches the bundled prompt's JSON keys
+// (ideas/scenes/concepts today).
+const LIGHT_TYPE_IDS = CATALOG_TYPES.filter((t) => t.extractionShape === 'light').map((t) => t.id);
+// Bible type ids, sourced the same way (`extractionShape === 'bible'`).
+const BIBLE_TYPE_IDS = CATALOG_TYPES.filter((t) => t.extractionShape === 'bible').map((t) => t.id);
+// Map a light TYPE id to its plural draft key (`idea` → `ideas`). The bundled
+// prompt's JSON keys + the draft scaffolding key results by this plural.
+const lightDraftKey = (id) => `${id}s`;
+
// Light-shape stage that bundles ideas/scenes/concepts into one LLM call.
// Surfaced to the UI as a single stage row — the three result arrays land
// in `draft.ideas` / `draft.scenes` / `draft.concepts` and the user reviews