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

plan: scope creative catalog extensibility roadmap + dashboard Quick Idea widget

[._.]/ Adam Eivy95ac5482cc1b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 6794dd57c3..ec1edf9c0f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -12,6 +12,7 @@
## Added
+- **[catalog-extensibility-roadmap] PLAN.md: Creative Catalog extensibility roadmap.** Internal: 14 new tracked items covering type-registry consolidation, types table vs CHECK constraint, per-payload `schemaVersion` + upgraders, user-defined ingredient types, ingredient↔ingredient relations, canonical tag taxonomy, revision history, media attachments, bulk import + slice export, ⌘K/Ask/voice discovery hooks, URL/file/voice-memo source kinds, scrap chunking, and a dashboard Quick Idea (Catalog) widget under Quick Capture. No user-visible behavior change yet — scopes the work required to evolve the catalog beyond the v1 six hardcoded types.
- **[creative-ingredients-catalog-upgrade-path] Catalog deployment + upgrade story.** The bible→catalog backfill is now peer-aware: when a universe arrives via federated sync carrying an `ingredientId` that doesn't exist in the receiving install's catalog, the backfill creates the local catalog row WITH that explicit id instead of minting a new one — so the same logical character keeps the same catalog id across every install in the federation, even when the catalog rows weren't in the original sync payload. A new admin endpoint `POST /api/catalog/migration/rerun` (with `{ force: true }` to ignore the applied-marker) lets users recover from a stuck backfill or fix data on a peer. Catalog DDL ships in both `server/scripts/init-db.sql` (fresh installs via docker-entrypoint-initdb.d or `setup-db.js`/`db.sh setup-native`) AND `server/lib/db.js:ensureSchema()` (idempotent runtime upgrades — runs on every server boot), so existing installs pick up the catalog tables on the first restart post-pull without needing to re-run `init-db.sql`.
- **[creative-ingredients-catalog] New "Catalog" feature under Create.** A central, Postgres-backed store of typed creative ingredients — characters, places, objects, ideas, scenes, concepts. Paste any creative scrap (a one-line story spark, a scene snippet, a rough short-story draft) into `/catalog/ingest` and the server extracts candidate characters / places / objects via LLM, streams progress as a stage checklist, and shows a review screen where you check the ones to commit. The Catalog page (`/catalog`) lists every ingredient with type-chip filters, debounced search, and a one-click "+ New" inline form for the lighter idea/scene/concept types. Each ingredient has a detail page with source-scrap provenance and an "Appears in" panel that back-links to every universe / series / issue / work referencing it. Federation routes (`GET/POST /api/catalog/sync`) are wired and version-gated via the existing `PORTOS_SCHEMA_VERSIONS` contract (`catalog: 1`); the auto-orchestrator hookup ships in a follow-up. A boot-time migration backfilled 970 ingredients across 10 existing universes (94 characters, 140 places, 736 objects) so the catalog opens populated. **Vector embeddings are provider-agnostic** — a new Embeddings settings tab lets you pick Ollama or LM Studio + a 768-dim model (e.g. `nomic-embed-text`); embeddings auto-apply at ingest when configured and a `/api/catalog/embeddings/backfill` admin endpoint fills missing rows. Per-record sanitizer carries an `ingredientId` field through the round-trip so embedded universe canon stays linked to its catalog row.
- **Voice coding agent can target a managed app.** When you dispatch a coding task by voice, you can now name a managed app ("fix the failing test in BookLoom") and the agent runs against that app's workspace instead of PortOS itself. The app name is fuzzy-matched, so "book loom", "BookLoom", and "bookloom" all resolve to the same app; if no app matches what you said, the agent refuses with a short list of valid names rather than silently running against PortOS.
diff --git a/PLAN.md b/PLAN.md
index bba7b2d823..ffc87ab0a1 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -21,6 +21,25 @@ The catalog backend, schema, federation routes, ingest extraction service, and C
- [ ] [catalog-tests] **Tests for the catalog stack.** `server/services/catalogDB.test.js` (CRUD round-trip — bootstrap follows `server/services/memoryDB.test.js`), `catalogExtraction.test.js` (mock aiToolkit, assert Zod conformance), `catalogSync.test.js` (envelope round-trip + LWW), `server/lib/catalogValidation.test.js` (Zod boundary tests), `server/scripts/migrateBibleToCatalog.test.js` (idempotency), `client/src/pages/Catalog.test.jsx`, `client/src/components/IngredientPicker.test.jsx`.
- [ ] [catalog-writers-room-version-refs] **Phase 9 (deferred at design time): capture catalog ingredient ids per Writers Room draft version.** Extend the draft save path in `server/services/writersRoom/local.js` to accept `referencedIngredientIds[]`. Add `scanProseForIngredientRefs(text, { universeId?, seriesId?, workId? })` to `catalogExtraction.js` (substring match scoped to refs linked to the target). UI: render referenced ingredients on each version-history chip in `client/src/pages/WritersRoom.jsx`.
+### Creative Catalog — extensibility roadmap
+
+The v1 catalog hardcodes six types (`character|place|object|idea|scene|concept`) in at least eight places: the Postgres CHECK constraint (`server/scripts/init-db.sql` + `server/lib/db.js:ensureSchema`), the Zod enum in `server/lib/catalogValidation.js`, the extraction prompt in `server/services/catalogExtraction.js`, the `TYPES` array + `PRIMARY_CONTENT_KEY` + `PRIMARY_CONTENT_LABEL` + `payloadSnippet` fallback chain in `client/src/pages/Catalog.jsx`, the type-specific editor branches in `client/src/pages/CatalogIngredient.jsx`, the `IngredientPicker.jsx` type filter, and the `search_tsv` generated column expression. Adding a seventh type today is an 8-file touch across server, client, and a Postgres migration. The items below collapse that surface so the catalog can grow into the long tail of creative shards (lore fragments, factions, magic systems, vehicles, wardrobe, dialogue snippets, beat cards, prompt fragments, voice-memo transcripts, mood references, etc.) without each new shard being a multi-PR effort.
+
+- [ ] [catalog-shared-type-registry] **Lift catalog ingredient types into a single shared registry (`server/lib/catalogTypes.js` + mirrored client constants).** Today the 6 types are duplicated across `init-db.sql`, `db.js:ensureSchema`, `catalogValidation.js` (Zod enum), `catalogExtraction.js` (prompt slot + JSON schema), `Catalog.jsx` (`TYPES`/`PRIMARY_CONTENT_KEY`/`PRIMARY_CONTENT_LABEL`/`payloadSnippet`), `CatalogIngredient.jsx` (per-type editor branches), `IngredientPicker.jsx` (type chips). One registry entry per type: `{ id, label, idPrefix, badgeColor, primaryContentKey, primaryContentLabel, snippetFallbackKeys, payloadSchema, extractionPromptFragment, editorComponent }`. Server-side: validation, extraction, ID prefix, and FTS field set derive from the registry. Client-side: list, picker, editor branches, and snippet fallback all map over the same registry. Adding a new type becomes one registry entry + one editor component + one migration that loosens the CHECK constraint (or replaces it with an FK to a `catalog_ingredient_types` table — see `[catalog-type-table-vs-check]`). Surfaced 2026-05-29 during the extensibility review.
+- [ ] [catalog-type-table-vs-check] **Replace the `type` CHECK constraint with a `catalog_ingredient_types` table (or relax to a free-form `VARCHAR(32)` + app-layer validation).** Today `catalog_ingredients.type` is `CHECK (type IN ('character','place','object','idea','scene','concept'))`, so adding a type requires a Postgres migration that DROP/RE-ADD the constraint in both `server/scripts/init-db.sql` and `server/lib/db.js:ensureSchema`, plus a `PORTOS_SCHEMA_VERSIONS.catalog` bump. Either (a) seed a `catalog_ingredient_types(id, label, payload_schema_version, system bool, created_at)` table and FK `catalog_ingredients.type → catalog_ingredient_types.id`, letting registry-driven seeds + user-defined types coexist; OR (b) drop the constraint entirely and validate `type` against the registry at the app layer. Pairs with `[catalog-shared-type-registry]` and is the precondition for `[catalog-user-defined-types]`. Decide before adding the 7th type.
+- [ ] [catalog-payload-schemaversion-per-type] **Stamp `payload.schemaVersion` per ingredient row + add a migration helper.** Today the JSONB `payload` is loose — when a type's payload shape evolves (e.g. character adds a `voiceNotes` field, scene adds `beat`/`povShift`), older rows have no marker for which shape they're in, and the sanitizer must tolerate any historical key set forever. Mirror the per-record `schemaVersion` convention already documented in CLAUDE.md (separate from the storage-layout version): each `createIngredient` stamps `payload.schemaVersion: <registry-current>`, and `server/scripts/migrateCatalogPayload.js` walks rows whose `payload.schemaVersion < registry-current` and applies registered upgraders. Registry entry gains `payloadSchemaVersion: number` + `payloadUpgraders: { 1: (p) => p2, 2: ... }`. Without this, payload evolution silently mixes shapes across rows.
+- [ ] [catalog-user-defined-types] **Allow user-defined ingredient types in the Settings → Catalog section.** Once `[catalog-type-table-vs-check]` lands, expose a Settings UI to add a user type: `{ id, label, primaryContentKey, fields: [{ key, label, kind: 'string'|'longtext'|'tags'|'ref', maxLength? }] }`. Persisted in the new `catalog_ingredient_types` table with `system: false`; the registry merges seeded + user types at boot. Editor component for user types is a generic form renderer driven by the `fields` array (no per-type React file). Unblocks the long tail of personal creative shards (wardrobe, vehicle, faction, magic-system, voice-line, prompt-fragment, etc.) without a code change per shard. Decision needed on whether user types federate to peers (probably yes, with the type row riding the catalog sync envelope and gated by `PORTOS_SCHEMA_VERSIONS.catalog`).
+- [ ] [catalog-ingredient-relations] **Add a `catalog_ingredient_relations` table for ingredient↔ingredient edges.** Today the only ingredient relationships are to *external* records (`catalog_ingredient_refs` → universe/series/issue/work). Within the catalog, a character has no link to its place or to scenes it appears in, a concept has no link to objects that embody it, and a scene can't enumerate its cast. Schema: `(from_id, to_id, kind, created_at, sync_sequence, deleted, deleted_at)` with `kind` from a registry (`appears-in`, `lives-in`, `created-by`, `parent-of`, `variant-of`, `references`, ...). FK both ids to `catalog_ingredients(id) ON DELETE CASCADE`. UI: a "Relations" panel on `CatalogIngredient.jsx` with picker-driven add. Federate via the existing catalog sync envelope (new `relations: [...]` block). Use `deleted/deleted_at` soft-delete from day one (don't repeat the `[catalog-ref-deletion-tombstones]` mistake). This is the seam that makes the catalog a graph instead of a flat list — required before the "Knowledge Graph Visualization" Future Idea (line 249) can include creative content.
+- [ ] [catalog-tag-taxonomy] **Promote tags from `TEXT[]` to a first-class `catalog_tags` table with autocomplete.** Today `catalog_ingredients.tags` is freeform (GIN-indexed, no canonical list) — `noir` / `Noir` / `noir-style` / `film noir` accumulate as separate tags and search by tag has no autocomplete. Add `catalog_tags(id, label, description?, color?, parent_id?, created_at, sync_sequence)`; keep the freeform `tags TEXT[]` column for write-path simplicity but add a normalization step that maps user input through the canonical table, creating new rows on first use. UI: tag picker autocomplete on `CatalogIngredient.jsx` and the Quick Idea form. Optional parent_id enables tag hierarchies (genre/tone vs structural vs character-trait). Pairs with `[catalog-shared-type-registry]` — the registry can also declare default tags per type.
+- [ ] [catalog-ingredient-revisions] **Add a `catalog_ingredient_revisions` history table.** Today `updateIngredient` overwrites `payload` + `tags` in place and only `updated_at` records that it changed — no "what changed" diff, no "restore previous version" UI, no audit trail for AI-driven refinement runs (story-builder refine, future agent edits). Schema: `(id, ingredient_id, payload, tags, name, source: 'user'|'extract'|'refine'|'sync', actor?: string, created_at)` keyed `(ingredient_id, created_at)`. Write a row inside `updateIngredient` whenever `payload`/`tags`/`name` changes. UI: revision history list on `CatalogIngredient.jsx` with inline diff + "Restore" button. Cap retention to last N revisions per ingredient (config; default 50) to avoid unbounded growth. Pairs naturally with the existing Writers-Room version-history pattern.
+- [ ] [catalog-ingredient-media-refs] **Add a `catalog_ingredient_media` join table for image/audio/video attachments.** Today scenes and characters can only carry text — but the natural creative workflow is "here's a generated portrait for this character, this is the voice memo I recorded for this scene, this is the reference mood image for this concept." Schema: `(ingredient_id, media_key, kind: 'portrait'|'reference'|'audio'|'video'|'document', role?, caption?, created_at, sync_sequence, deleted, deleted_at)`. `media_key` references the existing media-history sidecar (`data/history.jsonl` + generated assets); does NOT duplicate bytes. UI: drag-and-drop image into `CatalogIngredient.jsx`, voice-memo button (record → Whisper → ingredient attached audio + transcript as scrap), "set portrait" picker that scopes to existing media history. Federation: ingredient ships its media-key list; receiving peer matches against its own media library and surfaces missing entries via the existing `metadata-missing` integrity surface. Unblocks "Mood Board Canvas" (line 256) by giving creative refs a typed home.
+- [ ] [catalog-bulk-import] **Bulk-ingest path for markdown/CSV/JSON dumps.** Today the only ingest path is `POST /api/catalog/scraps` (single paste, LLM extraction). Add `POST /api/catalog/bulk-import` that accepts a structured payload — markdown with `# Character\n` style headings, or CSV with `type,name,description,tags` columns, or a JSON array — and creates ingredients directly without an extraction round-trip. Reuses `[catalog-commit-transactional]`'s transactional wrapper. UI: a "Bulk Import" button on `CatalogIngest.jsx` that opens a dropzone + format picker. Solves the "I have 80 character notes in a Notion export" cold-start problem and the "I want to seed a catalog from a community-shared YAML pack" community case.
+- [ ] [catalog-export-bundle] **Export a catalog slice as a portable bundle.** Today the catalog has no export path — a user wanting to share their universe's cast with a collaborator (outside peer-sync) has no JSON dump. Add `GET /api/catalog/export?refKind=universe&refId=X&format=json|markdown|yaml` that walks `catalog_ingredient_refs` for the target, hydrates each ingredient + its scraps + relations + media refs, and emits a bundle. Pairs with `[catalog-bulk-import]` for round-trip portability (export → edit → re-import). Foundation for the "Legacy Export Format" Future Idea (line 251) on the creative-content side.
+- [ ] [catalog-cmdk-ask-voice-discovery] **Surface catalog ingredients in ⌘K / Ask / voice (cross-surface discovery).** Today the catalog is only reachable via `/catalog` and the per-page Pick-from-Catalog buttons (post-`[catalog-universe-builder-picker]`). Three integrations needed: (1) `⌘K` palette — open the manifest to "search results" beyond static nav by calling `/api/catalog/ingredients?q=<query>` when the user types; show top 5 matches with type badges; selecting opens the ingredient detail. (2) Ask retrieval — let `/api/ask` pull catalog ingredients tagged or linked to the active universe/series as part of its context window (token-budgeted, top-K hybrid search). (3) Voice tool `catalog_lookup({ query, type? })` registered in `server/services/voice/tools.js` + the `palette.js` whitelist. Each integration is independent and the registry from `[catalog-shared-type-registry]` makes the type filter trivial.
+- [ ] [catalog-source-kinds-url-file-voice] **Expand scrap `source_kind` beyond `paste|brain-bridge|importer-handoff`.** The column is already a free `VARCHAR(32)`, but the only ingest path that hits it is the textarea paste. Add: (a) URL ingest — paste a URL, server fetches + extracts main text via the existing browser service, source_kind `url`, metadata carries the URL + fetched title. (b) File ingest — `.txt`/`.md`/`.pdf` upload, source_kind `file`, metadata carries the original filename + mime. (c) Voice ingest — record a memo, Whisper transcribes, source_kind `voice-memo`, metadata carries the audio media_key (pairs with `[catalog-ingredient-media-refs]`). Each reuses the existing extraction pipeline and emits the same `catalog:extract:progress` frames.
+- [ ] [catalog-scrap-chunking] **Chunk long scraps into multiple `(parent_scrap_id, chunk_index)` rows.** Today `raw_text` is a single TEXT column with no enforced cap, but a 50k-word screenplay paste lands as one row and one LLM call — context overflow is silent and extraction degrades. Add `chunk_index INT DEFAULT 0` + `parent_scrap_id TEXT REFERENCES catalog_scraps(id)` and split inputs over ~12k chars into N child rows; the extractor processes each child and unions the results, dedup by name+type. Surfaced by anticipation, not yet by user pain — defer until a long-input failure is reported.
+- [ ] [catalog-quick-idea-dashboard-widget] **Add a Quick Idea (Catalog) widget under the dashboard's Quick Capture set, mirroring `QuickBrainCapture`.** New file `client/src/components/QuickIdeaCapture.jsx`; registry entry `{ id: 'quick-idea', label: 'Quick Idea (Catalog)', Component: QuickIdeaCapture, width: 'half', defaultH: 4 }` in `widgetRegistry.jsx`; add to the `default` layout in `server/services/dashboardLayouts.js`. Behavior: a single-row type chip selector (driven by `[catalog-shared-type-registry]`'s `TYPES` so adding a 7th type lights up automatically — until that lands, mirror `Catalog.jsx`'s local `TYPES` array but mark the file with a `// TODO: switch to shared registry` comment so the followup is discoverable). On type pick, render the type's primary-content key as a single textarea labeled by `PRIMARY_CONTENT_LABEL[primaryContentKey]` (e.g. "Physical Description" for character, "Summary" for idea/scene/concept, "Description" for place/object), plus a name field and optional tag input. Submit calls `createCatalogIngredient({ type, name, payload: { [primaryContentKey]: text }, tags })`. Optimistic toast + clear; "Open in Catalog" link to `/catalog/:type/:id`. No LLM extraction — this is the *fast* path for the user who already knows what shape they want (the scrap+extract path on `/catalog/ingest` is the *slow* path). Mobile-responsive (chip row wraps; full-width textarea). Pairs with `[catalog-shared-type-registry]` — without the registry the widget will need to be touched whenever a new type lands.
+
_Batch-cleared 2026-05-25: 23 Next Up items shipped together via parallel sub-agents (env-file helper, formatBytes migration, lazy voice UI text, voice long-term-memory routing, voice tool expansion + `ui_describe_visually`, three phosphene generate_ltx2.py hardenings, the peer-sync snapshot-coverage P1 refactor + ephemeralize-then-delete, per-record tombstone-ack clamp, MediaLightbox→MediaImage, global vitest peer mock, videoHistory sync category, reverse-sub UI broadcast, palette Health disambiguation, insertXxxWithId resurrection side-effects, importer tombstone detection, TUI finish-rejection note, mortalLoom errno widen, VideoGen stale-model toast, Universes sidebar grandchildren). See `git log` + `.changelog/NEXT.md`._
- [ ] [mediacard-use-mediaimage-for-syncing-assets] **`MediaCard.jsx` grid thumbnails still use a raw `<img src={previewUrl}>`.** Same peer-sync placeholder/live-swap gap that `[peer-sync-medialightbox-use-mediaimage-for-syncing-assets]` fixed for the lightbox — `client/src/components/media/MediaCard.jsx` (~line 42) doesn't get the "Syncing" placeholder or the `peerSync:asset-arrived` atomic swap. Swap the raw `<img>` for `MediaImage`. Surfaced by that item's cross-check during the batch-clear (2026-05-25); was outside its stated scope.