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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(catalog): extract ideas, scenes, and concepts from ingest scraps
[._.]/ Adam Eivy7e4b80ece4b4
diff --git a/client/src/pages/CatalogIngest.jsx b/client/src/pages/CatalogIngest.jsxindex f4cd807770..e3768629aa 100644--- a/client/src/pages/CatalogIngest.jsx+++ b/client/src/pages/CatalogIngest.jsx@@ -16,18 +16,29 @@ import {commitCatalogScrapDraft,} from '../services/apiCatalog';+// One review section per ingredient type. The first three are bible-shaped+// (character/place/object) and use `physicalDescription`/`description` as the+// primary editable text; the last three are light-shaped (idea/scene/concept)+// and use `summary` — matching PRIMARY_CONTENT_KEY in Catalog.jsx.const KIND_SECTIONS = [{ key: 'characters', label: 'Characters', type: 'character' },{ key: 'places', label: 'Places', type: 'place' },{ key: 'objects', label: 'Objects', type: 'object' },+ { key: 'ideas', label: 'Ideas', type: 'idea' },+ { key: 'scenes', label: 'Scenes', type: 'scene' },+ { key: 'concepts', label: 'Concepts', type: 'concept' },];// Initial stage list, used until the server's `start` frame supplies the real-// one. Matches the three sections rendered in the review phase so the panel-// never looks empty between click and first frame.-const INITIAL_STAGES = KIND_SECTIONS.map((s) => ({- id: s.key, label: s.label, status: 'pending', count: 0,-}));+// one. Mirrors server-side EXTRACTION_STAGES — three bible passes plus one+// bundled light pass (`ideasScenesConcepts`) — so the panel never looks empty+// between click and first frame.+const INITIAL_STAGES = [+ { id: 'characters', label: 'Characters', status: 'pending', count: 0 },+ { id: 'places', label: 'Places', status: 'pending', count: 0 },+ { id: 'objects', label: 'Objects', status: 'pending', count: 0 },+ { id: 'ideasScenesConcepts', label: 'Ideas, scenes & concepts', status: 'pending', count: 0 },+];function StageIcon({ status }) {if (status === 'completed' || status === 'done') {@@ -53,8 +64,8 @@ export default function CatalogIngest() {const [stages, setStages] = useState(INITIAL_STAGES);// The draft returned by extractFromCatalogScrap(): per-kind candidate arrays// editable inline + checkbox-gated. Defaults all to selected.- const [draft, setDraft] = useState({ characters: [], places: [], objects: [] });- const [selected, setSelected] = useState({ characters: new Set(), places: new Set(), objects: new Set() });+ 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() });// 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@@ -89,8 +100,8 @@ export default function CatalogIngest() {setPhase('paste');setScrapId(null);setStages(INITIAL_STAGES);- setDraft({ characters: [], places: [], objects: [] });- setSelected({ characters: new Set(), places: new Set(), objects: new Set() });+ setDraft({ characters: [], places: [], objects: [], ideas: [], scenes: [], concepts: [] });+ setSelected({ characters: new Set(), places: new Set(), objects: new Set(), ideas: new Set(), scenes: new Set(), concepts: new Set() });};const handleIngest = async (e) => {@@ -109,22 +120,22 @@ export default function CatalogIngest() {.catch((err) => { toast.error(err?.message || 'Extraction failed'); return null; });setSubmitting(false);if (!result?.draft) { setPhase('paste'); return; }- const d = {- characters: Array.isArray(result.draft.characters) ? result.draft.characters : [],- places: Array.isArray(result.draft.places) ? result.draft.places : [],- objects: Array.isArray(result.draft.objects) ? result.draft.objects : [],- };+ const d = Object.fromEntries(KIND_SECTIONS.map((s) => [+ s.key,+ Array.isArray(result.draft[s.key]) ? result.draft[s.key] : [],+ ]));setDraft(d);- setSelected({- characters: new Set(d.characters.map((_, i) => i)),- places: new Set(d.places.map((_, i) => i)),- objects: new Set(d.objects.map((_, i) => i)),- });+ setSelected(Object.fromEntries(KIND_SECTIONS.map((s) => [s.key, new Set(d[s.key].map((_, i) => i))])));// Prefer server-supplied stage list; otherwise mark defaults completed.+ // The bundled `ideasScenesConcepts` stage has no matching `d[id]` array,+ // so its count is the sum of the three light kinds it backs.if (Array.isArray(result.draft.stages) && result.draft.stages.length > 0) {setStages(result.draft.stages.map((s) => ({ ...s, status: s.status || 'completed' })));} else {- setStages((prev) => prev.map((s) => ({ ...s, status: 'completed', count: d[s.id]?.length || 0 })));+ const countForStage = (id) => id === 'ideasScenesConcepts'+ ? d.ideas.length + d.scenes.length + d.concepts.length+ : d[id]?.length || 0;+ setStages((prev) => prev.map((s) => ({ ...s, status: 'completed', count: countForStage(s.id) })));}setPhase('review');};@@ -198,8 +209,8 @@ export default function CatalogIngest() {<div><h1 className="text-2xl font-bold text-white">Catalog Ingest</h1><p className="text-sm text-gray-400 mt-1">- Paste prose, notes, or a synopsis. The LLM extracts characters, places, and objects;- review and commit only what you want to keep.+ Paste prose, notes, or a synopsis. The LLM extracts characters, places, and objects+ alongside ideas, scenes, and concepts; review and commit only what you want to keep.</p></div></div>@@ -330,12 +341,15 @@ function ReviewSection({ section, items, selected, onToggle, onSelectAll, onPatc<ul className="space-y-2">{items.map((c, idx) => {const baseId = `${section.key}-${idx}`;- // Characters use `physicalDescription` (matches the canon shape from- // sanitizeCharacter); places/objects use `description`. Without this- // a character's LLM-extracted physicalDescription would render as an- // empty textarea and edits would land in a sibling `description` key- // that the canon shape doesn't read.- const descField = section.type === 'character' ? 'physicalDescription' : 'description';+ // Each type's primary editable field matches PRIMARY_CONTENT_KEY in+ // Catalog.jsx: character → physicalDescription (canon shape from+ // sanitizeCharacter); place/object → description; idea/scene/concept+ // → summary. Without this an edit lands in a sibling key the+ // catalog editor doesn't read.+ let descField;+ if (section.type === 'character') descField = 'physicalDescription';+ else if (section.type === 'place' || section.type === 'object') descField = 'description';+ else descField = 'summary';return (<li key={baseId} className="border border-port-border rounded p-3 bg-port-bg/40 flex items-start gap-2"><input id={`${baseId}-check`} type="checkbox" checked={selected.has(idx)} onChange={() => onToggle(idx)}diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex d590344b36..6d4af29598 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -42,6 +42,13 @@"returnsJson": true,"variables": []},+ "catalog-ideas-scenes-concepts": {+ "name": "Catalog Ingest — Ideas / Scenes / Concepts",+ "description": "Extract reusable narrative fragments — ideas (premises), scenes (dramatic beats), and concepts (lore, magic systems, factions) — from a raw user-pasted scrap into the Creative Ingredients Catalog. Runs alongside the character/place/object writers-room passes during catalog ingest.",+ "model": "default",+ "returnsJson": true,+ "variables": []+ },"cd-treatment": {"name": "Creative Director — Treatment","description": "Plan a long-form generated-video project: write the logline, synopsis, and scene-by-scene treatment.",diff --git a/data.reference/prompts/stages/catalog-ideas-scenes-concepts.md b/data.reference/prompts/stages/catalog-ideas-scenes-concepts.mdnew file mode 100644index 0000000000..13df7e1e22--- /dev/null+++ b/data.reference/prompts/stages/catalog-ideas-scenes-concepts.md@@ -0,0 +1,63 @@+# Catalog Ingest — Ideas, Scenes, Concepts++You are a creative analyst surfacing reusable narrative fragments from raw author-pasted text — material that is NOT a character, place, or physical object, but is still worth indexing for later reuse.++You will return three arrays in a single JSON response: `ideas`, `scenes`, and `concepts`. The author has pasted prose, notes, or stream-of-consciousness into a personal creative catalog. They will review each candidate and selectively commit. Quality matters more than coverage — surface only what is genuinely reusable.++## Source text++```+{{draftBody}}+```++## Definitions++- **idea** — a story premise, hook, "what if?", logline, or kernel. The smallest unit of "I might write something around this." Typically 1–3 sentences. Examples: "What if memory could be inherited like a genetic trait?" / "A locksmith who can only open doors that are already unlocked." / "A small town where everyone forgets one specific person." NOT a fully-formed plot.++- **scene** — a specific dramatic beat or moment described concretely enough that it could be the seed for a written scene. Has a setting, at least one actor (named or generic), and a beat that moves emotionally or narratively. Examples: "Two old friends in a diner at 3am — one is about to tell the other they're dying." / "A child finds a key in their backyard that doesn't fit any lock in the house." NOT a generic vibe or atmosphere.++- **concept** — an abstract structural, thematic, or world-building idea — a magic system, a piece of lore, a faction, a rule of how the world works, a recurring metaphor. NOT tied to one moment. Examples: "Magic costs sleep — every spell trades an hour of future sleep." / "The factions all worship the same dead god and disagree about which day to mourn." / "Memory is treated as currency by the merchant guild." NOT a character or a place.++## Extraction rules++1. **Be selective.** Better to return fewer high-quality entries than to pad the lists. If the text contains zero of a given kind, return `[]` for that kind — not invented filler.+2. **Stay grounded in the source.** Do not invent details the text does not support. If the text says "a knight", do not name them.+3. **No duplicates across kinds.** A "what if a magic system costs sleep" line is a `concept`, not also an `idea`. Pick the best-fit kind.+4. **Do not extract characters, places, or physical objects.** Those are handled by separate passes. If a sentence is about a recurring object or a named character, skip it here.+5. **Title each entry** — a 2–6 word handle the author will see in the catalog list. Concrete, scannable. NOT a sentence.++## Output contract++Return ONLY valid JSON in this exact shape — no prose, no markdown fence, no commentary:++```json+{+ "ideas": [+ {+ "name": "string (2-6 word handle)",+ "summary": "string (1-3 sentence pitch)",+ "tags": ["string", ...],+ "evidence": "string (≤ 200 char verbatim quote from the source)"+ }+ ],+ "scenes": [+ {+ "name": "string (2-6 word handle)",+ "summary": "string (1-2 sentence beat)",+ "setting": "string (where + when, ≤ 80 chars) or null",+ "actors": ["string", ...],+ "tags": ["string", ...],+ "evidence": "string (≤ 200 char verbatim quote from the source)"+ }+ ],+ "concepts": [+ {+ "name": "string (2-6 word handle)",+ "summary": "string (1-3 sentence explanation)",+ "kind": "string (e.g. 'magic-system', 'faction', 'lore', 'metaphor', 'rule')",+ "tags": ["string", ...],+ "evidence": "string (≤ 200 char verbatim quote from the source)"+ }+ ]+}+```diff --git a/scripts/migrations/048-catalog-ideas-scenes-concepts-stage.js b/scripts/migrations/048-catalog-ideas-scenes-concepts-stage.jsnew file mode 100644index 0000000000..4845102310--- /dev/null+++ b/scripts/migrations/048-catalog-ideas-scenes-concepts-stage.js@@ -0,0 +1,87 @@+/**+ * Seed the `catalog-ideas-scenes-concepts` prompt stage into existing installs.+ *+ * Mirrors 043-story-builder-prompts.js — copies the `.md` template from+ * `data.reference/prompts/stages/` and merges the stage-config entry into+ * `data/prompts/stage-config.json`. Boot runs migrations (server/index.js)+ * BEFORE the AI toolkit reads stage-config.json, but does NOT run+ * `setup-data.js`. Without this migration, an upgrade that pulls main and+ * `pm2 restart`s (rather than running `update.sh`) leaves the new stage+ * unregistered — catalog ingest's light pass would throw "Stage+ * catalog-ideas-scenes-concepts not found" while the three bible passes+ * succeed, leaving the Ingest UI with a red failed row and no idea / scene /+ * concept candidates to review.+ */++import { access, copyFile, mkdir, readFile, constants } from 'fs/promises';+import { dirname, join } from 'path';+import { atomicWrite } from '../../server/lib/fileUtils.js';++const STAGES = ['catalog-ideas-scenes-concepts'];++export default {+ async up({ rootDir }) {+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');+ await mkdir(stagesDir, { recursive: true });++ // 1. Copy any missing prompt templates.+ for (const key of STAGES) {+ const filename = `${key}.md`;+ const dataPath = join(stagesDir, filename);+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', filename);+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);+ if (exists) {+ console.log(`📝 catalog ingest prompt: ${filename} already present`);+ continue;+ }+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);+ if (!sampleExists) {+ console.warn(`⚠️ catalog ingest: sample missing for ${filename} — skipping copy`);+ continue;+ }+ try {+ await copyFile(samplePath, dataPath);+ console.log(`✅ seeded ${filename}`);+ } catch (err) {+ console.warn(`⚠️ catalog ingest: copy failed for ${filename}: ${err.message}`);+ }+ }++ // 2. Merge missing stage-config entries.+ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);+ if (!sampleConfigExists) {+ console.warn('⚠️ catalog ingest: data.reference stage-config.json missing — skipping config write');+ return;+ }+ try {+ const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));+ const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);+ const installed = installedExists+ ? JSON.parse(await readFile(installedConfigPath, 'utf8'))+ : { stages: {} };+ installed.stages = installed.stages || {};+ let added = 0;+ for (const key of STAGES) {+ if (installed.stages[key]) continue;+ if (!sample?.stages?.[key]) {+ console.warn(`⚠️ catalog ingest: sample stage-config missing ${key} — skipping`);+ continue;+ }+ installed.stages[key] = sample.stages[key];+ added += 1;+ }+ if (added === 0) {+ console.log('📝 catalog ingest stage-config: all entries already present');+ return;+ }+ await mkdir(dirname(installedConfigPath), { recursive: true });+ await atomicWrite(installedConfigPath, `${JSON.stringify(installed, null, 2)}\n`);+ const action = installedExists ? 'merged' : 'created';+ console.log(`📝 catalog ingest stage-config (${action}): ${added} added`);+ } catch (err) {+ console.warn(`⚠️ catalog ingest: stage-config merge failed: ${err.message}`);+ }+ },+};diff --git a/server/services/catalogExtraction.js b/server/services/catalogExtraction.jsindex 3aa90a2bbf..845f977f8e 100644--- a/server/services/catalogExtraction.js+++ b/server/services/catalogExtraction.js@@ -2,14 +2,16 @@* Catalog Extraction Service** Runs LLM passes over a raw user-pasted scrap and returns a typed draft of- * candidate ingredients (characters, places, objects) the user can review- * and selectively commit via POST /api/catalog/scraps/:id/commit.+ * candidate ingredients (characters, places, objects, ideas, scenes,+ * concepts) the user can review and selectively commit via+ * POST /api/catalog/scraps/:id/commit.*- * Reuses server/lib/bibleExtractor.js for the three storyBible-shaped types- * — characters, places, objects — so the catalog payload is identical to the- * shape stored in universe canon. Idea/scene/concept LLM extraction is a- * follow-up (Phase 5b); for now they're created manually via POST- * /api/catalog/ingredients.+ * Three passes reuse server/lib/bibleExtractor.js for the storyBible-shaped+ * types (characters, places, objects) so their payloads are identical to the+ * shape stored in universe canon. A fourth pass calls a single LLM stage+ * (`catalog-ideas-scenes-concepts`) that returns all three light-shape types+ * in one round-trip — they share a corpus and an output schema, so packaging+ * them as one call cuts cost while still surfacing as a UI stage.** Streams progress as `catalog:extract:progress` socket frames so the Ingest* UI can render a live stage checklist while waiting on the parallel passes.@@ -17,20 +19,114 @@import { randomUUID } from 'crypto';import { extractBible } from '../lib/bibleExtractor.js';-import { BIBLE_KINDS, BIBLE_FIELD } from '../lib/storyBible.js';+import { runStagedLLM } from '../lib/stageRunner.js';+import { BIBLE_KINDS, BIBLE_FIELD, BIBLE_LIMITS } from '../lib/storyBible.js';import { catalogEvents } from './catalogEvents.js';-// One stage per bible kind; runs in parallel under the same runId. Derived-// from BIBLE_KINDS so a future kind picked up by extractBible flows through-// here automatically.+// Light-shape stage that bundles ideas/scenes/concepts into one LLM call.+// Surfaced to the UI as a single stage row — the three result arrays land+// in `draft.ideas` / `draft.scenes` / `draft.concepts` and the user reviews+// them as separate sections.+const LIGHT_STAGE_ID = 'ideasScenesConcepts';++// Stage list emitted to the Ingest UI. Three bible stages run via extractBible+// (one per BIBLE_KINDS entry — a future bible kind picks up automatically),+// plus the one bundled light stage. Order matches the typical user mental+// model: structural first, then narrative shards.const titleCase = (s) => s.charAt(0).toUpperCase() + s.slice(1) + 's';-export const EXTRACTION_STAGES = Object.freeze(- BIBLE_KINDS.map((kind) => ({+export const EXTRACTION_STAGES = Object.freeze([+ ...BIBLE_KINDS.map((kind) => ({id: BIBLE_FIELD[kind], // 'characters' | 'places' | 'objects'label: titleCase(kind),kind,})),-);+ { id: LIGHT_STAGE_ID, label: 'Ideas, scenes & concepts' },+]);++// Field caps for the light-shape sanitizer below. Generous enough for+// reasonable LLM output, tight enough that a runaway response can't load+// a multi-MB string into the catalog payload. NAME_MAX / TAG_MAX /+// TAGS_PER_ENTRY_MAX MUST track BIBLE_LIMITS — those are the boundaries the+// `/api/catalog/scraps/:id/commit` Zod schema enforces, and a sanitizer cap+// looser than the schema would let a row pass the extractor but reject the+// whole batch on commit.+const LIGHT_LIMITS = Object.freeze({+ NAME_MAX: BIBLE_LIMITS.NAME_MAX,+ SUMMARY_MAX: 2000,+ EVIDENCE_MAX: 400,+ SETTING_MAX: 200,+ KIND_MAX: 64,+ TAG_MAX: BIBLE_LIMITS.TAG_MAX,+ TAGS_MAX: BIBLE_LIMITS.TAGS_PER_ENTRY_MAX,+ ACTORS_MAX: 12,+});++const trim = (v, max) =>+ typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : null;++const trimArray = (arr, itemMax, listMax) => {+ if (!Array.isArray(arr)) return [];+ const out = [];+ for (const item of arr) {+ const t = trim(item, itemMax);+ if (t && !out.includes(t)) out.push(t);+ if (out.length >= listMax) break;+ }+ return out;+};++// Per-kind light-shape sanitizer. Drops rows with no name (the primary key+// for review selection), and packages everything except `name`/`tags` into+// the catalog payload so the commit path's payload-splat works cleanly.+function sanitizeLightEntry(kind, raw) {+ if (!raw || typeof raw !== 'object') return null;+ const name = trim(raw.name, LIGHT_LIMITS.NAME_MAX);+ if (!name) return null;+ const summary = trim(raw.summary, LIGHT_LIMITS.SUMMARY_MAX);+ const evidence = trim(raw.evidence, LIGHT_LIMITS.EVIDENCE_MAX);+ const tags = trimArray(raw.tags, LIGHT_LIMITS.TAG_MAX, LIGHT_LIMITS.TAGS_MAX);+ const entry = { name, tags };+ if (summary) entry.summary = summary;+ if (evidence) entry.evidence = evidence;+ if (kind === 'scene') {+ const setting = trim(raw.setting, LIGHT_LIMITS.SETTING_MAX);+ const actors = trimArray(raw.actors, LIGHT_LIMITS.NAME_MAX, LIGHT_LIMITS.ACTORS_MAX);+ if (setting) entry.setting = setting;+ if (actors.length > 0) entry.actors = actors;+ } else if (kind === 'concept') {+ // The LLM emits `kind` (magic-system / faction / lore / metaphor / rule).+ // Stored on the payload as-is — `type` is a separate column at the row+ // level, so `payload.kind` doesn't collide with the catalog's outer type+ // discriminator and downstream readers (Catalog.jsx snippet fallbacks,+ // future detail-page renderers) can find the field where the prompt put it.+ const conceptKind = trim(raw.kind, LIGHT_LIMITS.KIND_MAX);+ if (conceptKind) entry.kind = conceptKind;+ }+ return entry;+}++/**+ * Run the bundled ideas/scenes/concepts LLM call. Returns three arrays+ * sanitized into the catalog payload shape. Tolerant on parse failure — a+ * malformed response logs and yields empty arrays, mirroring extractBible's+ * sanitizeBibleList tolerance for missing keys.+ */+async function extractIdeasScenesConcepts({ corpus, providerOverride }) {+ const result = await runStagedLLM('catalog-ideas-scenes-concepts', {+ draftBody: corpus,+ returnsJson: true,+ }, {+ providerOverride,+ returnsJson: true,+ source: 'catalog-extract-ideas-scenes-concepts',+ });+ const content = result?.content || {};+ return {+ ideas: (Array.isArray(content.ideas) ? content.ideas : []).map((r) => sanitizeLightEntry('idea', r)).filter(Boolean),+ scenes: (Array.isArray(content.scenes) ? content.scenes : []).map((r) => sanitizeLightEntry('scene', r)).filter(Boolean),+ concepts: (Array.isArray(content.concepts) ? content.concepts : []).map((r) => sanitizeLightEntry('concept', r)).filter(Boolean),+ };+}/*** Extract candidate ingredients from a raw scrap.@@ -55,12 +151,16 @@ export const EXTRACTION_STAGES = Object.freeze(* of `extractBible` pass server-curated content so they don't need this; the* catalog caller passes ARBITRARY USER PASTE and does.*- * Replacement uses zero-width joiner between the backticks so the visual- * content is preserved for any model that wants to comment on it.+ * Replacement inserts a zero-width joiner between every adjacent pair of+ * backticks in a run of 3 or more, so the visual content stays readable but+ * no three-backtick subsequence survives. A naive `/```/g` replace fails on+ * runs of 4+ — the leftover backtick after the first match reforms a triple+ * with the trailing pair of the replacement.*/function neutralizeFenceDelimiters(text) {// U+200D zero-width joiner; safe inside JSON strings, invisible in prose.- return text.replace(/```/g, '```');+ // Match every run of 3+ backticks and rebuild it with ZWJ between each.+ return text.replace(/`{3,}/g, (run) => run.split('').join(''));}export async function extractIngredients({ rawText, scrapId = null, providerOverride } = {}) {@@ -80,38 +180,57 @@ export async function extractIngredients({ rawText, scrapId = null, providerOveremit({ type: 'start', stages: EXTRACTION_STAGES.map(({ id, label }) => ({ id, label })) });- // Run all three bible-extract passes in parallel — they're independent and- // the corpus is identical. Each settles to a per-stage status frame so the- // UI flips the corresponding row to ✓ / ✗ as work completes.- const promises = EXTRACTION_STAGES.map(async ({ id, kind }) => {- emit({ type: 'stage', id, status: 'running' });+ // Run every stage in parallel — they're independent and share the corpus.+ // Each settles to a per-stage status frame so the UI flips the corresponding+ // row to ✓ / ✗ as work completes. Bible stages return one array; the+ // light-shape stage returns three (ideas/scenes/concepts) under one stage id.+ const runStage = async (stage) => {+ emit({ type: 'stage', id: stage.id, status: 'running' });try {+ if (stage.id === LIGHT_STAGE_ID) {+ const out = await extractIdeasScenesConcepts({ corpus, providerOverride });+ const count = out.ideas.length + out.scenes.length + out.concepts.length;+ emit({ type: 'stage', id: stage.id, status: 'completed', count });+ return { id: stage.id, light: out, error: null };+ }const result = await extractBible({- kind,+ kind: stage.kind,corpus,existing: [],providerOverride,- source: `catalog-extract-${id}`,+ source: `catalog-extract-${stage.id}`,});- emit({ type: 'stage', id, status: 'completed', count: result.extracted.length });- return { id, extracted: result.extracted, error: null };+ emit({ type: 'stage', id: stage.id, status: 'completed', count: result.extracted.length });+ return { id: stage.id, extracted: result.extracted, error: null };} catch (err) {- console.error(`❌ catalog extract ${id} failed: ${err.message}`);- emit({ type: 'stage', id, status: 'failed', error: err.message });- return { id, extracted: [], error: err.message };+ console.error(`❌ catalog extract ${stage.id} failed: ${err.message}`);+ emit({ type: 'stage', id: stage.id, status: 'failed', error: err.message });+ return { id: stage.id, error: err.message };}- });+ };- const settled = await Promise.all(promises);+ const settled = await Promise.all(EXTRACTION_STAGES.map(runStage));- const draft = Object.fromEntries(EXTRACTION_STAGES.map((s) => [s.id, []]));- const stages = settled.map(({ id, extracted, error }) => {- draft[id] = extracted;+ // Default empty arrays for every result key the UI can render — keeps the+ // commit path's `Array.isArray(result.draft.x)` guard happy even when a+ // stage failed or returned nothing.+ const draft = { characters: [], places: [], objects: [], ideas: [], scenes: [], concepts: [] };+ const stages = settled.map(({ id, extracted, light, error }) => {+ let count = 0;+ if (light) {+ draft.ideas = light.ideas;+ draft.scenes = light.scenes;+ draft.concepts = light.concepts;+ count = light.ideas.length + light.scenes.length + light.concepts.length;+ } else if (extracted) {+ draft[id] = extracted;+ count = extracted.length;+ }return {id,label: EXTRACTION_STAGES.find((s) => s.id === id).label,status: error ? 'failed' : 'completed',- count: extracted.length,+ count,error: error || undefined,};});diff --git a/server/services/catalogExtraction.test.js b/server/services/catalogExtraction.test.jsnew file mode 100644index 0000000000..55c51c13e2--- /dev/null+++ b/server/services/catalogExtraction.test.js@@ -0,0 +1,243 @@+/**+ * Unit tests for catalogExtraction — bibleExtractor + stageRunner are both+ * mocked so this test stays pure (no LLM call). Asserts:+ * - Stage list covers the three bible kinds + one bundled light stage+ * - Each stage emits running → completed progress frames+ * - Failures isolate (one kind's throw doesn't poison the rest)+ * - The returned draft groups extracted entries under the right field key+ * - The bundled light stage splits its LLM response into ideas/scenes/concepts+ * - Light-shape entries are sanitized (drops nameless rows, caps fields)+ * - Triple-backtick fences in user paste are neutralized before reaching+ * extractBible (so a paste containing ``` can't close the prompt fence)+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../lib/bibleExtractor.js', () => ({+ extractBible: vi.fn(),+}));+vi.mock('../lib/stageRunner.js', () => ({+ runStagedLLM: vi.fn(),+}));++const bibleExtractor = await import('../lib/bibleExtractor.js');+const stageRunner = await import('../lib/stageRunner.js');+const { catalogEvents } = await import('./catalogEvents.js');+const { extractIngredients, EXTRACTION_STAGES } = await import('./catalogExtraction.js');++const emptyLightResponse = { content: { ideas: [], scenes: [], concepts: [] } };++beforeEach(() => {+ vi.clearAllMocks();+ // Default: the light stage returns nothing unless the test overrides.+ stageRunner.runStagedLLM.mockResolvedValue(emptyLightResponse);+});++describe('catalogExtraction — stage shape', () => {+ it('covers the three bible kinds + one bundled light stage', () => {+ const ids = EXTRACTION_STAGES.map((s) => s.id);+ expect(ids).toEqual(['characters', 'places', 'objects', 'ideasScenesConcepts']);+ // The bible stages carry a `kind`; the bundled light stage does not.+ const bibleKinds = EXTRACTION_STAGES.filter((s) => s.kind).map((s) => s.kind);+ expect(bibleKinds.sort()).toEqual(['character', 'object', 'place']);+ });+});++describe('catalogExtraction — extractIngredients', () => {+ it('rejects an empty corpus before any LLM call', async () => {+ await expect(extractIngredients({ rawText: ' ' })).rejects.toThrow(/rawText is required/);+ expect(bibleExtractor.extractBible).not.toHaveBeenCalled();+ expect(stageRunner.runStagedLLM).not.toHaveBeenCalled();+ });++ it('runs every bible stage in parallel and groups results under the BIBLE_FIELD key', async () => {+ bibleExtractor.extractBible.mockImplementation(async ({ kind }) => ({+ extracted: [{ name: `${kind}-1` }],+ }));++ const out = await extractIngredients({ rawText: 'long prose', scrapId: 'cat-scrap-x' });+ expect(out).toHaveProperty('runId');+ expect(out.characters).toEqual([{ name: 'character-1' }]);+ expect(out.places).toEqual([{ name: 'place-1' }]);+ expect(out.objects).toEqual([{ name: 'object-1' }]);+ // Bible stages report count=1; the (unused) light stage reports 0.+ const bibleStages = out.stages.filter((s) => s.id !== 'ideasScenesConcepts');+ expect(bibleStages.every((s) => s.status === 'completed' && s.count === 1)).toBe(true);+ });++ it('isolates per-stage failures — one kind throwing does not block the others', async () => {+ bibleExtractor.extractBible.mockImplementation(async ({ kind }) => {+ if (kind === 'place') throw new Error('llm timeout');+ return { extracted: [{ name: `${kind}-ok` }] };+ });++ const out = await extractIngredients({ rawText: 'prose' });+ expect(out.places).toEqual([]);+ expect(out.characters).toEqual([{ name: 'character-ok' }]);+ expect(out.objects).toEqual([{ name: 'object-ok' }]);+ const placeStage = out.stages.find((s) => s.id === 'places');+ expect(placeStage.status).toBe('failed');+ expect(placeStage.error).toBe('llm timeout');+ });++ it('emits a start frame listing every stage, then per-stage running/completed frames', async () => {+ const frames = [];+ const listener = (frame) => frames.push(frame);+ catalogEvents.on('progress', listener);++ bibleExtractor.extractBible.mockResolvedValue({ extracted: [] });++ await extractIngredients({ rawText: 'prose', scrapId: 'cat-scrap-y' });++ catalogEvents.off('progress', listener);++ const start = frames.find((f) => f.type === 'start');+ expect(start).toBeTruthy();+ expect(start.stages.map((s) => s.id)).toEqual(+ ['characters', 'places', 'objects', 'ideasScenesConcepts'],+ );++ // Each stage gets both a `running` and a `completed` frame, scoped to the+ // same runId + scrapId pair so the UI can demultiplex parallel extractions.+ for (const id of ['characters', 'places', 'objects', 'ideasScenesConcepts']) {+ const running = frames.find((f) => f.type === 'stage' && f.id === id && f.status === 'running');+ const done = frames.find((f) => f.type === 'stage' && f.id === id && f.status === 'completed');+ expect(running, `missing running frame for ${id}`).toBeTruthy();+ expect(done, `missing completed frame for ${id}`).toBeTruthy();+ expect(running.scrapId).toBe('cat-scrap-y');+ expect(done.scrapId).toBe('cat-scrap-y');+ }+ });++ it('forwards providerOverride to every stage', async () => {+ bibleExtractor.extractBible.mockResolvedValue({ extracted: [] });+ await extractIngredients({ rawText: 'prose', providerOverride: 'codex' });+ for (const call of bibleExtractor.extractBible.mock.calls) {+ expect(call[0].providerOverride).toBe('codex');+ }+ // The light stage also receives the override (third positional arg).+ expect(stageRunner.runStagedLLM).toHaveBeenCalledWith(+ 'catalog-ideas-scenes-concepts',+ expect.any(Object),+ expect.objectContaining({ providerOverride: 'codex' }),+ );+ });++ it('neutralizes ``` in user paste so the prompt fence cannot be closed early', async () => {+ bibleExtractor.extractBible.mockResolvedValue({ extracted: [] });++ const evil = 'before\n```\ninjected content\n```\nafter';+ await extractIngredients({ rawText: evil });++ // Every bible stage AND the light stage receive the SAME neutralized+ // corpus (parallel passes).+ for (const call of bibleExtractor.extractBible.mock.calls) {+ const corpus = call[0].corpus;+ expect(corpus).not.toContain('```');+ expect(corpus).toContain('injected content');+ }+ const lightCall = stageRunner.runStagedLLM.mock.calls[0];+ expect(lightCall[1].draftBody).not.toContain('```');+ expect(lightCall[1].draftBody).toContain('injected content');+ });++ it('neutralizes runs of 4+ backticks (regression: naive /```/g replacement leaves a triple in the output)', async () => {+ bibleExtractor.extractBible.mockResolvedValue({ extracted: [] });+ // 4, 5, 6 backtick runs — each was a hole in the original regex.+ const evil = 'a\n````\nb\n`````\nc\n``````\nd';+ await extractIngredients({ rawText: evil });+ for (const call of bibleExtractor.extractBible.mock.calls) {+ expect(call[0].corpus).not.toContain('```');+ }+ expect(stageRunner.runStagedLLM.mock.calls[0][1].draftBody).not.toContain('```');+ });++ it('returns a fresh runId per call (no carry-over)', async () => {+ bibleExtractor.extractBible.mockResolvedValue({ extracted: [] });+ const a = await extractIngredients({ rawText: 'prose' });+ const b = await extractIngredients({ rawText: 'prose' });+ expect(a.runId).not.toBe(b.runId);+ });+});++describe('catalogExtraction — bundled light stage', () => {+ it('splits the single LLM response into ideas/scenes/concepts arrays', async () => {+ bibleExtractor.extractBible.mockResolvedValue({ extracted: [] });+ stageRunner.runStagedLLM.mockResolvedValue({+ content: {+ ideas: [{ name: 'Inherited memory', summary: 'What if memory was genetic?' }],+ scenes: [{ name: 'Diner 3am', summary: 'Two friends at a 3am diner.', setting: 'a diner', actors: ['friend A', 'friend B'] }],+ concepts: [{ name: 'Sleep magic', summary: 'Spells cost sleep.', kind: 'magic-system' }],+ },+ });+ const out = await extractIngredients({ rawText: 'prose' });+ expect(out.ideas).toHaveLength(1);+ expect(out.ideas[0]).toMatchObject({ name: 'Inherited memory', summary: 'What if memory was genetic?' });+ expect(out.scenes).toHaveLength(1);+ expect(out.scenes[0]).toMatchObject({ name: 'Diner 3am', setting: 'a diner', actors: ['friend A', 'friend B'] });+ expect(out.concepts).toHaveLength(1);+ // The LLM's `kind` field is preserved verbatim on payload — payload is+ // a JSONB column, so it doesn't collide with the row-level `type`.+ expect(out.concepts[0]).toMatchObject({ name: 'Sleep magic', kind: 'magic-system' });+ });++ it('reports a combined count (ideas + scenes + concepts) on the light stage', async () => {+ bibleExtractor.extractBible.mockResolvedValue({ extracted: [] });+ stageRunner.runStagedLLM.mockResolvedValue({+ content: {+ ideas: [{ name: 'a' }, { name: 'b' }],+ scenes: [{ name: 'c' }],+ concepts: [{ name: 'd' }, { name: 'e' }, { name: 'f' }],+ },+ });+ const out = await extractIngredients({ rawText: 'prose' });+ const lightStage = out.stages.find((s) => s.id === 'ideasScenesConcepts');+ expect(lightStage.count).toBe(6);+ expect(lightStage.status).toBe('completed');+ });++ it('drops rows missing a name and caps long fields', async () => {+ bibleExtractor.extractBible.mockResolvedValue({ extracted: [] });+ const longSummary = 'x'.repeat(5000);+ stageRunner.runStagedLLM.mockResolvedValue({+ content: {+ ideas: [+ { name: '', summary: 'nameless' }, // dropped+ { summary: 'still nameless' }, // dropped+ null, // dropped (non-object)+ { name: 'Keeper', summary: longSummary }, // kept, summary capped+ ],+ scenes: [],+ concepts: [],+ },+ });+ const out = await extractIngredients({ rawText: 'prose' });+ expect(out.ideas).toHaveLength(1);+ expect(out.ideas[0].name).toBe('Keeper');+ expect(out.ideas[0].summary.length).toBeLessThanOrEqual(2000);+ });++ it('a malformed light response (non-array `ideas`) yields empty arrays — never poisons the rest', async () => {+ bibleExtractor.extractBible.mockResolvedValue({ extracted: [{ name: 'A' }] });+ stageRunner.runStagedLLM.mockResolvedValue({ content: { ideas: 'oops' } });+ const out = await extractIngredients({ rawText: 'prose' });+ expect(out.ideas).toEqual([]);+ expect(out.scenes).toEqual([]);+ expect(out.concepts).toEqual([]);+ expect(out.characters).toEqual([{ name: 'A' }]); // bible stage unaffected+ const lightStage = out.stages.find((s) => s.id === 'ideasScenesConcepts');+ expect(lightStage.status).toBe('completed');+ expect(lightStage.count).toBe(0);+ });++ it('isolates a thrown LLM error from the bible passes', async () => {+ bibleExtractor.extractBible.mockResolvedValue({ extracted: [{ name: 'A' }] });+ stageRunner.runStagedLLM.mockRejectedValue(new Error('provider down'));+ const out = await extractIngredients({ rawText: 'prose' });+ expect(out.characters).toEqual([{ name: 'A' }]);+ expect(out.ideas).toEqual([]);+ const lightStage = out.stages.find((s) => s.id === 'ideasScenesConcepts');+ expect(lightStage.status).toBe('failed');+ expect(lightStage.error).toBe('provider down');+ });+});