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

catalog: bulk import/export, Cast panel on series/issue/work, ⌘K + voice discovery

[._.]/ Adam Eivy91a5851a25cc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7e143ad31d..ff52c2e692 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -13,6 +13,10 @@
## Added
+- **[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 LLM round-trip, no per-row review screen. The whole batch commits or rolls back together, so a malformed entry can't leave the catalog half-populated. `POST /api/catalog/bulk-import` is Zod-validated (2 MB payload cap) and stamps optional `defaults.tags` plus an optional `universe`/`series`/`work`/`issue` ref onto every row in the same transaction.
+- **[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.
+- **[catalog-cmdk-ask-voice-discovery] Catalog ingredients are now discoverable from ⌘K and voice.** The Command Palette ⌘K shows live catalog hits (top 5, debounced) under a "Catalog" group as you type — selecting one jumps straight to the ingredient detail page. A new voice tool `catalog_lookup({ query, type?, limit? })` returns matching ingredients with type, snippet, and ref-count, intent-gated so it only loads on catalog-y turns and doesn't bloat every prompt. Ask retrieval (the third leg of the original PLAN item) is split out to follow.
- **[catalog-extraction-idea-scene-concept] Catalog Ingest now extracts ideas, scenes, and concepts too.** Pasting prose into `/catalog/ingest` previously only surfaced characters / places / objects. A new LLM stage runs alongside the three existing bible passes and proposes idea, scene, and concept candidates from the same scrap — each rendered as its own review section with selectable / editable rows, then committed via the same path. One additional LLM call per ingest; failures isolate to that stage so the other three are unaffected.
- **[catalog-quick-idea-dashboard-widget] New "Quick Idea (Catalog)" dashboard widget.** Captures a creative ingredient directly into the catalog without the scrap+extract LLM round-trip — pick a type chip (character / place / object / idea / scene / concept), name it, optionally add primary text and tags, and submit. Lands in the Quick Capture row of the seeded "Everything" layout on fresh installs. Existing installs whose `data/dashboard-layouts.json` predates this PR keep their saved layout — the new widget appears in the Layout Picker's "Edit" sheet so you can toggle it on. The "Open" link in the success toast jumps straight to the new ingredient's detail page.
- **[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.
diff --git a/PLAN.md b/PLAN.md
index 64c90081e1..058af3462f 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -10,7 +10,7 @@ The catalog backend, schema, federation routes, ingest extraction service, and C
- [ ] [catalog-universe-builder-picker] **Add "Pick from Catalog" button to `client/src/pages/UniverseBuilder.jsx` character/place/object panels (~3736 LOC file).** When a catalog ingredient is picked, copy its `payload` into a new embedded canon entry with `ingredientId` stamped, AND post `linkCatalogIngredient(id, { refKind: 'universe', refId, role: 'canon-character'|'canon-place'|'canon-object' })`. Picker component lives at `client/src/components/IngredientPicker.jsx` (already built). Deferred from the initial PR because of the file size — needs targeted exploration of the canon-panel structure first (CanonTab / BibleTab around `UniverseBuilder.jsx:1835` + `:2945`).
- [ ] [catalog-character-sheet-enrichment] **Upgrade `client/src/pages/CatalogIngredient.jsx` character detail/edit routes (for example `/catalog/character/cat-chr-224496f9-22ec-4784-b84a-f69cecdd4f01`) into a full editable DnD-style character sheet backed by the enriched universe-canon payload.** Character rows should expose and edit all enriched canon data already present in universe records: identity, role/archetype, appearance, personality, goals/fears, relationships, stats/abilities, color palette, style notes, prompt/render hints, reference images, and any future `payload.schemaVersion` fields. If a character reference sheet has already been rendered, show it in the detail page; if none exists, allow rendering one from this page using the linked universe's style data (`styleNotes`, `influences`, `styleImageRefs`, palette, and render settings) when the ingredient has an associated universe ref. Catalog ingredients and universe canon characters must become the same durable records rather than copy-on-write mirrors: editing either the Catalog detail page or the universe canon surface should update the same `catalog_ingredients` row (with the universe canon entry carrying only a stable `ingredientId`/projection cache if needed), so enriched fields cannot diverge between Catalog and Universe Builder. Migration/backfill: update universe-backfilled character tags from machine tags like `from-universe, universe:14590a09-5a49-4994-b401-395ee354528d` to friendly, user-facing universe-name tags while preserving a structured universe ref for querying; ship a one-time data repair for the current instance as part of the implementation. Pairs with `[catalog-universe-builder-picker]`, `[catalog-bundled-universe-push]`, `[catalog-ingredient-media-refs]`, and `[catalog-payload-schemaversion-per-type]`.
-- [ ] [catalog-pipeline-series-cast] **Add a "Cast (from Catalog)" section to `client/src/pages/PipelineSeries.jsx` that surfaces `listCatalogIngredientsForRef('series', seriesId)` and lets the user attach/detach via `IngredientPicker`.** Series records carry no embedded `characters[]` array, so this is purely additive — backed entirely by `catalog_ingredient_refs`. Same pattern applies to `client/src/pages/PipelineIssue.jsx` (refKind `'issue'`) and `client/src/pages/WritersRoom.jsx` work bibles (refKind `'work'`).
+- [x] [catalog-pipeline-series-cast] **Add a "Cast (from Catalog)" section to `client/src/pages/PipelineSeries.jsx` that surfaces `listCatalogIngredientsForRef('series', seriesId)` and lets the user attach/detach via `IngredientPicker`.** Series records carry no embedded `characters[]` array, so this is purely additive — backed entirely by `catalog_ingredient_refs`. Same pattern applies to `client/src/pages/PipelineIssue.jsx` (refKind `'issue'`) and `client/src/pages/WritersRoom.jsx` work bibles (refKind `'work'`). _Shipped 2026-05-29: `CatalogCastPanel` reusable component wired into all three pages._
- [ ] [catalog-federation-orchestrator] **Wire the catalog into `server/services/syncOrchestrator.js` (or `server/services/sharing/peerSync.js`, whichever owns memory sync orchestration) so the existing `/api/catalog/sync` + `/api/catalog/sync/apply` routes auto-replicate between peers.** Today the routes exist and are version-gated via `PORTOS_SCHEMA_VERSIONS.catalog = 1`, but no scheduler pulls from peers. Mirror how memory sync is registered (it's the only existing Postgres-backed sync category). Outbound `portosMeta.schemaVersions.catalog` is already stamped server-side. **Universe/series sync today does NOT block on catalog sync** — universes carry their full embedded canon payloads, so a peer-pushed universe still arrives complete; the receiving peer's boot-time backfill walks the freshly-arrived universe and (now, post-`[catalog-universe-builder-picker]`'s peer-reconciliation fix) creates local catalog rows with the original IDs preserved. Direct catalog sync only matters for **orphan ingredients** (idea/scene/concept rows not attached to a universe) and for **post-`[catalog-universe-builder-picker]`** universe-ingredient picker links (the `catalog_ingredient_refs` rows themselves) so the "Appears in" panel populates across peers.
- [ ] [catalog-bundled-universe-push] **Bundle catalog ingredients into universe peer-push payloads.** When peer A pushes a universe to peer B, the push should include the `catalog_ingredients` rows referenced by that universe's embedded canon plus the `catalog_ingredient_refs` rows linking universe→ingredient. Today the embedded canon payloads still replicate (so universes work end-to-end across peers), but the `tags`, `embedding`, `payload.summary`-style enrichments that live ONLY in the catalog row do not — they get re-derived from the embedded entry on the receiver's first backfill, which is a strictly-lossy view. Mirror the `bundleAdditionalKinds` pattern in `server/services/sharing/peerSync.js`. Schema-version gating already covers the new bundle: `RECORD_KIND_SCHEMA_CATEGORIES.universe` would need `['universes', 'catalog']` appended OR the bundling can rely on `cat-ingredient` arriving as its own already-gated kind in the same push. Pairs with `[catalog-federation-orchestrator]`.
- [ ] [catalog-tests] **Remaining tests for the catalog stack.** `server/services/catalogDB.test.js` (CRUD round-trip — bootstrap follows `server/services/memoryDB.test.js` — needs a Postgres test fixture), `server/scripts/migrateBibleToCatalog.test.js` (idempotency), `client/src/pages/Catalog.test.jsx`, `client/src/components/IngredientPicker.test.jsx`. _Pure-unit slice shipped 2026-05-29: `server/lib/catalogValidation.test.js` (Zod boundary), `server/services/catalogSync.test.js` (envelope round-trip + LWW + cursor normalization), `server/services/catalogExtraction.test.js` (mocked bibleExtractor + stage progress), and `server/lib/db.catalogDdlParity.test.js` (init-db.sql ↔ ensureSchema DDL parity)._
@@ -28,15 +28,20 @@ The v1 catalog hardcodes six types (`character|place|object|idea|scene|concept`)
- [ ] [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.
+- [x] [catalog-bulk-import] **Bulk-ingest path for markdown/CSV/JSON dumps.** _Shipped 2026-05-29: `POST /api/catalog/bulk-import` with JSON / CSV / markdown (`## <Type>: <Name>`) parsers, single-transaction insert, optional `defaults.tags` + `*Ref` stamping. UI on `CatalogIngest.jsx`._
+- [x] [catalog-export-bundle] **Export a catalog slice as a portable bundle.** _Shipped 2026-05-29: `GET /api/catalog/export?refKind=&refId=&format=json|markdown|yaml` hydrates ingredients + scraps + ref-links, sets `Content-Disposition: attachment`. Relations + media-refs deferred to those PLAN items._
+- [x] [catalog-cmdk-ask-voice-discovery] **Surface catalog ingredients in ⌘K / Ask / voice (cross-surface discovery).** _Partially shipped 2026-05-29: ⌘K palette renders live catalog hits under a "Catalog" group (debounced search); voice tool `catalog_lookup({ query, type?, limit? })` registered with intent-gated loading. **Ask retrieval still open — see `[catalog-ask-retrieval]`.**_
+- [ ] [catalog-ask-retrieval] **Wire catalog ingredients into `/api/ask` context (token-budgeted, top-K hybrid search).** Deferred from `[catalog-cmdk-ask-voice-discovery]` — needs a research pass on the existing Ask retriever + budgeter before implementing so the catalog slice shares the same scoring/budget model as memory/universe context.
- [ ] [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.
_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`._
+_Batch-cleared 2026-05-29 (catalog batch 2): 4 catalog items shipped via parallel sub-agents — `catalog-pipeline-series-cast` (reusable `CatalogCastPanel` on Series/Issue/WritersRoom), `catalog-bulk-import` (JSON/CSV/markdown ingest), `catalog-export-bundle` (JSON/markdown/YAML), and the palette + voice slice of `catalog-cmdk-ask-voice-discovery` (Ask retrieval split out as `[catalog-ask-retrieval]`)._
+
- [x] [mediacard-use-mediaimage-for-syncing-assets] **`MediaCard.jsx` grid thumbnails now use `MediaImage`.** Grid thumbnails show the peer-sync "Syncing" placeholder on missing assets and live-swap when `peerSync:asset-arrived` lands. Shipped 2026-05-30 with a MediaCard regression test.
+- [ ] [chrome-canary-followups] **Hardening for the custom-Chrome-binary feature (xhigh code-review 2026-05-25).** _DONE in the v2.10.0 release review: (b) both `spawn()` calls now have `.on('error', …)` listeners; (d) `browser/server.js#loadConfig` now try/catches the `JSON.parse`; (e) `setup-browser.js#loadConfig` now warns + returns `null` and `applyCanaryToConfig` skips the save when the existing config is unreadable; (f) top-level `runCanarySetup()` is now `.catch()`-wrapped. (c) is tracked separately in `[setup-browser-canary-headless]`. Remaining: (a), (g)–(o)._ **High-severity:** (a) On macOS headed mode (the default), `browser/server.js:208` uses `macAppBundle` only and silently ignores `chromePath` — a UI user who fills in `chromePath` for Canary/Chromium/Brave but leaves `macAppBundle` empty gets stock Chrome and the log misreports the binary; couple the two fields in the UI (or auto-derive `macAppBundle` from `chromePath` when the latter is inside a `.app`). (b) Neither `spawn(chromePath, …)` (line 216) nor `spawn('/usr/bin/open', …)` (line 208) has an `.on('error', …)` listener — a typo in `chromePath` emits 'error' with no listener → `uncaughtException` → portos-browser PM2 child crashes and restart-loops. (c) `scripts/setup-browser.js#applyCanaryToConfig` writes `chromePath` + `macAppBundle` but doesn't flip `headless: false`; combined with the seed default of `headless: true` (`data.reference/browser-config.json`), a fresh install accepting Canary runs Canary invisibly. (d) `browser/server.js#loadConfig` does bare `JSON.parse(raw)` with no try/catch — combined with setup-browser's non-atomic `writeFileSync` and the `cachedConfig` race, a partial-file write crashes the supervisor on next start (PM2 restart-loop forever). **Medium-severity:** (e) `setup-browser.js#loadConfig` silently catches all JSON parse errors and returns `{}`, then `applyCanaryToConfig` saves `{chromePath, macAppBundle}` only — wiping every other user-customized key. (f) Top-level `await runCanarySetup()` has no try/catch — any EACCES on data/browser-config.json aborts `npm run setup` / `update.sh` at what was previously a no-op step. (g) Idempotency guard only checks `chromePath`: users who decline get re-prompted on every update, and users who set only `macAppBundle` keep getting re-prompted. (h) `PORTOS_USE_CANARY` only matches literal `'0'`/`'false'` (opt-out) or `'1'`/`'true'` (opt-in) — `'no'`/`'off'`/`'yes'`/`'on'`/`'True'` fall through both branches. (i) `spawnSync(install.cmd, …, { stdio: 'inherit' })` for brew/winget can hang on a sudo password prompt under non-TTY + `PORTOS_USE_CANARY=1` (update.sh stalls). (j) `cachedConfig` in `browserService.js` is stale relative to setup-browser's direct write — GET /api/browser/config returns pre-update values until process restart. (k) `saveConfig` uses bare `writeFileSync` — switch to the canonical `atomicWrite` pattern (`server/lib/fileUtils.js`). **Low-severity:** (l) `spawnSync` failure-status check `result.status !== 0` treats `status: null` (spawn-failure / signal kill) identically to a non-zero exit and never logs `result.error` — masks ENOENT/EPERM/SIGKILL. (m) `optionalPath` Zod schema accepts any string up to 1024 chars; no `.app`/`.exe` sanity check — user pastes the bundle into `chromePath` → spawn() EISDIR. (n) `launchBrowser`'s reuse-existing-Chrome early-return (line 167) fires BEFORE `headlessMode = config.headless === true` (line 170), leaving the module-level default `false` after a PM2 restart that reuses Chrome — /health reports wrong mode (pre-existing, but in a function touched by this change). (o) `detectCanary` on macOS only checks `/Applications/...`; misses per-user `~/Applications/Google Chrome Canary.app` installs (corporate Macs, `HOMEBREW_CASK_OPTS=--appdir=$HOME/Applications`).
+- [ ] [strip-malloc-env-ffmpeg-children] **Extend `stripDebugMallocEnv` coverage to ffmpeg child spawns if Pinokio users still see the warning.** The Malloc-strip PR (`[ref-watch-phosphene-strip-malloc-subprocess-env]`) routed every direct Node→Python spawn through `stripDebugMallocEnv`, but ffmpeg children (`server/lib/ffmpeg.js:81`, the ffmpeg/ffprobe calls in `server/services/mediaService.js`, `server/services/videoTimeline/local.js`, and the post-render thumbnail/optimize/upscale paths in `server/services/videoGen/local.js`) still inherit `process.env`. ffmpeg on macOS links libSystem (which includes libmalloc) so it can in principle emit the same `MallocStackLogging: can't turn off…` line — unverified whether it actually does. Trigger: if Pinokio-launched installs still report stderr noise after the Python-spawn fix lands, wrap each ffmpeg spawn `env` the same way. Surfaced by reuse-review subagent during the original PR (2026-05-29).
- [ ] [mediajobqueue-shared-provider-kind-predicate] **Share a `getJobProviderKind(job)` predicate between `getGenModuleForJob` and `resolveLiveParams` in `server/services/mediaJobQueue/index.js`.** Both now encode the same `video | image+codex | image+local` partition by hand (`getGenModuleForJob` at ~line 109, `resolveLiveParams.usesLocalPython` at ~line 122). A shared `getJobProviderKind(job) → 'video-local' | 'image-local' | 'image-codex' | null` would let both branches derive from one predicate and extend cleanly to future providers. Surfaced by reuse-review during the resolveLiveParams extract (2026-05-29); deferred because today's duplication is two lines and the seam is still small.
- [ ] [ref-watch-phosphene-teacache-extend-a2v-denoise] **TeaCache through Extend + A2V Stage-1 denoise loops.** From `reference-watch` review of phosphene (commits `ea98aad8` + `17be2a79`, 2026-05-28). PortOS's `scripts/generate_ltx2.py` invokes `ExtendPipeline.extend_from_video(...)` (~line 378) and `AudioToVideoPipeline.generate_and_save(...)` (~line 417) directly without passing a TeaCache controller, so the slowest two modes in the panel run full denoise. Phosphene reuses the existing Stage-1 calibration (`ti2vid_two_stages._build_teacache_controller(n_steps, thresh=0.5)`) by monkey-patching `guided_denoise_loop` on the `ltx_pipelines_mlx.retake` and `ltx_pipelines_mlx.a2vid_two_stage` modules, gating activation on a per-call module-level config dict, set before the pipeline call and cleared in `finally`. Predicted ~1.2× on extend at default threshold (up to ~3× at 1.5); similar for A2V Stage 1. Fix: install both monkey-patches at the top of `generate_ltx2.py`, wire `_EXTEND_TC_CONFIG` / `_A2V_TC_CONFIG` from the helper's `run_extend`/`run_a2v` paths, and add a `--no-teacache` CLI flag (default-on). **Decision needed:** ride along with the `[ref-watch-phosphene-bump-ltx2-pin-v0148]` pin bump (the calibration constants are part of the same upstream surface that gets renamed) or land independently against today's pin? Scope: small/medium.
## Deferred Architecture (human-led planning)
diff --git a/client/src/components/CatalogCastPanel.jsx b/client/src/components/CatalogCastPanel.jsx
new file mode 100644
index 0000000000..959a326dff
--- /dev/null
+++ b/client/src/components/CatalogCastPanel.jsx
@@ -0,0 +1,195 @@
+/**
+ * CatalogCastPanel — a per-record "Cast (from Catalog)" surface.
+ *
+ * Lists `catalog_ingredient_refs` for a given (refKind, refId) and lets the
+ * user attach/detach ingredients through the shared IngredientPicker. The
+ * panel is purely additive: it owns no embedded array on the host record —
+ * everything is backed by the catalog_ingredient_refs table.
+ *
+ * Props:
+ * refKind — 'series' | 'issue' | 'work' (also 'universe', 'scene', etc.).
+ * refId — the host record id.
+ * refLabel — optional human label of the host record, used in the picker
+ * header and empty-state copy (e.g. "this issue").
+ */
+
+import { useEffect, useState } from 'react';
+import { Plus, Trash2, Loader2 } from 'lucide-react';
+import toast from './ui/Toast';
+import IngredientPicker from './IngredientPicker';
+import {
+ listCatalogIngredientsForRef,
+ linkCatalogIngredient,
+ unlinkCatalogIngredient,
+} from '../services/apiCatalog';
+
+const TYPE_BADGE = {
+ character: 'bg-blue-500/20 text-blue-300 border-blue-500/40',
+ place: 'bg-emerald-500/20 text-emerald-300 border-emerald-500/40',
+ object: 'bg-amber-500/20 text-amber-300 border-amber-500/40',
+ idea: 'bg-purple-500/20 text-purple-300 border-purple-500/40',
+ scene: 'bg-pink-500/20 text-pink-300 border-pink-500/40',
+ concept: 'bg-cyan-500/20 text-cyan-300 border-cyan-500/40',
+};
+
+const ROLE_BY_TYPE = {
+ character: 'cast-character',
+ place: 'cast-place',
+ object: 'cast-object',
+ idea: 'reference',
+ scene: 'reference',
+ concept: 'reference',
+};
+
+const roleForType = (type) => ROLE_BY_TYPE[type] || 'reference';
+
+function snippet(payload) {
+ if (!payload || typeof payload !== 'object') return '';
+ const text = String(payload.description || payload.summary || payload.notes || '').trim().replace(/\s+/g, ' ');
+ if (text.length <= 160) return text;
+ return `${text.slice(0, 157)}…`;
+}
+
+export default function CatalogCastPanel({ refKind, refId, refLabel }) {
+ const [rows, setRows] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [pickerOpen, setPickerOpen] = useState(false);
+ const [busyId, setBusyId] = useState(null);
+
+ useEffect(() => {
+ if (!refId) return undefined;
+ let cancelled = false;
+ setLoading(true);
+ listCatalogIngredientsForRef(refKind, refId, { silent: true })
+ .then((data) => {
+ if (cancelled) return;
+ setRows(Array.isArray(data) ? data : []);
+ })
+ .catch((err) => {
+ if (cancelled) return;
+ toast.error(err.message || 'Failed to load catalog cast');
+ setRows([]);
+ })
+ .finally(() => { if (!cancelled) setLoading(false); });
+ return () => { cancelled = true; };
+ }, [refKind, refId]);
+
+ const handlePicked = async (picked) => {
+ const ingredient = Array.isArray(picked) ? picked[0] : picked;
+ if (!ingredient) return;
+ const role = roleForType(ingredient.type);
+ await linkCatalogIngredient(ingredient.id, { refKind, refId, role }, { silent: true })
+ .then(() => {
+ setRows((prev) => {
+ if (prev.some((r) => r.ingredient.id === ingredient.id)) return prev;
+ return [...prev, { ingredient, role }];
+ });
+ toast.success(`Linked ${ingredient.name || 'ingredient'}`);
+ })
+ .catch((err) => {
+ toast.error(err.message || 'Link failed');
+ });
+ };
+
+ const handleUnlink = async (row) => {
+ const { ingredient, role } = row;
+ setBusyId(ingredient.id);
+ await unlinkCatalogIngredient(ingredient.id, { refKind, refId, role }, { silent: true })
+ .then(() => {
+ setRows((prev) => prev.filter((r) => r.ingredient.id !== ingredient.id));
+ })
+ .catch((err) => {
+ toast.error(err.message || 'Unlink failed');
+ })
+ .finally(() => setBusyId(null));
+ };
+
+ const excludeIds = rows.map((r) => r.ingredient.id);
+ const labelSuffix = refLabel ? ` for ${refLabel}` : '';
+
+ return (
+ <section className="rounded-lg border border-port-border bg-port-card/40 p-3 space-y-3">
+ <div className="flex items-center justify-between gap-2 flex-wrap">
+ <div>
+ <h3 className="text-xs uppercase tracking-wider text-gray-500">Cast (from Catalog)</h3>
+ <p className="text-[11px] text-gray-600">
+ Characters, places, objects and references pinned to this record from the shared Catalog.
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={() => setPickerOpen(true)}
+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded text-xs bg-port-accent/15 border border-port-accent/40 text-port-accent hover:bg-port-accent/25"
+ >
+ <Plus size={12} aria-hidden="true" />
+ Add from Catalog
+ </button>
+ </div>
+
+ {loading ? (
+ <div className="flex items-center gap-2 text-xs text-gray-500">
+ <Loader2 size={12} className="animate-spin" aria-hidden="true" />
+ Loading cast…
+ </div>
+ ) : rows.length === 0 ? (
+ <p className="text-xs text-gray-500 italic">
+ No catalog ingredients linked yet. Click Add to pick from the Catalog{labelSuffix}.
+ </p>
+ ) : (
+ <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 text = snippet(ingredient.payload);
+ return (
+ <li
+ key={ingredient.id}
+ 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">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-sm font-medium text-white truncate">
+ {ingredient.name || '(untitled)'}
+ </span>
+ <span className={`text-[10px] uppercase tracking-wider px-1.5 py-0.5 rounded border ${badge}`}>
+ {ingredient.type}
+ </span>
+ {role ? (
+ <span className="text-[10px] uppercase tracking-wider px-1.5 py-0.5 rounded border border-port-border text-gray-500">
+ {role}
+ </span>
+ ) : null}
+ </div>
+ {text ? (
+ <p className="text-xs text-gray-400 mt-1 line-clamp-2">{text}</p>
+ ) : null}
+ </div>
+ <button
+ type="button"
+ onClick={() => handleUnlink(row)}
+ disabled={busyId === ingredient.id}
+ aria-label={`Unlink ${ingredient.name || ingredient.id}`}
+ className="p-1.5 rounded text-gray-500 hover:text-port-error hover:bg-port-bg disabled:opacity-50"
+ title="Unlink from this record"
+ >
+ {busyId === ingredient.id
+ ? <Loader2 size={14} className="animate-spin" aria-hidden="true" />
+ : <Trash2 size={14} aria-hidden="true" />}
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+
+ <IngredientPicker
+ open={pickerOpen}
+ onClose={() => setPickerOpen(false)}
+ onSelect={handlePicked}
+ excludeIds={excludeIds}
+ refKind={refKind}
+ refId={refId}
+ />
+ </section>
+ );
+}
diff --git a/client/src/components/CatalogCastPanel.test.jsx b/client/src/components/CatalogCastPanel.test.jsx
new file mode 100644
index 0000000000..fe9c8529a2
--- /dev/null
+++ b/client/src/components/CatalogCastPanel.test.jsx
@@ -0,0 +1,123 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+
+vi.mock('../services/apiCatalog', () => ({
+ listCatalogIngredientsForRef: vi.fn(),
+ linkCatalogIngredient: vi.fn(),
+ unlinkCatalogIngredient: vi.fn(),
+ listCatalogIngredients: vi.fn(),
+}));
+
+vi.mock('./ui/Toast', () => ({
+ default: {
+ success: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ },
+}));
+
+import CatalogCastPanel from './CatalogCastPanel';
+import {
+ listCatalogIngredientsForRef,
+ linkCatalogIngredient,
+ unlinkCatalogIngredient,
+ listCatalogIngredients,
+} from '../services/apiCatalog';
+
+const renderPanel = (props = {}) => render(
+ <MemoryRouter>
+ <CatalogCastPanel refKind="series" refId="series-1" {...props} />
+ </MemoryRouter>,
+);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ listCatalogIngredients.mockResolvedValue({ items: [] });
+});
+
+describe('CatalogCastPanel', () => {
+ it('renders the empty state when no ingredients are linked', async () => {
+ listCatalogIngredientsForRef.mockResolvedValue([]);
+ renderPanel({ refLabel: 'Test Series' });
+ await waitFor(() => {
+ expect(screen.getByText(/No catalog ingredients linked yet/i)).toBeTruthy();
+ });
+ expect(screen.getByText(/for Test Series/i)).toBeTruthy();
+ });
+
+ it('renders rows from the fetched list', async () => {
+ listCatalogIngredientsForRef.mockResolvedValue([
+ {
+ ingredient: {
+ id: 'i-1',
+ name: 'Ada Lovelace',
+ type: 'character',
+ payload: { description: 'Mathematician, programmer, dreamer.' },
+ },
+ role: 'cast-character',
+ },
+ {
+ ingredient: {
+ id: 'i-2',
+ name: 'Babbage Hall',
+ type: 'place',
+ payload: { description: 'A drafty workshop full of brass.' },
+ },
+ role: 'cast-place',
+ },
+ ]);
+ renderPanel();
+ await waitFor(() => {
+ expect(screen.getByText('Ada Lovelace')).toBeTruthy();
+ });
+ expect(screen.getByText('Babbage Hall')).toBeTruthy();
+ expect(screen.getByText(/Mathematician, programmer/i)).toBeTruthy();
+ });
+
+ it('opens the picker when Add is clicked', async () => {
+ listCatalogIngredientsForRef.mockResolvedValue([]);
+ renderPanel();
+ await waitFor(() => {
+ expect(screen.getByText(/No catalog ingredients linked yet/i)).toBeTruthy();
+ });
+ fireEvent.click(screen.getByRole('button', { name: /Add from Catalog/i }));
+ await waitFor(() => {
+ expect(screen.getByRole('heading', { name: /Pick an ingredient/i })).toBeTruthy();
+ });
+ });
+
+ it('removes a row locally after unlink succeeds', async () => {
+ listCatalogIngredientsForRef.mockResolvedValue([
+ {
+ ingredient: { id: 'i-1', name: 'Ada Lovelace', type: 'character', payload: {} },
+ role: 'cast-character',
+ },
+ {
+ ingredient: { id: 'i-2', name: 'Babbage Hall', type: 'place', payload: {} },
+ role: 'cast-place',
+ },
+ ]);
+ unlinkCatalogIngredient.mockResolvedValue(undefined);
+ renderPanel();
+ await waitFor(() => {
+ expect(screen.getByText('Ada Lovelace')).toBeTruthy();
+ });
+
+ const removeBtn = screen.getByLabelText(/Unlink Ada Lovelace/i);
+ await act(async () => {
+ fireEvent.click(removeBtn);
+ });
+
+ await waitFor(() => {
+ expect(screen.queryByText('Ada Lovelace')).toBeNull();
+ });
+ expect(screen.getByText('Babbage Hall')).toBeTruthy();
+ expect(unlinkCatalogIngredient).toHaveBeenCalledWith(
+ 'i-1',
+ { refKind: 'series', refId: 'series-1', role: 'cast-character' },
+ { silent: true },
+ );
+ expect(linkCatalogIngredient).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/CmdKSearch.jsx b/client/src/components/CmdKSearch.jsx
index fc4e6a686d..0d52c05ed9 100644
--- a/client/src/components/CmdKSearch.jsx
+++ b/client/src/components/CmdKSearch.jsx
@@ -1,10 +1,10 @@
import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { createPortal } from 'react-dom';
import { useNavigate } from 'react-router-dom';
-import { Brain, Cpu, Package, History, HeartPulse, Search, Loader2, Navigation, Play, LayoutGrid } from 'lucide-react';
+import { Brain, Cpu, Package, History, HeartPulse, Search, Loader2, Navigation, Play, LayoutGrid, BookMarked } from 'lucide-react';
import { useCmdKSearch } from '../hooks/useCmdKSearch';
import { useScrollLock } from '../hooks/useScrollLock';
-import { search, getPaletteManifest, runPaletteAction, getDashboardLayouts, setActiveDashboardLayout } from '../services/api';
+import { search, getPaletteManifest, runPaletteAction, getDashboardLayouts, setActiveDashboardLayout, listCatalogIngredients } from '../services/api';
import toast from './ui/Toast';
import { modKey } from '../utils/platform';
import { DASHBOARD_LAYOUT_CHANGED } from '../constants/events.js';
@@ -67,6 +67,7 @@ export default function CmdKSearch() {
const [query, setQuery] = useState('');
const [manifest, setManifest] = useState(null);
const [searchResults, setSearchResults] = useState([]);
+ const [catalogResults, setCatalogResults] = useState([]);
const [loading, setLoading] = useState(false);
const [focusedIndex, setFocusedIndex] = useState(0);
const [expandedSources, setExpandedSources] = useState(new Set());
@@ -82,6 +83,7 @@ export default function CmdKSearch() {
if (!open) {
setQuery('');
setSearchResults([]);
+ setCatalogResults([]);
setFocusedIndex(0);
setExpandedSources(new Set());
resultRefs.current = [];
@@ -165,9 +167,23 @@ export default function CmdKSearch() {
return () => clearTimeout(timer);
}, [query]);
+ useEffect(() => {
+ if (query.length < 2) {
+ setCatalogResults([]);
+ return;
+ }
+ let cancelled = false;
+ const timer = setTimeout(() => {
+ listCatalogIngredients({ q: query, limit: 5 }, { silent: true })
+ .then((data) => { if (!cancelled) setCatalogResults(data?.items ?? []); })
+ .catch(() => { if (!cancelled) setCatalogResults([]); });
+ }, 300);
+ return () => { cancelled = true; clearTimeout(timer); };
+ }, [query]);
+
useEffect(() => {
setFocusedIndex(0);
- }, [searchResults, query]);
+ }, [searchResults, catalogResults, query]);
const combined = useMemo(() => {
if (!manifest) return { nav: [], actions: [], layouts: [], commandCount: 0 };
@@ -197,9 +213,20 @@ export default function CmdKSearch() {
[searchResults, expandedSources]
);
+ const catalogHits = useMemo(
+ () => catalogResults.map((ing) => ({
+ kind: 'catalog',
+ id: ing.id,
+ name: ing.name,
+ type: ing.type,
+ path: `/catalog/${encodeURIComponent(ing.type)}/${encodeURIComponent(ing.id)}`,
+ })),
+ [catalogResults]
+ );
+
const focusable = useMemo(
- () => [...combined.nav, ...combined.actions, ...combined.layouts, ...flatSearchResults],
- [combined, flatSearchResults]
+ () => [...combined.nav, ...combined.actions, ...combined.layouts, ...catalogHits, ...flatSearchResults],
+ [combined, catalogHits, flatSearchResults]
);
useEffect(() => {
@@ -212,6 +239,7 @@ export default function CmdKSearch() {
const DISPATCH = useMemo(() => ({
nav: (item) => { navigate(item.path); close(); },
search: (item) => { navigate(item.url); close(); },
+ catalog: (item) => { navigate(item.path); close(); },
layout: async (item) => {
// request() toasts errors centrally; swallow the rejection here so
// clicks from sync event handlers don't bubble as unhandled. On
@@ -356,13 +384,21 @@ export default function CmdKSearch() {
)
)}
+ {renderGroup(
+ <BookMarked size={14} />,
+ 'Catalog',
+ catalogHits.map((c) =>
+ renderRow(c, { icon: BookMarked, title: c.name, subtitle: c.type, badge: c.type.toUpperCase() })
+ )
+ )}
+
{loading && (
<div className="flex items-center justify-center py-4">
<Loader2 size={18} className="animate-spin text-gray-400" />
</div>
)}
- {!loading && query.length >= 2 && searchResults.length === 0 && combined.commandCount === 0 && (
+ {!loading && query.length >= 2 && searchResults.length === 0 && catalogHits.length === 0 && combined.commandCount === 0 && (
<div className="text-center text-sm text-gray-500 py-8">
No results for &ldquo;{query}&rdquo;
</div>
diff --git a/client/src/pages/CatalogIngest.jsx b/client/src/pages/CatalogIngest.jsx
index e3768629aa..6540ac108c 100644
--- a/client/src/pages/CatalogIngest.jsx
+++ b/client/src/pages/CatalogIngest.jsx
@@ -7,13 +7,14 @@
import { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
-import { Sparkles, Loader2, CheckCircle2, AlertCircle, ArrowLeft, RotateCcw, Circle } from 'lucide-react';
+import { Sparkles, Loader2, CheckCircle2, AlertCircle, ArrowLeft, RotateCcw, Circle, Upload } from 'lucide-react';
import toast from '../components/ui/Toast';
import socket from '../services/socket';
import {
createCatalogScrap,
extractFromCatalogScrap,
commitCatalogScrapDraft,
+ bulkImportCatalogIngredients,
} from '../services/apiCatalog';
// One review section per ingredient type. The first three are bible-shaped
@@ -66,6 +67,13 @@ export default function CatalogIngest() {
// editable inline + checkbox-gated. Defaults all to selected.
const [draft, setDraft] = useState({ characters: [], places: [], objects: [], ideas: [], scenes: [], concepts: [] });
const [selected, setSelected] = useState({ characters: new Set(), places: new Set(), objects: new Set(), ideas: new Set(), scenes: new Set(), concepts: new Set() });
+ // Bulk import is a separate ingest path — no LLM extraction, no review.
+ // Power-user paste of pre-structured markdown/CSV/JSON. Lives on the
+ // paste phase so users can switch between the two flows freely.
+ const [bulkOpen, setBulkOpen] = useState(false);
+ const [bulkFormat, setBulkFormat] = useState('markdown');
+ const [bulkText, setBulkText] = useState('');
+ const [bulkSubmitting, setBulkSubmitting] = useState(false);
// Track active runId so a stale frame from an earlier scrap can't mutate the
// current stage list (server fans these to all sockets — single-user trust
@@ -140,6 +148,21 @@ export default function CatalogIngest() {
setPhase('review');
};
+ const handleBulkImport = async () => {
+ const payload = bulkText.trim();
+ if (!payload) { toast.error('Paste a markdown / CSV / JSON dump first.'); return; }
+ setBulkSubmitting(true);
+ const result = await bulkImportCatalogIngredients({ format: bulkFormat, payload }, { silent: true })
+ .catch((err) => { toast.error(err?.message || 'Bulk import failed'); return null; });
+ setBulkSubmitting(false);
+ if (!result) return;
+ const n = result.count || 0;
+ toast.success(`Bulk imported ${n} ingredient${n === 1 ? '' : 's'}.`);
+ setBulkText('');
+ setBulkOpen(false);
+ navigate('/catalog');
+ };
+
const toggle = (kind, idx) => {
setSelected((prev) => {
const next = new Set(prev[kind]);
@@ -219,6 +242,13 @@ export default function CatalogIngest() {
className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm text-gray-400 hover:text-white">
<ArrowLeft size={14} aria-hidden="true" /> Back to Catalog
</button>
+ {phase === 'paste' && (
+ <button type="button" onClick={() => setBulkOpen((v) => !v)}
+ className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm border border-port-border text-gray-300 hover:text-white"
+ aria-expanded={bulkOpen}>
+ <Upload size={14} aria-hidden="true" /> Bulk Import
+ </button>
+ )}
{phase !== 'paste' && (
<button type="button" onClick={reset}
className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm border border-port-border text-gray-300 hover:text-white">
@@ -228,6 +258,53 @@ export default function CatalogIngest() {
</div>
</header>
+ {phase === 'paste' && bulkOpen && (
+ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6 space-y-4">
+ <div>
+ <h2 className="text-lg font-semibold text-white flex items-center gap-2">
+ <Upload className="w-4 h-4 text-port-accent" aria-hidden="true" /> Bulk Import
+ </h2>
+ <p className="text-xs text-gray-500 mt-1">
+ Direct ingest — no LLM extraction. Markdown sections use
+ <code className="mx-1 px-1 bg-port-bg rounded">## &lt;Type&gt;: &lt;Name&gt;</code>
+ headings; CSV expects <code className="mx-1 px-1 bg-port-bg rounded">type,name,description,tags</code>;
+ JSON is an array of <code className="mx-1 px-1 bg-port-bg rounded">{'{ type, name, description?, payload?, tags? }'}</code>.
+ </p>
+ </div>
+ <div>
+ <label htmlFor="bulk-format" className="block text-sm font-medium mb-1 text-white">Format</label>
+ <select id="bulk-format" value={bulkFormat} onChange={(e) => setBulkFormat(e.target.value)}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent">
+ <option value="markdown">Markdown</option>
+ <option value="csv">CSV</option>
+ <option value="json">JSON</option>
+ </select>
+ </div>
+ <div>
+ <label htmlFor="bulk-text" className="block text-sm font-medium mb-1 text-white">Payload</label>
+ <textarea id="bulk-text" rows={10} value={bulkText} onChange={(e) => setBulkText(e.target.value)}
+ placeholder={bulkFormat === 'csv'
+ ? 'type,name,description,tags\ncharacter,Alice,A curious sleuth,"noir, gritty"\nplace,The Hollow,Abandoned subway tunnel,'
+ : bulkFormat === 'json'
+ ? '[\n { "type": "character", "name": "Alice", "description": "A curious sleuth", "tags": ["noir"] }\n]'
+ : '## Character: Alice\nA curious sleuth.\ntags: noir, gritty\n\n## Place: The Hollow\nAbandoned subway tunnel.\n'}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm font-mono focus:outline-none focus:border-port-accent" />
+ <p className="text-xs text-gray-500 mt-1">{bulkText.length.toLocaleString()} chars</p>
+ </div>
+ <div className="flex items-center justify-end gap-2">
+ <button type="button" onClick={() => setBulkOpen(false)} disabled={bulkSubmitting}
+ className="px-3 py-2 rounded-lg text-gray-400 hover:text-white text-sm">
+ Cancel
+ </button>
+ <button type="button" onClick={handleBulkImport} disabled={bulkSubmitting || !bulkText.trim()}
+ className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium">
+ {bulkSubmitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Upload className="w-4 h-4" />}
+ {bulkSubmitting ? 'Importing…' : 'Import'}
+ </button>
+ </div>
+ </div>
+ )}
+
{phase === 'paste' && (
<form onSubmit={handleIngest} className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6 space-y-4">
<div>
diff --git a/client/src/pages/PipelineIssue.jsx b/client/src/pages/PipelineIssue.jsx
index 63c41a9a0c..4debeab204 100644
--- a/client/src/pages/PipelineIssue.jsx
+++ b/client/src/pages/PipelineIssue.jsx
@@ -33,6 +33,7 @@ import EpisodeVideoStage from '../components/pipeline/stages/EpisodeVideoStage';
import AudioStage from '../components/pipeline/stages/AudioStage';
import SeriesLlmPicker from '../components/pipeline/SeriesLlmPicker';
import LengthProfilePicker from '../components/pipeline/LengthProfilePicker';
+import CatalogCastPanel from '../components/CatalogCastPanel';
import { VisualGenSettingsPanel } from '../components/pipeline/stages/VisualGenSettings';
// Stages that surface a header-level settings gear. The Comic editor
@@ -401,7 +402,12 @@ export default function PipelineIssue() {
) : null}
{/* Active stage panel */}
- <div className="flex-1 overflow-auto p-4 md:p-6">
+ <div className="flex-1 overflow-auto p-4 md:p-6 space-y-4">
+ <CatalogCastPanel
+ refKind="issue"
+ refId={issue.id}
+ refLabel={issue.title ? `#${issue.number} ${issue.title}` : `issue #${issue.number}`}
+ />
{StageComponent ? (
<StageComponent
issue={issue}
diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsx
index e325cf7171..88f8b83fe5 100644
--- a/client/src/pages/PipelineSeries.jsx
+++ b/client/src/pages/PipelineSeries.jsx
@@ -18,6 +18,7 @@ import {
} from 'lucide-react';
import toast from '../components/ui/Toast';
import ArcCanvas from '../components/pipeline/ArcCanvas';
+import CatalogCastPanel from '../components/CatalogCastPanel';
import TabPills from '../components/ui/TabPills';
import {
getPipelineSeries, updatePipelineSeries,
@@ -405,6 +406,8 @@ function BibleSidebar({ series, universes, patchSeries, onSeriesUpdate, onFlushP
</p>
</Field>
+ <CatalogCastPanel refKind="series" refId={series.id} refLabel={series.name || 'this series'} />
+
<div>
<h3 className="text-xs uppercase tracking-wider text-gray-500 mb-2">Canon</h3>
{series.universeId ? (
diff --git a/client/src/pages/WritersRoom.jsx b/client/src/pages/WritersRoom.jsx
index b473755ef9..7a1eeb15ae 100644
--- a/client/src/pages/WritersRoom.jsx
+++ b/client/src/pages/WritersRoom.jsx
@@ -4,6 +4,7 @@ import { NotebookPen, PanelLeftOpen, BookOpen } from 'lucide-react';
import LibraryPane from '../components/writers-room/LibraryPane';
import WorkEditor from '../components/writers-room/WorkEditor';
import ExercisePanel from '../components/writers-room/ExercisePanel';
+import CatalogCastPanel from '../components/CatalogCastPanel';
import {
listWritersRoomFolders,
listWritersRoomWorks,
@@ -201,12 +202,21 @@ export default function WritersRoom() {
</div>
)}
{!loadingWork && activeWork && (
- <WorkEditor
- work={activeWork}
- onChange={handleWorkChange}
- onToggleExercise={() => setShowExercise((s) => !s)}
- exerciseOpen={showExercise}
- />
+ <>
+ <div className="px-3 pt-3">
+ <CatalogCastPanel
+ refKind="work"
+ refId={activeWork.id}
+ refLabel={activeWork.title || 'this work'}
+ />
+ </div>
+ <WorkEditor
+ work={activeWork}
+ onChange={handleWorkChange}
+ onToggleExercise={() => setShowExercise((s) => !s)}
+ exerciseOpen={showExercise}
+ />
+ </>
)}
</main>
diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.js
index c79feb0d73..2d27f79985 100644
--- a/client/src/services/apiCatalog.js
+++ b/client/src/services/apiCatalog.js
@@ -73,6 +73,20 @@ export const unlinkCatalogIngredient = (id, body, options) =>
export const listCatalogIngredientsForRef = (refKind, refId, options) =>
request(`/catalog/refs/${enc(refKind)}/${enc(refId)}/ingredients`, options);
+// --- Bulk import / export ----------------------------------------------
+
+export const bulkImportCatalogIngredients = (body, options) =>
+ request('/catalog/bulk-import', { method: 'POST', body: JSON.stringify(body), ...options });
+
+// Returns the raw bundle text/JSON; the caller is responsible for triggering
+// a browser download (typically by constructing a Blob and clicking an
+// anchor). For programmatic use (round-trip ingest), the JSON form is the
+// canonical shape.
+export const exportCatalogSlice = ({ refKind, refId, format = 'json' } = {}, options) => {
+ const params = new URLSearchParams({ refKind, refId, format });
+ return request(`/catalog/export?${params}`, { responseType: 'text', ...options });
+};
+
// --- Admin --------------------------------------------------------------
export const backfillCatalogEmbeddings = ({ limit, ...options } = {}) =>
diff --git a/client/src/services/apiCore.js b/client/src/services/apiCore.js
index 4f256bf623..37a435f5b0 100644
--- a/client/src/services/apiCore.js
+++ b/client/src/services/apiCore.js
@@ -58,6 +58,13 @@ export async function request(endpoint, options = {}) {
if (responseType === 'arraybuffer') {
return response.arrayBuffer();
}
+ // `responseType: 'text'` returns the raw body so callers (e.g. catalog
+ // export, which may be JSON, markdown, or YAML) get a string they can
+ // wrap in a Blob and trigger a download from. JSON.parse on the caller
+ // side when needed.
+ if (responseType === 'text') {
+ return response.text();
+ }
return response.json();
}
diff --git a/server/lib/README.md b/server/lib/README.md
index f638e4b12a..8f5596d604 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -50,6 +50,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `sceneExtractor.js` | Split prose or teleplay into scene list via LLM. |
| `seasonStructure.js` | Season/episode structure recommendation. |
| `bibleExtractor.js` | LLM bible-extraction stage + sanitization. |
+| `catalogBulkParsers.js` | Dependency-free markdown/CSV/JSON parsers for `POST /api/catalog/bulk-import` and YAML/markdown serializers for `GET /api/catalog/export`. |
| `comicScriptParser.js` | Marvel/DC-format comic script parser. |
| `composeStyledPrompt.js` | Compose user prompt + negative with an optional style preset. |
| `creativeDirectorPresets.js` | Locked-at-creation aspect ratio + quality presets for the Creative Director. |
diff --git a/server/lib/catalogBulkParsers.js b/server/lib/catalogBulkParsers.js
new file mode 100644
index 0000000000..4446ec3c5a
--- /dev/null
+++ b/server/lib/catalogBulkParsers.js
@@ -0,0 +1,476 @@
+/**
+ * Pure parsers for the catalog bulk-import path. Dependency-free —
+ * markdown / CSV / JSON each normalize to a list of
+ * `{ type, name, payload, tags }` entries that the route then validates
+ * one-by-one against `catalogIngredientCreateSchema` before insert.
+ *
+ * The parsers are intentionally lenient (best-effort); the Zod gate after
+ * parse is what guarantees DB-safe shape. Each parser throws on structural
+ * failure (not on per-row content errors) — those bubble up as the
+ * `BULK_IMPORT_PARSE_FAILED` error.
+ *
+ * `PRIMARY_CONTENT_KEY_BY_TYPE` mirrors the client-side map in
+ * `client/src/pages/Catalog.jsx`. When a markdown body or CSV `description`
+ * column is supplied without an explicit field name, it lands in the
+ * type-appropriate payload key.
+ *
+ * Also exports a minimal `toYamlString()` serializer used by the export
+ * route — handwritten so we don't pull js-yaml just for the catalog bundle.
+ */
+
+export const INGREDIENT_TYPES = Object.freeze([
+ 'character',
+ 'place',
+ 'object',
+ 'idea',
+ 'scene',
+ 'concept',
+]);
+
+// Mirrors PRIMARY_CONTENT_KEY in client/src/pages/Catalog.jsx and
+// CatalogIngest.jsx. When a bulk-import row supplies a body paragraph or a
+// CSV `description` column, it lands here so the entry renders correctly in
+// the catalog UI without forcing the user to hand-wire payload keys.
+export const PRIMARY_CONTENT_KEY_BY_TYPE = Object.freeze({
+ character: 'physicalDescription',
+ place: 'description',
+ object: 'description',
+ idea: 'summary',
+ scene: 'summary',
+ concept: 'summary',
+});
+
+const TYPE_LOWER = new Set(INGREDIENT_TYPES);
+
+function normalizeType(raw) {
+ if (typeof raw !== 'string') return null;
+ const t = raw.trim().toLowerCase();
+ return TYPE_LOWER.has(t) ? t : null;
+}
+
+function normalizeTags(raw) {
+ if (Array.isArray(raw)) {
+ return raw
+ .map((t) => (typeof t === 'string' ? t.trim() : ''))
+ .filter(Boolean);
+ }
+ if (typeof raw === 'string') {
+ return raw
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean);
+ }
+ return [];
+}
+
+/**
+ * Normalize one freeform entry into the import shape.
+ * Returns `{ type, name, payload, tags }` or throws.
+ */
+function normalizeEntry(input, index) {
+ if (!input || typeof input !== 'object') {
+ throw new Error(`entry[${index}]: not an object`);
+ }
+ const type = normalizeType(input.type);
+ if (!type) {
+ throw new Error(`entry[${index}]: invalid or missing type (got ${JSON.stringify(input.type)})`);
+ }
+ const name = typeof input.name === 'string' ? input.name.trim() : '';
+ if (!name) {
+ throw new Error(`entry[${index}]: name is required`);
+ }
+ // Caller may supply payload directly OR a top-level `description` /
+ // `summary` shortcut that flows into the type's primary content key.
+ const explicitPayload = input.payload && typeof input.payload === 'object' && !Array.isArray(input.payload)
+ ? { ...input.payload }
+ : {};
+ if (typeof input.description === 'string' && input.description.trim()) {
+ const key = PRIMARY_CONTENT_KEY_BY_TYPE[type];
+ // Don't overwrite an explicit payload key — the explicit one wins.
+ if (!(key in explicitPayload)) explicitPayload[key] = input.description.trim();
+ }
+ return {
+ type,
+ name,
+ payload: explicitPayload,
+ tags: normalizeTags(input.tags),
+ };
+}
+
+/**
+ * JSON: must be a non-empty array of objects.
+ */
+export function parseJsonBulk(payload) {
+ if (typeof payload !== 'string') {
+ throw new Error('json payload must be a string');
+ }
+ let parsed;
+ try {
+ parsed = JSON.parse(payload);
+ } catch (err) {
+ throw new Error(`invalid JSON: ${err.message}`);
+ }
+ if (!Array.isArray(parsed)) {
+ throw new Error('json payload must be an array of objects');
+ }
+ return parsed.map((entry, i) => normalizeEntry(entry, i));
+}
+
+/**
+ * CSV: dependency-free parser. Header row required; supports basic
+ * double-quoted fields ("" = literal quote, embedded commas allowed).
+ * Recognized headers: `type`, `name`, `description`, `tags`. Unknown
+ * columns are folded into `payload[colName]`.
+ */
+export function parseCsvBulk(payload) {
+ if (typeof payload !== 'string') {
+ throw new Error('csv payload must be a string');
+ }
+ const rows = tokenizeCsv(payload);
+ if (rows.length < 2) {
+ throw new Error('csv requires a header row and at least one data row');
+ }
+ const headers = rows[0].map((h) => h.trim());
+ const typeIdx = headers.indexOf('type');
+ const nameIdx = headers.indexOf('name');
+ if (typeIdx < 0 || nameIdx < 0) {
+ throw new Error('csv headers must include `type` and `name`');
+ }
+ const out = [];
+ for (let r = 1; r < rows.length; r++) {
+ const row = rows[r];
+ // Skip blank lines (tokenizer leaves a single empty string per blank).
+ if (row.length === 1 && row[0] === '') continue;
+ const entry = { type: row[typeIdx], name: row[nameIdx], payload: {}, tags: [] };
+ for (let c = 0; c < headers.length; c++) {
+ const h = headers[c];
+ const v = row[c] ?? '';
+ if (h === 'type' || h === 'name') continue;
+ if (h === 'tags') {
+ entry.tags = normalizeTags(v);
+ } else if (h === 'description') {
+ entry.description = v;
+ } else if (h) {
+ // Unknown column → stash in payload so users can pre-populate
+ // canon-shape keys (e.g. `personality,role,significance,…`) without
+ // a custom format.
+ if (v !== '') entry.payload[h] = v;
+ }
+ }
+ out.push(normalizeEntry(entry, r - 1));
+ }
+ if (out.length === 0) {
+ throw new Error('csv produced zero data rows');
+ }
+ return out;
+}
+
+function tokenizeCsv(text) {
+ const rows = [];
+ let row = [];
+ let cur = '';
+ let inQuotes = false;
+ let i = 0;
+ const n = text.length;
+ while (i < n) {
+ const ch = text[i];
+ if (inQuotes) {
+ if (ch === '"') {
+ if (text[i + 1] === '"') {
+ cur += '"';
+ i += 2;
+ continue;
+ }
+ inQuotes = false;
+ i++;
+ continue;
+ }
+ cur += ch;
+ i++;
+ continue;
+ }
+ if (ch === '"') { inQuotes = true; i++; continue; }
+ if (ch === ',') { row.push(cur); cur = ''; i++; continue; }
+ if (ch === '\r') {
+ // Swallow lone \r; handle \r\n via the \n branch
+ if (text[i + 1] === '\n') { i++; continue; }
+ // Treat bare \r as line terminator
+ row.push(cur); cur = ''; rows.push(row); row = []; i++;
+ continue;
+ }
+ if (ch === '\n') {
+ row.push(cur); cur = ''; rows.push(row); row = []; i++;
+ continue;
+ }
+ cur += ch;
+ i++;
+ }
+ // Final cell + row (no trailing newline case).
+ row.push(cur);
+ // If the only thing in the final row is an empty cell AND there were prior
+ // rows, drop it (trailing newline artifact).
+ if (!(row.length === 1 && row[0] === '' && rows.length > 0)) {
+ rows.push(row);
+ }
+ return rows;
+}
+
+/**
+ * Markdown convention:
+ * ## <Type>: <Name>
+ * <body paragraph(s) — primary content for the type>
+ * tags: <comma, separated, tags>
+ *
+ * The `tags:` line is optional and case-insensitive; everything else above
+ * it (until the next `## ` heading) becomes the body. Body lands in the
+ * type's primary content key per PRIMARY_CONTENT_KEY_BY_TYPE.
+ */
+export function parseMarkdownBulk(payload) {
+ if (typeof payload !== 'string') {
+ throw new Error('markdown payload must be a string');
+ }
+ const lines = payload.replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n');
+ // Heading regex: `## <Type>: <Name>` — case-insensitive on the type, name
+ // is everything to the right of the first `:`. Heading must start the line.
+ const headingRe = /^##\s+([A-Za-z][A-Za-z-]*)\s*:\s*(.+?)\s*$/;
+ const out = [];
+ let current = null;
+ const flush = () => {
+ if (!current) return;
+ const bodyText = current.bodyLines.join('\n').trim();
+ if (bodyText) {
+ const key = PRIMARY_CONTENT_KEY_BY_TYPE[current.type];
+ current.payload[key] = bodyText;
+ }
+ out.push({
+ type: current.type,
+ name: current.name,
+ payload: current.payload,
+ tags: current.tags,
+ });
+ };
+ for (const line of lines) {
+ const m = headingRe.exec(line);
+ if (m) {
+ flush();
+ const type = normalizeType(m[1]);
+ const name = m[2].trim();
+ if (!type) {
+ // Skip unrecognized headings (e.g. `## Notes:`); they'd otherwise
+ // open a malformed section. Leave `current` null so any following
+ // body lines are dropped until the next valid heading.
+ current = null;
+ continue;
+ }
+ current = { type, name, bodyLines: [], tags: [], payload: {} };
+ continue;
+ }
+ if (!current) continue;
+ // `tags: a, b, c` (case-insensitive, anywhere in the section).
+ const tagMatch = /^\s*tags\s*:\s*(.*)$/i.exec(line);
+ if (tagMatch) {
+ current.tags = normalizeTags(tagMatch[1]);
+ continue;
+ }
+ current.bodyLines.push(line);
+ }
+ flush();
+ if (out.length === 0) {
+ throw new Error('markdown produced zero `## <Type>: <Name>` sections');
+ }
+ return out.map((entry, i) => normalizeEntry(entry, i));
+}
+
+/**
+ * Top-level dispatch — `format` is the trusted enum (already Zod-validated
+ * at the route boundary).
+ */
+export function parseBulkPayload(format, payload) {
+ if (format === 'json') return parseJsonBulk(payload);
+ if (format === 'csv') return parseCsvBulk(payload);
+ if (format === 'markdown') return parseMarkdownBulk(payload);
+ throw new Error(`unknown bulk-import format: ${format}`);
+}
+
+// === Export serializers ===================================================
+
+/**
+ * Render a single ingredient as a `## <Type>: <Name>` block with body +
+ * tags + scraps. Inverse of parseMarkdownBulk (lossy on payload keys that
+ * aren't the primary content key — they're still dumped as a JSON code
+ * fence so round-tripping power users don't lose data).
+ */
+export function ingredientToMarkdown(ing) {
+ const lines = [];
+ lines.push(`## ${capitalize(ing.type)}: ${ing.name}`);
+ lines.push('');
+ const primaryKey = PRIMARY_CONTENT_KEY_BY_TYPE[ing.type];
+ const payload = ing.payload || {};
+ const primaryBody = typeof payload[primaryKey] === 'string' ? payload[primaryKey].trim() : '';
+ if (primaryBody) {
+ lines.push(primaryBody);
+ lines.push('');
+ }
+ if (Array.isArray(ing.tags) && ing.tags.length > 0) {
+ lines.push(`tags: ${ing.tags.join(', ')}`);
+ lines.push('');
+ }
+ // Dump remaining payload keys as a JSON fence so power users keep the
+ // full canon shape on round-trip. Empty {} is suppressed.
+ const remainder = { ...payload };
+ delete remainder[primaryKey];
+ if (Object.keys(remainder).length > 0) {
+ lines.push('```json');
+ lines.push(JSON.stringify(remainder, null, 2));
+ lines.push('```');
+ lines.push('');
+ }
+ if (Array.isArray(ing.scraps) && ing.scraps.length > 0) {
+ lines.push('### Scraps');
+ lines.push('');
+ for (const s of ing.scraps) {
+ lines.push(`- (${s.sourceKind || 'unknown'}) ${truncate(s.rawText || '', 500)}`);
+ }
+ lines.push('');
+ }
+ return lines.join('\n');
+}
+
+function capitalize(s) {
+ if (!s) return '';
+ return s.charAt(0).toUpperCase() + s.slice(1);
+}
+
+function truncate(s, n) {
+ return s.length > n ? `${s.slice(0, n).trimEnd()}…` : s;
+}
+
+/**
+ * Bundle the export envelope as markdown — top heading + per-ingredient
+ * blocks via ingredientToMarkdown.
+ */
+export function bundleToMarkdown(bundle) {
+ const out = [];
+ out.push(`# Catalog Export — ${bundle.ref.kind}/${bundle.ref.id}`);
+ out.push('');
+ out.push(`Exported at ${bundle.exportedAt} (${bundle.ingredients.length} ingredient${bundle.ingredients.length === 1 ? '' : 's'})`);
+ out.push('');
+ for (const ing of bundle.ingredients) {
+ out.push(ingredientToMarkdown(ing));
+ }
+ return out.join('\n');
+}
+
+/**
+ * Minimal YAML serializer for the export bundle's JSON shape. Supports the
+ * value types we actually emit (strings, numbers, booleans, null, arrays,
+ * objects). Strings always quote with double-quotes to sidestep YAML's
+ * special-token landmines (`yes`, `no`, `null`, leading-`-`, etc.).
+ *
+ * Power users who need a richer YAML round-trip can convert from the JSON
+ * format instead; we don't pull js-yaml just for this.
+ */
+export function toYamlString(value) {
+ // Top-level shape: emit as a mapping if it's a plain object, else fall
+ // back to a list/scalar at depth 0.
+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
+ return emitMapping(value, 0).join('\n') + '\n';
+ }
+ if (Array.isArray(value)) {
+ return emitSequence(value, 0).join('\n') + '\n';
+ }
+ return emitScalar(value) + '\n';
+}
+
+function isScalar(v) {
+ return v === null || v === undefined || typeof v !== 'object';
+}
+
+function emitScalar(value) {
+ if (value === null || value === undefined) return 'null';
+ if (typeof value === 'boolean') return value ? 'true' : 'false';
+ if (typeof value === 'number') return Number.isFinite(value) ? String(value) : 'null';
+ if (typeof value === 'string') return yamlQuote(value);
+ return yamlQuote(String(value));
+}
+
+function emitMapping(obj, depth) {
+ const pad = ' '.repeat(depth);
+ const keys = Object.keys(obj);
+ if (keys.length === 0) return [`${pad}{}`];
+ const out = [];
+ for (const k of keys) {
+ const v = obj[k];
+ const keyStr = yamlKey(k);
+ if (isScalar(v)) {
+ out.push(`${pad}${keyStr}: ${emitScalar(v)}`);
+ continue;
+ }
+ if (Array.isArray(v)) {
+ if (v.length === 0) {
+ out.push(`${pad}${keyStr}: []`);
+ } else {
+ out.push(`${pad}${keyStr}:`);
+ out.push(...emitSequence(v, depth));
+ }
+ continue;
+ }
+ // Object (non-null, non-array)
+ if (Object.keys(v).length === 0) {
+ out.push(`${pad}${keyStr}: {}`);
+ } else {
+ out.push(`${pad}${keyStr}:`);
+ out.push(...emitMapping(v, depth + 1));
+ }
+ }
+ return out;
+}
+
+function emitSequence(arr, depth) {
+ const pad = ' '.repeat(depth);
+ const out = [];
+ for (const v of arr) {
+ if (isScalar(v)) {
+ out.push(`${pad}- ${emitScalar(v)}`);
+ continue;
+ }
+ if (Array.isArray(v)) {
+ if (v.length === 0) {
+ out.push(`${pad}- []`);
+ } else {
+ out.push(`${pad}-`);
+ out.push(...emitSequence(v, depth + 1));
+ }
+ continue;
+ }
+ // Object: inline first key after the `- ` then indent the rest.
+ const keys = Object.keys(v);
+ if (keys.length === 0) {
+ out.push(`${pad}- {}`);
+ continue;
+ }
+ const mapLines = emitMapping(v, depth + 1);
+ // The first mapping line already carries depth+1 indentation; rewrite
+ // it to use `- ` at depth instead so the list item is properly aligned.
+ const firstPad = ' '.repeat(depth + 1);
+ const first = mapLines[0].startsWith(firstPad) ? mapLines[0].slice(firstPad.length) : mapLines[0];
+ out.push(`${pad}- ${first}`);
+ for (let i = 1; i < mapLines.length; i++) out.push(mapLines[i]);
+ }
+ return out;
+}
+
+function yamlKey(k) {
+ // Quote keys that aren't safe bare identifiers; covers spaces, colons,
+ // special tokens. Cheap and correct for our shape.
+ if (/^[A-Za-z_][A-Za-z0-9_-]*$/.test(k) && !['null', 'true', 'false', 'yes', 'no'].includes(k.toLowerCase())) {
+ return k;
+ }
+ return yamlQuote(k);
+}
+
+function yamlQuote(s) {
+ // JSON.stringify already gives us a YAML-compatible double-quoted form
+ // for the subset of strings we'll see (escapes \, ", \n, control chars).
+ return JSON.stringify(s);
+}
diff --git a/server/lib/catalogBulkParsers.test.js b/server/lib/catalogBulkParsers.test.js
new file mode 100644
index 0000000000..bd4b9fe0c0
--- /dev/null
+++ b/server/lib/catalogBulkParsers.test.js
@@ -0,0 +1,253 @@
+/**
+ * Boundary tests for the catalog bulk-import parsers. Pure — no DB, no LLM.
+ *
+ * Each parser is exercised on a happy-path payload + at least one structural
+ * failure mode. Per-entry Zod validation happens at the route boundary; this
+ * suite only asserts that the parser produces the normalized
+ * `{ type, name, payload, tags }` shape (or throws on structurally invalid
+ * input).
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ parseJsonBulk,
+ parseCsvBulk,
+ parseMarkdownBulk,
+ parseBulkPayload,
+ PRIMARY_CONTENT_KEY_BY_TYPE,
+ ingredientToMarkdown,
+ bundleToMarkdown,
+ toYamlString,
+} from './catalogBulkParsers.js';
+
+describe('PRIMARY_CONTENT_KEY_BY_TYPE', () => {
+ it('mirrors the client-side map for the six v1 types', () => {
+ expect(PRIMARY_CONTENT_KEY_BY_TYPE).toEqual({
+ character: 'physicalDescription',
+ place: 'description',
+ object: 'description',
+ idea: 'summary',
+ scene: 'summary',
+ concept: 'summary',
+ });
+ });
+});
+
+describe('parseJsonBulk', () => {
+ it('parses an array of well-formed entries and lands description in the type primary key', () => {
+ const out = parseJsonBulk(JSON.stringify([
+ { type: 'character', name: 'Alice', description: 'a curious sleuth', tags: ['noir'] },
+ { type: 'place', name: 'The Hollow', description: 'abandoned subway tunnel' },
+ ]));
+ expect(out).toEqual([
+ { type: 'character', name: 'Alice', payload: { physicalDescription: 'a curious sleuth' }, tags: ['noir'] },
+ { type: 'place', name: 'The Hollow', payload: { description: 'abandoned subway tunnel' }, tags: [] },
+ ]);
+ });
+
+ it('preserves explicit payload keys over the description shortcut', () => {
+ const out = parseJsonBulk(JSON.stringify([
+ { type: 'character', name: 'Bob', description: 'shortcut', payload: { physicalDescription: 'explicit wins' } },
+ ]));
+ expect(out[0].payload.physicalDescription).toBe('explicit wins');
+ });
+
+ it('throws on non-array root', () => {
+ expect(() => parseJsonBulk(JSON.stringify({ type: 'character', name: 'X' }))).toThrow(/array/);
+ });
+
+ it('throws on invalid JSON', () => {
+ expect(() => parseJsonBulk('{not json}')).toThrow(/invalid JSON/);
+ });
+
+ it('throws on unknown ingredient type', () => {
+ expect(() => parseJsonBulk(JSON.stringify([{ type: 'faction', name: 'X' }]))).toThrow(/invalid or missing type/);
+ });
+
+ it('throws on missing name', () => {
+ expect(() => parseJsonBulk(JSON.stringify([{ type: 'idea', name: ' ' }]))).toThrow(/name is required/);
+ });
+});
+
+describe('parseCsvBulk', () => {
+ it('parses the documented header + data rows', () => {
+ const csv = [
+ 'type,name,description,tags',
+ 'character,Alice,A curious sleuth,"noir, gritty"',
+ 'place,The Hollow,Abandoned subway tunnel,',
+ ].join('\n');
+ const out = parseCsvBulk(csv);
+ expect(out).toEqual([
+ { type: 'character', name: 'Alice', payload: { physicalDescription: 'A curious sleuth' }, tags: ['noir', 'gritty'] },
+ { type: 'place', name: 'The Hollow', payload: { description: 'Abandoned subway tunnel' }, tags: [] },
+ ]);
+ });
+
+ it('folds unknown columns into payload (canon shape pass-through)', () => {
+ const csv = [
+ 'type,name,personality,role',
+ 'character,Alice,curious,detective',
+ ].join('\n');
+ const out = parseCsvBulk(csv);
+ expect(out[0].payload).toEqual({ personality: 'curious', role: 'detective' });
+ });
+
+ it('handles quoted fields with embedded commas and escaped quotes', () => {
+ const csv = [
+ 'type,name,description',
+ 'idea,X,"comma, inside and ""quotes"" too"',
+ ].join('\n');
+ const out = parseCsvBulk(csv);
+ expect(out[0].payload.summary).toBe('comma, inside and "quotes" too');
+ });
+
+ it('throws when required headers are missing', () => {
+ expect(() => parseCsvBulk('foo,bar\nx,y')).toThrow(/headers must include/);
+ });
+
+ it('throws when there is no data row', () => {
+ expect(() => parseCsvBulk('type,name')).toThrow(/header row and at least one/);
+ });
+
+ it('skips blank lines between data rows', () => {
+ const csv = ['type,name', 'idea,A', '', 'idea,B', ''].join('\n');
+ const out = parseCsvBulk(csv);
+ expect(out.map((e) => e.name)).toEqual(['A', 'B']);
+ });
+});
+
+describe('parseMarkdownBulk', () => {
+ it('parses sections, body, and tags', () => {
+ const md = [
+ '## Character: Alice',
+ 'A curious sleuth.',
+ 'She walks at night.',
+ 'tags: noir, gritty',
+ '',
+ '## Place: The Hollow',
+ 'Abandoned subway tunnel.',
+ ].join('\n');
+ const out = parseMarkdownBulk(md);
+ expect(out).toEqual([
+ {
+ type: 'character',
+ name: 'Alice',
+ payload: { physicalDescription: 'A curious sleuth.\nShe walks at night.' },
+ tags: ['noir', 'gritty'],
+ },
+ {
+ type: 'place',
+ name: 'The Hollow',
+ payload: { description: 'Abandoned subway tunnel.' },
+ tags: [],
+ },
+ ]);
+ });
+
+ it('ignores unrecognized type headings (drops their body)', () => {
+ const md = [
+ '## Faction: Goons',
+ 'a body we ignore',
+ '## Scene: Rooftop chase',
+ 'jumped across two buildings',
+ ].join('\n');
+ const out = parseMarkdownBulk(md);
+ expect(out).toEqual([
+ { type: 'scene', name: 'Rooftop chase', payload: { summary: 'jumped across two buildings' }, tags: [] },
+ ]);
+ });
+
+ it('throws when no `## <Type>: <Name>` section is found', () => {
+ expect(() => parseMarkdownBulk('Just a paragraph.\nNo heading here.')).toThrow(/zero `## <Type>: <Name>`/);
+ });
+
+ it('handles CRLF line endings', () => {
+ const md = '## Idea: X\r\ndescribed here\r\ntags: a, b\r\n';
+ const out = parseMarkdownBulk(md);
+ expect(out[0]).toEqual({ type: 'idea', name: 'X', payload: { summary: 'described here' }, tags: ['a', 'b'] });
+ });
+
+ it('is case-insensitive on the type token', () => {
+ const md = '## CHARACTER: X\nbody\n';
+ const out = parseMarkdownBulk(md);
+ expect(out[0].type).toBe('character');
+ });
+});
+
+describe('parseBulkPayload dispatch', () => {
+ it('routes to the right parser by format name', () => {
+ expect(parseBulkPayload('json', '[{"type":"idea","name":"X"}]')[0].name).toBe('X');
+ expect(parseBulkPayload('csv', 'type,name\nidea,X')[0].name).toBe('X');
+ expect(parseBulkPayload('markdown', '## Idea: X\nbody\n')[0].name).toBe('X');
+ });
+
+ it('throws on unknown format', () => {
+ expect(() => parseBulkPayload('toml', 'x')).toThrow(/unknown bulk-import format/);
+ });
+});
+
+describe('ingredientToMarkdown / bundleToMarkdown', () => {
+ it('emits a Type: Name heading + body + tags + scraps', () => {
+ const md = ingredientToMarkdown({
+ type: 'character',
+ name: 'Alice',
+ payload: { physicalDescription: 'a curious sleuth', personality: 'quiet' },
+ tags: ['noir'],
+ scraps: [{ sourceKind: 'paste', rawText: 'first sighting in chapter 1' }],
+ });
+ expect(md).toContain('## Character: Alice');
+ expect(md).toContain('a curious sleuth');
+ expect(md).toContain('tags: noir');
+ expect(md).toContain('"personality": "quiet"');
+ expect(md).toContain('### Scraps');
+ expect(md).toContain('first sighting in chapter 1');
+ });
+
+ it('round-trips type/name/body via the markdown parser', () => {
+ const bundle = {
+ ref: { kind: 'universe', id: 'u1' },
+ exportedAt: '2026-05-29T00:00:00.000Z',
+ ingredients: [
+ { type: 'character', name: 'Alice', payload: { physicalDescription: 'curious' }, tags: ['noir'], scraps: [] },
+ { type: 'idea', name: 'time loop', payload: { summary: 'recurs every Tuesday' }, tags: [], scraps: [] },
+ ],
+ };
+ const md = bundleToMarkdown(bundle);
+ const reparsed = parseMarkdownBulk(md);
+ expect(reparsed).toEqual([
+ { type: 'character', name: 'Alice', payload: { physicalDescription: 'curious' }, tags: ['noir'] },
+ { type: 'idea', name: 'time loop', payload: { summary: 'recurs every Tuesday' }, tags: [] },
+ ]);
+ });
+});
+
+describe('toYamlString', () => {
+ it('emits a parseable subset for the export bundle shape', () => {
+ const yaml = toYamlString({
+ version: 1,
+ ref: { kind: 'universe', id: 'u1' },
+ ingredients: [
+ { id: 'cat-chr-1', type: 'character', name: 'Alice', tags: ['noir'], payload: { physicalDescription: 'curious' } },
+ ],
+ });
+ expect(yaml).toMatch(/^version: 1\n/);
+ expect(yaml).toContain('ref:\n');
+ expect(yaml).toContain('kind: "universe"');
+ expect(yaml).toContain('- id: "cat-chr-1"');
+ expect(yaml).toContain('tags:\n');
+ expect(yaml).toContain('- "noir"');
+ });
+
+ it('handles null / boolean / numeric scalars', () => {
+ const yaml = toYamlString({ a: null, b: true, c: 42 });
+ expect(yaml).toContain('a: null');
+ expect(yaml).toContain('b: true');
+ expect(yaml).toContain('c: 42');
+ });
+
+ it('emits empty array / object as the inline form', () => {
+ const yaml = toYamlString({ tags: [], payload: {} });
+ expect(yaml).toContain('tags: []');
+ expect(yaml).toContain('payload: {}');
+ });
+});
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index 5988fb99ef..0208507c0a 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -107,6 +107,37 @@ export const catalogMigrationRerunSchema = z.object({
force: z.boolean().optional(),
}).strict();
+// /bulk-import — accept a structured payload in one of three formats. The
+// route parses `payload` into a list of ingredient drafts (per the format),
+// then validates each entry against catalogIngredientCreateSchema before
+// insert. `defaults.tags` are merged onto every row; `defaults.*Ref` (if any)
+// creates a catalog_ingredient_refs row in the same transaction.
+//
+// Payload is capped at 2MB (same ceiling as scrap rawText) so a single
+// import can't blow the request body limit. Per-entry shape is validated
+// after parse, not here.
+export const catalogBulkImportSchema = z.object({
+ format: z.enum(['json', 'csv', 'markdown']),
+ payload: z.string().min(1).max(2_000_000),
+ defaults: z.object({
+ universeRef: z.string().trim().min(1).max(120).optional(),
+ seriesRef: z.string().trim().min(1).max(120).optional(),
+ workRef: z.string().trim().min(1).max(120).optional(),
+ issueRef: z.string().trim().min(1).max(120).optional(),
+ role: z.string().trim().min(1).max(64).optional(),
+ tags: z.array(tag).max(BIBLE_LIMITS.TAGS_PER_ENTRY_MAX).optional(),
+ }).strict().optional(),
+}).strict();
+
+// /export — query params for the export endpoint. Returns the bundle in
+// the requested serialization; the response is `Content-Disposition:
+// attachment` so the browser saves it directly.
+export const catalogExportQuerySchema = z.object({
+ refKind: z.enum(REF_KINDS),
+ refId: z.string().trim().min(1).max(120),
+ format: z.enum(['json', 'markdown', 'yaml']).optional(),
+}).strict();
+
// Sync envelope shape — used by POST /api/catalog/sync/apply when a peer
// forwards changes pulled from another instance. Each kind is optional so
// callers can apply a partial envelope (e.g. ingredients-only).
diff --git a/server/lib/catalogValidation.test.js b/server/lib/catalogValidation.test.js
index 4c0c62cd04..c4bd191502 100644
--- a/server/lib/catalogValidation.test.js
+++ b/server/lib/catalogValidation.test.js
@@ -19,6 +19,8 @@ import {
catalogIngredientLinkSchema,
catalogScrapCommitSchema,
catalogSyncEnvelopeSchema,
+ catalogBulkImportSchema,
+ catalogExportQuerySchema,
} from './catalogValidation.js';
describe('catalogValidation — ingredient types & ref kinds', () => {
@@ -239,3 +241,80 @@ describe('catalogValidation — catalogSyncEnvelopeSchema', () => {
expect(() => catalogSyncEnvelopeSchema.parse(env)).toThrow();
});
});
+
+describe('catalogValidation — catalogBulkImportSchema', () => {
+ it('accepts a minimal markdown payload', () => {
+ const out = catalogBulkImportSchema.parse({ format: 'markdown', payload: '## Idea: X\nbody' });
+ expect(out.format).toBe('markdown');
+ });
+
+ it('accepts json/csv/markdown as formats', () => {
+ for (const f of ['json', 'csv', 'markdown']) {
+ expect(() => catalogBulkImportSchema.parse({ format: f, payload: 'x' })).not.toThrow();
+ }
+ });
+
+ it('rejects unknown formats', () => {
+ expect(() => catalogBulkImportSchema.parse({ format: 'toml', payload: 'x' })).toThrow();
+ });
+
+ it('rejects empty payload', () => {
+ expect(() => catalogBulkImportSchema.parse({ format: 'json', payload: '' })).toThrow();
+ });
+
+ it('caps payload at 2MB', () => {
+ const huge = 'a'.repeat(2_000_001);
+ expect(() => catalogBulkImportSchema.parse({ format: 'json', payload: huge })).toThrow();
+ });
+
+ it('accepts defaults block with universe/series/work refs and tags', () => {
+ const out = catalogBulkImportSchema.parse({
+ format: 'json',
+ payload: '[]',
+ defaults: { universeRef: 'u1', seriesRef: 's1', tags: ['noir'] },
+ });
+ expect(out.defaults.universeRef).toBe('u1');
+ expect(out.defaults.tags).toEqual(['noir']);
+ });
+
+ it('rejects unknown keys in defaults (strict)', () => {
+ expect(() => catalogBulkImportSchema.parse({
+ format: 'json', payload: '[]', defaults: { universeRef: 'u1', mystery: true },
+ })).toThrow();
+ });
+
+ it('rejects unknown top-level keys (strict)', () => {
+ expect(() => catalogBulkImportSchema.parse({ format: 'json', payload: '[]', sneaky: true })).toThrow();
+ });
+});
+
+describe('catalogValidation — catalogExportQuerySchema', () => {
+ it('accepts every ref kind', () => {
+ for (const k of REF_KINDS) {
+ expect(() => catalogExportQuerySchema.parse({ refKind: k, refId: 'r1' })).not.toThrow();
+ }
+ });
+
+ it('rejects unknown ref kind', () => {
+ expect(() => catalogExportQuerySchema.parse({ refKind: 'galaxy', refId: 'r1' })).toThrow();
+ });
+
+ it('defaults to no format (route resolves to json)', () => {
+ const out = catalogExportQuerySchema.parse({ refKind: 'universe', refId: 'u1' });
+ expect(out.format).toBeUndefined();
+ });
+
+ it('accepts json/markdown/yaml format', () => {
+ for (const f of ['json', 'markdown', 'yaml']) {
+ expect(() => catalogExportQuerySchema.parse({ refKind: 'universe', refId: 'u1', format: f })).not.toThrow();
+ }
+ });
+
+ it('rejects unknown format', () => {
+ expect(() => catalogExportQuerySchema.parse({ refKind: 'universe', refId: 'u1', format: 'xml' })).toThrow();
+ });
+
+ it('caps refId at 120 chars', () => {
+ expect(() => catalogExportQuerySchema.parse({ refKind: 'universe', refId: 'a'.repeat(200) })).toThrow();
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index d1464d3c50..a854aaa47d 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -32,6 +32,7 @@ export * from './validation.js';
// === Story & narrative ===
export * from './bibleExtractor.js';
+export * as catalogBulkParsers from './catalogBulkParsers.js';
export * from './canonPrompt.js';
export * from './comicScriptParser.js';
export * from './composeStyledPrompt.js';
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index 4732d32dcd..1ff6a8dc39 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -19,7 +19,10 @@ import {
catalogExtractRequestSchema,
catalogEmbeddingsBackfillSchema,
catalogMigrationRerunSchema,
+ catalogBulkImportSchema,
+ catalogExportQuerySchema,
} from '../lib/catalogValidation.js';
+import { parseBulkPayload, bundleToMarkdown, toYamlString } from '../lib/catalogBulkParsers.js';
import { embedIngredient, embedBatch, ingredientEmbedSeed } from '../services/embeddings.js';
import { extractIngredients } from '../services/catalogExtraction.js';
import { migrateBibleToCatalog } from '../scripts/migrateBibleToCatalog.js';
@@ -205,6 +208,105 @@ router.get('/refs/:refKind/:refId/ingredients', asyncHandler(async (req, res) =>
res.json(await catalogDB.listIngredientsForRef(req.params.refKind, req.params.refId));
}));
+// Bulk-create ingredients from a markdown / CSV / JSON dump — no LLM round
+// trip, unlike the scrap → extract → commit path. The whole batch commits
+// or rolls back together so a malformed entry can't leave the catalog
+// half-populated.
+router.post('/bulk-import', asyncHandler(async (req, res) => {
+ validateRequest(catalogBulkImportSchema, req.body);
+ const { format, payload, defaults = {} } = req.body;
+
+ // Parse → normalize → per-entry Zod validate BEFORE we open a transaction.
+ // Reject the whole batch on any invalid entry; report the first failure
+ // with its index so the user can fix the source file.
+ let parsed;
+ try {
+ parsed = parseBulkPayload(format, payload);
+ } catch (err) {
+ throw new ServerError(`Bulk import parse failed: ${err.message}`, { status: 400 });
+ }
+
+ const defaultTags = Array.isArray(defaults.tags) ? defaults.tags : [];
+ const entries = [];
+ for (let i = 0; i < parsed.length; i++) {
+ const entry = parsed[i];
+ // Merge default tags onto each row (dedup), then validate the full
+ // per-row shape against the same schema the single-create endpoint uses.
+ const mergedTags = Array.from(new Set([...(entry.tags || []), ...defaultTags]));
+ const result = catalogIngredientCreateSchema.safeParse({ ...entry, tags: mergedTags });
+ if (!result.success) {
+ const msg = result.error.errors?.[0]?.message || result.error.message;
+ throw new ServerError(`Bulk import entry ${i} invalid: ${msg}`, { status: 400 });
+ }
+ entries.push(result.data);
+ }
+
+ // Optional ref-links: same shape as the /link route, applied once per
+ // created ingredient inside the same transaction.
+ const refLinks = [];
+ const REF_FIELD_TO_KIND = { universeRef: 'universe', seriesRef: 'series', issueRef: 'issue', workRef: 'work' };
+ for (const [field, kind] of Object.entries(REF_FIELD_TO_KIND)) {
+ if (defaults[field]) refLinks.push({ refKind: kind, refId: defaults[field], role: defaults.role || `bulk-${kind}` });
+ }
+
+ const created = await withTransaction(async (client) => {
+ const out = [];
+ for (const entry of entries) {
+ const ing = await catalogDB.createIngredient({
+ type: entry.type,
+ name: entry.name,
+ payload: entry.payload || {},
+ tags: entry.tags || [],
+ }, { client });
+ // Stamp ref links inside the same transaction so a mid-batch failure
+ // rolls back the link rows alongside their ingredients.
+ for (const link of refLinks) {
+ await client.query(
+ `INSERT INTO catalog_ingredient_refs (ingredient_id, ref_kind, ref_id, role)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT (ingredient_id, ref_kind, ref_id, role) DO UPDATE
+ SET deleted = false, deleted_at = NULL`,
+ [ing.id, link.refKind, link.refId, link.role],
+ );
+ }
+ out.push({ id: ing.id, type: ing.type, name: ing.name });
+ }
+ return out;
+ });
+
+ console.log(`📥 Catalog bulk import: ${format} → ${created.length} ingredient(s)`);
+ res.status(201).json({ created, count: created.length });
+}));
+
+// Export one ref slice (universe/series/issue/work) as a portable bundle.
+// JSON is the canonical round-trip format; markdown + YAML are convenience
+// outputs. Relations and media-refs are intentionally absent — those tables
+// don't exist yet; when they ship the export helper will include them
+// without a payload-shape break (the consumer treats unknown keys as
+// passthrough).
+router.get('/export', asyncHandler(async (req, res) => {
+ const params = validateRequest(catalogExportQuerySchema, req.query);
+ const format = params.format || 'json';
+ const bundle = await catalogDB.exportSliceForRef(params.refKind, params.refId);
+ const baseName = `catalog-${params.refKind}-${params.refId}`.replace(/[^A-Za-z0-9._-]+/g, '_');
+ if (format === 'markdown') {
+ res.setHeader('Content-Type', 'text/markdown; charset=utf-8');
+ res.setHeader('Content-Disposition', `attachment; filename="${baseName}.md"`);
+ res.send(bundleToMarkdown(bundle));
+ return;
+ }
+ if (format === 'yaml') {
+ res.setHeader('Content-Type', 'application/yaml; charset=utf-8');
+ res.setHeader('Content-Disposition', `attachment; filename="${baseName}.yaml"`);
+ res.send(toYamlString(bundle));
+ return;
+ }
+ // json (default)
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
+ res.setHeader('Content-Disposition', `attachment; filename="${baseName}.json"`);
+ res.send(JSON.stringify(bundle, null, 2));
+}));
+
router.get('/sync', asyncHandler(async (req, res) => {
// The four `sync_sequence` columns are independent — accept either
// `?since=N` (uniform; only meaningful on the first pull where everyone's
diff --git a/server/routes/palette.js b/server/routes/palette.js
index 223e67acf8..27f19b8f63 100644
--- a/server/routes/palette.js
+++ b/server/routes/palette.js
@@ -53,6 +53,7 @@ const PALETTE_ACTIONS = [
{ id: 'dispatch_code_agent', label: 'Dispatch coding agent', section: 'Agents' },
{ id: 'code_agent_status', label: 'Coding agent status', section: 'Agents' },
{ id: 'time_now', label: 'Current time', section: 'System' },
+ { id: 'catalog_lookup', label: 'Look up ingredient…', section: 'Catalog' },
];
const PALETTE_ACTION_IDS = new Set(PALETTE_ACTIONS.map((a) => a.id));
diff --git a/server/routes/palette.test.js b/server/routes/palette.test.js
index 07fee18b02..d44872ca60 100644
--- a/server/routes/palette.test.js
+++ b/server/routes/palette.test.js
@@ -33,6 +33,15 @@ vi.mock('../services/feeds.js', () => ({
getItems: vi.fn(async () => []),
getFeeds: vi.fn(async () => []),
}));
+vi.mock('../services/catalogDB.js', () => ({
+ listIngredients: vi.fn(async () => ({
+ items: [
+ { id: 'character-1', type: 'character', name: 'Mira', payload: { physicalDescription: 'A tall stoic ranger.' }, tags: [] },
+ ],
+ nextOffset: 1,
+ })),
+ listRefsForIngredient: vi.fn(async () => [{ ingredientId: 'character-1', refKind: 'universe', refId: 'u1', role: 'cast' }]),
+}));
vi.mock('../services/askService.js', () => ({
VALID_MODES: new Set(['ask', 'advise', 'draft']),
runAsk: vi.fn(async function* () {
@@ -106,6 +115,18 @@ describe('GET /api/palette/manifest', () => {
expect(ids).not.toContain('ui_describe_visually');
});
+ it('exposes catalog_lookup with type+query parameters hydrated from the voice tool', async () => {
+ const res = await request(makeApp()).get('/api/palette/manifest');
+ const action = res.body.actions.find((a) => a.id === 'catalog_lookup');
+ expect(action).toBeTruthy();
+ expect(action.section).toBe('Catalog');
+ expect(action.label).toMatch(/look up/i);
+ expect(action.parameters?.properties?.query).toBeTruthy();
+ expect(action.parameters?.properties?.type?.enum).toEqual(
+ expect.arrayContaining(['character', 'place', 'object', 'idea', 'scene', 'concept']),
+ );
+ });
+
it('exposes ui_ask in the manifest with description hydrated from voice tools', async () => {
const res = await request(makeApp()).get('/api/palette/manifest');
const askAction = res.body.actions.find((a) => a.id === 'ui_ask');
@@ -144,6 +165,18 @@ describe('POST /api/palette/action/:id', () => {
expect(res.status).toBe(404);
});
+ it('dispatches catalog_lookup and returns shaped results with snippet + refsCount', async () => {
+ const res = await request(makeApp())
+ .post('/api/palette/action/catalog_lookup')
+ .send({ args: { query: 'Mira' } });
+ expect(res.status).toBe(200);
+ expect(res.body.ok).toBe(true);
+ expect(res.body.result.count).toBe(1);
+ const hit = res.body.result.results[0];
+ expect(hit).toMatchObject({ id: 'character-1', type: 'character', name: 'Mira', refsCount: 1 });
+ expect(hit.snippet).toMatch(/tall stoic ranger/);
+ });
+
it('dispatches ui_ask through the palette and returns the answer + sources', async () => {
const res = await request(makeApp())
.post('/api/palette/action/ui_ask')
diff --git a/server/services/catalogDB.js b/server/services/catalogDB.js
index 8d4073b8c8..7eba547995 100644
--- a/server/services/catalogDB.js
+++ b/server/services/catalogDB.js
@@ -666,6 +666,69 @@ export async function upsertRefFromPeer(ref) {
}
+/**
+ * Hydrate one ingredient with its scraps for the export bundle. Issues two
+ * queries: the sources join to look up the scrap ids, then a single batch
+ * lookup of those scraps. Returns `[]` when an ingredient has no sources.
+ */
+export async function listScrapsForIngredient(ingredientId) {
+ const result = await query(
+ `SELECT s.id, s.title, s.raw_text, s.source_kind, s.metadata,
+ s.created_at, s.updated_at
+ FROM catalog_scraps s
+ JOIN catalog_ingredient_sources src ON src.scrap_id = s.id
+ WHERE src.ingredient_id = $1
+ AND s.deleted = false
+ ORDER BY s.created_at ASC`,
+ [ingredientId],
+ );
+ return result.rows.map((row) => ({
+ id: row.id,
+ title: row.title,
+ rawText: row.raw_text,
+ sourceKind: row.source_kind,
+ metadata: row.metadata || {},
+ createdAt: row.created_at.toISOString(),
+ updatedAt: row.updated_at.toISOString(),
+ }));
+}
+
+/**
+ * Build an export bundle for one ref (universe/series/issue/work).
+ * Hydrates each ingredient + its scraps + ref links. Relations and media
+ * refs are intentionally omitted — the underlying tables (catalog_ingredient_relations,
+ * catalog_ingredient_media) don't exist yet (see PLAN items
+ * `[catalog-ingredient-relations]` / `[catalog-ingredient-media-refs]`).
+ * When they land, extend this helper to hydrate them too.
+ */
+export async function exportSliceForRef(refKind, refId) {
+ const rows = await listIngredientsForRef(refKind, refId);
+ // Hydrate scraps + refs in parallel per ingredient. Small N (one slice
+ // is typically <100 ingredients); a per-row round-trip is fine.
+ const ingredients = await Promise.all(rows.map(async ({ ingredient, role }) => {
+ const [scraps, refs] = await Promise.all([
+ listScrapsForIngredient(ingredient.id),
+ listRefsForIngredient(ingredient.id),
+ ]);
+ const { embedding: _embedding, ...rest } = ingredient;
+ return {
+ ...rest,
+ // The role this ingredient plays for the queried ref — handy for
+ // round-trip re-imports that want to preserve roleness without
+ // re-deriving it from the full refs list.
+ roleForExportedRef: role,
+ refs,
+ scraps,
+ };
+ }));
+ return {
+ version: 1,
+ ref: { kind: refKind, id: refId },
+ exportedAt: new Date().toISOString(),
+ ingredients,
+ };
+}
+
export async function getCatalogStats() {
const [byTypeResult, scrapResult, withEmb] = await Promise.all([
query(`SELECT type, COUNT(*) AS count FROM catalog_ingredients WHERE deleted = false GROUP BY type`),
diff --git a/server/services/voice/tools.js b/server/services/voice/tools.js
index 208d593573..619cfec943 100644
--- a/server/services/voice/tools.js
+++ b/server/services/voice/tools.js
@@ -16,6 +16,7 @@ import { scheduleTimer } from './timers.js';
import { getUserTimezone, todayInTimezone, getLocalParts, getUtcOffsetMs } from '../../lib/timezone.js';
import * as journal from '../brainJournal.js';
import { resolveNavCommand, normalizeLabel } from '../../lib/navManifest.js';
+import { listIngredients as listCatalogIngredients, listRefsForIngredient } from '../catalogDB.js';
import { runAsk, VALID_MODES as ASK_VALID_MODES } from '../askService.js';
import * as imageGen from '../imageGen/index.js';
import { createImageGenWaiter } from '../imageGenWaiter.js';
@@ -204,6 +205,7 @@ const TOOL_GROUPS = {
pipeline_open_stage: 'pipeline',
dispatch_code_agent: 'code',
code_agent_status: 'code',
+ catalog_lookup: 'catalog',
// UNGROUPED = always-on: time_now, daily_log_append, ui_navigate.
// brain_capture used to be always-on, but that caused form-fill turns
// ("fill description with X") to be misrouted to brain_capture because
@@ -297,6 +299,10 @@ const GROUP_INTENT = {
// (pipeline.js strips it from the spec list when off).
code: /\b(?:have (?:claude|codex|gemini|the agent|an agent)\b|dispatch (?:a |an )?(?:coding |code )?agent|spin up an agent|code (?:it )?up|open a pr|pull request|refactor|(?:implement|debug|rewrite|patch)\b[^.!?\n]{0,40}\b(?:bug|tests?|function|method|build|lint|type ?error|error|code|file|module|endpoint|route|component|class|api|schema|migration|script|flag|regression|handler|parser|service|hook|query|registry|config)\b|fix (?:the |a |an |my )?(?:bug|test|tests|failing|function|method|build|lint|type|error|code|file|module|endpoint|route|component)|write (?:a |the |some )?(?:unit |integration )?tests?|add (?:a |an |the )?(?:flag|function|method|endpoint|route|test|migration)\b|(?:how(?:'s| is| are)?|status of|progress on|what(?:'s| is)? happening (?:with|on)|where (?:are|is) (?:we|it|that|the))\b[^.!?\n]{0,40}\b(?:coding (?:task|agent|job)|code agent|dispatched (?:task|job|agent)|pull request|the agent|the pr|that pr|my pr|the task)\b|\bis (?:the |that |my )?(?:coding |code )?(?:agent|task) (?:still |yet )?(?:running|going|working|done|finished))/i,
ui: UI_INTENT_RE,
+ // Creative catalog lookups — "find my character X", "what scenes feature Y",
+ // "look up the place named Z", "search my catalog for …". Tight enough that
+ // generic "find" / "search" don't trip it (those still go to brain_search).
+ catalog: /\b(catalog|ingredient|cast|creative library)\b|\b(?:look ?up|find|search|show me|do i have|any)\b[^.!?\n]{0,30}\b(?:character|place|object|scene|concept|idea|prop|setting|location|faction)s?\b/i,
};
// Fail-fast at import time: any group referenced in TOOL_GROUPS that has no
@@ -443,6 +449,28 @@ const describeWeatherCode = (code) => WEATHER_CODES[code] ?? 'unknown conditions
const DEFAULT_LAT = 37.7749;
const DEFAULT_LON = -122.4194;
+// Catalog ingredient kinds. Hardcoded for now — the shared catalog type
+// registry (PLAN item `[catalog-shared-type-registry]`) will replace this.
+const CATALOG_INGREDIENT_TYPES = ['character', 'place', 'object', 'idea', 'scene', 'concept'];
+
+// Pull a short snippet from an ingredient's type-specific payload. Mirrors
+// the fallback chain used by client/src/pages/Catalog.jsx so voice + UI agree
+// on what "the body" of an ingredient is. Trimmed to 200 chars.
+const catalogPayloadSnippet = (payload) => {
+ if (!payload || typeof payload !== 'object') return '';
+ const raw = payload.physicalDescription
+ || payload.description
+ || payload.summary
+ || payload.personality
+ || payload.significance
+ || payload.role
+ || payload.notes
+ || '';
+ const text = String(raw).trim().replace(/\s+/g, ' ');
+ if (text.length <= 200) return text;
+ return `${text.slice(0, 197)}…`;
+};
+
const TOOLS = [
{
name: 'brain_capture',
@@ -2034,6 +2062,44 @@ const TOOLS = [
return { ok: true, count: matched.length, agents: matched, summary };
},
},
+
+ {
+ name: 'catalog_lookup',
+ description:
+ 'Search the creative ingredients catalog (characters, places, objects, ideas, scenes, concepts) by name or content. ' +
+ 'Use when the user asks "do I have a character named X?", "find my places", "look up the scene where Y happens", "what concepts are in my catalog about Z". ' +
+ 'Returns up to `limit` matches (default 5) with id, name, type, a short snippet, and link count. Pass `type` to narrow to a single kind.',
+ parameters: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'Free-text search across name + payload content. Use the user\'s most distinctive phrasing.' },
+ type: { type: 'string', enum: CATALOG_INGREDIENT_TYPES, description: 'Optional: restrict to one ingredient kind.' },
+ limit: { type: 'integer', description: 'Max results (default 5, max 20).' },
+ },
+ required: ['query'],
+ },
+ execute: async ({ query, type, limit = 5 } = {}) => {
+ if (typeof query !== 'string' || !query.trim()) throw new Error('query is required');
+ const q = query.trim();
+ const max = clampLimit(limit, 5, 20);
+ const filterType = CATALOG_INGREDIENT_TYPES.includes(type) ? type : undefined;
+ const { items } = await listCatalogIngredients({ query: q, type: filterType, limit: max });
+ const results = await Promise.all(items.map(async (ing) => {
+ const refs = await listRefsForIngredient(ing.id);
+ return {
+ id: ing.id,
+ name: ing.name,
+ type: ing.type,
+ snippet: catalogPayloadSnippet(ing.payload),
+ refsCount: refs.length,
+ };
+ }));
+ const summary = results.length
+ ? `Found ${results.length} catalog match${results.length === 1 ? '' : 'es'} for "${q}"${filterType ? ` (${filterType})` : ''}.`
+ : `No catalog ingredients matched "${q}"${filterType ? ` in ${filterType}` : ''}.`;
+ return { ok: true, count: results.length, results, summary };
+ },
+ },
];
const toSpec = (t) => ({
diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.js
index d6e7e86c93..a858ce13ac 100644
--- a/server/services/voice/tools.test.js
+++ b/server/services/voice/tools.test.js
@@ -165,6 +165,12 @@ const activeAppsRef = { value: [
vi.mock('../apps.js', () => ({
getActiveApps: vi.fn(async () => activeAppsRef.value),
}));
+const catalogItemsRef = { value: [] };
+const catalogRefsRef = { value: [] };
+vi.mock('../catalogDB.js', () => ({
+ listIngredients: vi.fn(async () => ({ items: catalogItemsRef.value, nextOffset: catalogItemsRef.value.length })),
+ listRefsForIngredient: vi.fn(async () => catalogRefsRef.value),
+}));
// dispatch_code_agent resolves a code-capable provider when none is pinned.
// Default the active provider to a code-capable (tui) one so the inherit path
// is exercised; individual tests override for the API-default / substitution
@@ -1481,4 +1487,45 @@ describe('new tool intent routing', () => {
expect(classifyIntent("what's on this chart?").has('vision')).toBe(true);
expect(classifyIntent('describe the cybercity').has('vision')).toBe(true);
});
+ it('routes catalog lookups to the catalog group', () => {
+ expect(classifyIntent('find my character Mira').has('catalog')).toBe(true);
+ expect(classifyIntent('search my catalog for ideas').has('catalog')).toBe(true);
+ expect(classifyIntent('look up the scene in the woods').has('catalog')).toBe(true);
+ expect(classifyIntent('what time is it').has('catalog')).toBe(false);
+ });
+});
+
+describe('catalog_lookup', () => {
+ afterEach(() => {
+ catalogItemsRef.value = [];
+ catalogRefsRef.value = [];
+ });
+ it('requires a non-empty query', async () => {
+ await expect(dispatchTool('catalog_lookup', { query: '' })).rejects.toThrow(/query is required/);
+ await expect(dispatchTool('catalog_lookup', {})).rejects.toThrow(/query is required/);
+ });
+ it('returns shaped results with snippet + refsCount and ignores invalid type', async () => {
+ catalogItemsRef.value = [
+ { id: 'place-1', type: 'place', name: 'The Reach', payload: { description: 'A windswept plateau under perpetual storm clouds.' }, tags: [] },
+ ];
+ catalogRefsRef.value = [
+ { ingredientId: 'place-1', refKind: 'universe', refId: 'u-1', role: 'setting' },
+ { ingredientId: 'place-1', refKind: 'series', refId: 's-1', role: 'setting' },
+ ];
+ const res = await dispatchTool('catalog_lookup', { query: 'reach', type: 'bogus', limit: 5 });
+ expect(res.ok).toBe(true);
+ expect(res.count).toBe(1);
+ const hit = res.results[0];
+ expect(hit).toMatchObject({ id: 'place-1', type: 'place', name: 'The Reach', refsCount: 2 });
+ expect(hit.snippet).toMatch(/windswept plateau/);
+ expect(res.summary).toMatch(/Found 1 catalog match for "reach"/);
+ });
+ it('reports zero matches gracefully', async () => {
+ catalogItemsRef.value = [];
+ const res = await dispatchTool('catalog_lookup', { query: 'nope' });
+ expect(res.ok).toBe(true);
+ expect(res.count).toBe(0);
+ expect(res.results).toEqual([]);
+ expect(res.summary).toMatch(/No catalog ingredients matched "nope"/);
+ });
});