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: Story Builder import intake (reverse-engineer a finished work)
Adam Eivy038c798926c2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2311cf58b9..8108fa9c54 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,7 +8,7 @@ TBD## Added-- **Unified Story Builder** (`/story-builder`): a new guided page that walks a story from idea → universe aesthetic → plot arc → reader map → characters → issues → production as one linear flow. Each step is LLM-assisted with an AI-refinement affordance and ends with an explicit lock before the next unlocks; going back to revise an earlier step soft-flags the downstream locked steps as "stale" (integrity gate) so nothing silently drifts — without destroying their content. The builder is a thin conductor over the existing Universe / Series / Issue records (no data duplication); heavy per-issue production hands off to the existing Pipeline issue page. Reachable from the sidebar (Create → Story Builder), ⌘K, and voice. (Seed-mode v1; import-mode intake + a few refinements tracked in PLAN.md.)+- **Unified Story Builder** (`/story-builder`): a new guided page that walks a story from idea → universe aesthetic → plot arc → reader map → characters → issues → production as one linear flow. Each step is LLM-assisted with an AI-refinement affordance and ends with an explicit lock before the next unlocks; going back to revise an earlier step soft-flags the downstream locked steps as "stale" (integrity gate) so nothing silently drifts — without destroying their content. The builder is a thin conductor over the existing Universe / Series / Issue records (no data duplication); heavy per-issue production hands off to the existing Pipeline issue page. Reachable from the sidebar (Create → Story Builder), ⌘K, and voice. The intro screen supports two intake modes: **start from a seed idea**, or **import a finished work** (comic script / screenplay / novel / short story) — the importer reverse-engineers it into a universe, arc, characters, and issues, then drops you into the wizard to review and lock each stage.- **Reader Map** on a series arc (`series.arc.readerMap`): a distinct audience-experience roadmap — hooks, payoffs, emotional beats, and cliffhangers across the arc — built on top of the Vonnegut story shape, separate from the protagonist arc. Generated and refined via the new Story Builder reader-map step (also preserved by arc regeneration).## Changeddiff --git a/PLAN.md b/PLAN.mdindex 51b01d83ee..db275759f8 100644--- a/PLAN.md+++ b/PLAN.md@@ -192,7 +192,7 @@ Surfaced by the multi-reviewer release gate for v2.11.0. The correctness/contracThe first slice shipped a working **seed-mode** conductor (`/story-builder`): create → idea → universeAesthetic → plotArc → readerMap → characters → issues (deep-link handoff) → production, with per-step lock gating and soft-flag integrity staleness. New code: `server/services/storyBuilder.js`, `server/routes/storyBuilder.js`, `server/lib/storyBuilderSteps.js`, `server/lib/storyBuilderIntegrity.js`, `client/src/pages/StoryBuilder.jsx`, `client/src/services/apiStoryBuilder.js`, plus `series.arc.readerMap` (new field + `generateReaderMap`/`refineReaderMap` in `arcPlanner.js`, prompts + migration 043, `pipelineSeries` schema → 2). These are the deliberately-deferred pieces:-- [ ] [story-builder-import-mode-ui] **Import-mode intake UI.** The conductor + service already accept `intakeMode: 'import'` (pre-creates universe/series via the importer, marks every step `ready`), but the index `StoryBuilderIndex` create form only offers seed mode. Add an "Import a finished work" tab that runs the existing `analyzeImport` → `commitImport` flow (reuse `client/src/pages/Importer.jsx` intake), then creates a session linked to the resulting universe/series ids so the user reviews + locks each pre-filled step. Server reconciliation is already in place (`createStorySession` import branch). Deferred from the initial build to keep v1 scoped to seed mode.+- [ ] [story-builder-import-aesthetic-readermap-gaps] **Import pre-fills arc/characters/issues but NOT universe aesthetic or reader map.** `analyzeImport` creates the universe with only a name (no logline/premise/styleNotes/influences) and the importer never extracts a reader map — yet `createStorySession` import-branch marks every step `ready`. So in an imported session the universeAesthetic + readerMap steps show empty content under a misleading "Ready" badge; the user must Generate them in-wizard. Mitigations already in place: the session `seedIdea` is seeded from the extracted arc summary so the aesthetic Expand has a real starter, and generateStep's expand falls back through `seedIdea`→universe name (won't crash). Follow-up: either mark only the importer-filled steps `ready` (others `pending`), or extract a starter/aesthetic + reader-map pass during import. Surfaced building import mode (2026-05-27).- [ ] [story-builder-issue-llm-seeding] **Seed issues from the arc inside the builder.** The `issues` step currently lists existing issues (from `listPipelineIssues`) and links out to the Pipeline to create/produce them. Add a "Generate issues from arc" action that calls `generateSeasonEpisodes` (arcPlanner) per season and persists via `createIssue`, so the user doesn't have to leave the builder to break the arc into issues. Per-issue lock + production handoff already work.- [ ] [story-builder-sse-progress] **SSE streaming for long generations.** `generateStep`/`refineStep` are synchronous request/response (await the LLM, return the result) — fine for arc/reader-map but a long arc-overview blocks the button with only a spinner. Add a `GET /api/story-builder/:id/steps/:stepId/progress` EventSource endpoint (reuse `client/src/hooks/useSseProgress.js`) and stream stage progress like the pipeline auto-run does. The plan specced this; deferred as a v1 simplification.- [ ] [story-builder-arc-refine-feedback] **AI refine-with-feedback for the plot-arc step.** `refineStep` supports `universeAesthetic` (via `refineWorldPrompts`), `readerMap` (`refineReaderMap`), and `characters` (`refineUniverseCharacter`), but `plotArc` only offers full regenerate (`generateArcOverview`) — there's no "refine the arc against this note" path. Add an arc-refine prompt + `refineArc` in `arcPlanner.js` and wire it into `refineStep`'s `plotArc` branch + the `StepPanel` plotArc RefineBox.diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsxindex 0fb6722eee..bdc8d27210 100644--- a/client/src/pages/StoryBuilder.jsx+++ b/client/src/pages/StoryBuilder.jsx@@ -11,13 +11,28 @@ import {setStoryCurrentStep, lockStoryStep, unlockStoryStep,generateStoryStep, refineStoryStep, setStoryIssueLock,getUniverse, getPipelineSeries, listPipelineIssues,+ analyzeImport, commitImport, retryImporterIssues, IMPORTER_CONTENT_TYPES,} from '../services/api';+// Mirror Importer.jsx's commit picker — only these arc fields are sent on commit.+const ARC_FIELDS_TO_COMMIT = ['logline', 'summary', 'protagonistArc', 'themes', 'shape'];+const pickArcFields = (arc) => {+ if (!arc) return null;+ const out = {};+ for (const k of ARC_FIELDS_TO_COMMIT) if (arc[k] !== undefined) out[k] = arc[k];+ return out;+};++const CONTENT_TYPE_LABELS = {+ 'short-story': 'Short story', novel: 'Novel', screenplay: 'Screenplay', 'comic-script': 'Comic script',+};+// ── Index view: list existing sessions + create a new one ──────────────────function StoryBuilderIndex() {const navigate = useNavigate();const [sessions, setSessions] = useState([]);+ const [mode, setMode] = useState('seed');const [title, setTitle] = useState('');const [seedIdea, setSeedIdea] = useState('');const [creating, setCreating] = useState(false);@@ -29,12 +44,18 @@ function StoryBuilderIndex() {const create = async () => {if (!title.trim()) { toast.error('Give your story a working title'); return; }setCreating(true);- const created = await createStorySession({ title: title.trim(), seedIdea: seedIdea.trim() })+ const created = await createStorySession({ title: title.trim(), seedIdea: seedIdea.trim() }, { silent: true }).catch((err) => { toast.error(err?.message || 'Failed to create'); return null; });setCreating(false);if (created) navigate(`/story-builder/${created.id}/idea`);};+ const onCreated = (session) => navigate(`/story-builder/${session.id}/idea`);++ const tabClass = (id) => `px-4 py-2 text-sm rounded-t border-b-2 ${+ mode === id ? 'border-port-accent text-white' : 'border-transparent text-gray-400 hover:text-gray-200'+ }`;+return (<div className="max-w-3xl mx-auto space-y-6"><header>@@ -42,36 +63,46 @@ function StoryBuilderIndex() {<Sparkles className="w-6 h-6 text-port-accent" /> Story Builder</h1><p className="text-gray-400 mt-1">- One guided path from idea to video — name a universe, capture an idea, then review and lock each- stage (aesthetic → plot arc → reader map → characters → issues) before moving on.+ One guided path from idea to video — start from a seed idea or import a finished work, then review and+ lock each stage (aesthetic → plot arc → reader map → characters → issues) before moving on.</p></header>- <section className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">- <h2 className="font-semibold">Start a new story</h2>- <div>- <label htmlFor="stb-title" className="block text-sm text-gray-400 mb-1">Universe / story name</label>- <input- id="stb-title" type="text" value={title} onChange={(e) => setTitle(e.target.value)}- placeholder="e.g. The Salt Run"- className="w-full bg-port-bg border border-port-border rounded px-3 py-2"- />+ <section className="bg-port-card border border-port-border rounded-lg">+ <div className="flex gap-1 border-b border-port-border px-2 pt-2">+ <button onClick={() => setMode('seed')} className={tabClass('seed')}>Start from an idea</button>+ <button onClick={() => setMode('import')} className={tabClass('import')}>Import a finished work</button></div>- <div>- <label htmlFor="stb-seed" className="block text-sm text-gray-400 mb-1">Starter idea</label>- <textarea- id="stb-seed" value={seedIdea} onChange={(e) => setSeedIdea(e.target.value)} rows={3}- placeholder="A one-line or one-paragraph seed. You'll expand it with AI in the first step."- className="w-full bg-port-bg border border-port-border rounded px-3 py-2"- />- </div>- <button- onClick={create} disabled={creating}- className="inline-flex items-center gap-2 bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white px-4 py-2 rounded"- >- {creating ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}- Create & begin- </button>++ {mode === 'seed' ? (+ <div className="p-4 space-y-3">+ <div>+ <label htmlFor="stb-title" className="block text-sm text-gray-400 mb-1">Universe / story name</label>+ <input+ id="stb-title" type="text" value={title} onChange={(e) => setTitle(e.target.value)}+ placeholder="e.g. The Salt Run"+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2"+ />+ </div>+ <div>+ <label htmlFor="stb-seed" className="block text-sm text-gray-400 mb-1">Starter idea</label>+ <textarea+ id="stb-seed" value={seedIdea} onChange={(e) => setSeedIdea(e.target.value)} rows={3}+ placeholder="A one-line or one-paragraph seed. You'll expand it with AI in the first step."+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2"+ />+ </div>+ <button+ onClick={create} disabled={creating}+ className="inline-flex items-center gap-2 bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white px-4 py-2 rounded"+ >+ {creating ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}+ Create & begin+ </button>+ </div>+ ) : (+ <ImportPanel onCreated={onCreated} />+ )}</section>{sessions.length > 0 && (@@ -92,6 +123,156 @@ function StoryBuilderIndex() {);}+// ── Import intake (reuses the Importer's analyze → commit) ──────────────────++function ImportPanel({ onCreated }) {+ const [universeName, setUniverseName] = useState('');+ const [seriesName, setSeriesName] = useState('');+ const [contentType, setContentType] = useState('comic-script');+ const [source, setSource] = useState('');+ const [analyzing, setAnalyzing] = useState(false);+ const [preview, setPreview] = useState(null);+ const [retrying, setRetrying] = useState(false);+ const [committing, setCommitting] = useState(false);++ const types = IMPORTER_CONTENT_TYPES || ['short-story', 'novel', 'screenplay', 'comic-script'];++ const analyze = async () => {+ if (!universeName.trim() || !seriesName.trim() || !source.trim()) {+ toast.error('Universe name, series name, and source text are required'); return;+ }+ setAnalyzing(true); setPreview(null);+ const res = await analyzeImport(+ { universeName: universeName.trim(), seriesName: seriesName.trim(), contentType, source },+ { silent: true },+ ).catch((err) => { toast.error(err?.message || 'Analyze failed'); return null; });+ setAnalyzing(false);+ if (res) setPreview(res);+ };++ const retryIssues = async () => {+ setRetrying(true);+ const res = await retryImporterIssues(+ { contentType, source, seriesName: seriesName.trim(), arcSummary: preview?.arcPreview?.summary || '' },+ { silent: true },+ ).catch((err) => { toast.error(err?.message || 'Retry failed'); return null; });+ setRetrying(false);+ if (res) setPreview((p) => ({ ...p, issueProposals: res.issueProposals || [], issueSplitFailed: false }));+ };++ const importAndBuild = async () => {+ if (!preview) return;+ const issues = preview.issueProposals || [];+ if (issues.length === 0) { toast.error('No issues were extracted — retry the issue split or adjust the source'); return; }+ setCommitting(true);+ const committed = await commitImport({+ universeId: preview.universe.id,+ seriesId: preview.series.id,+ issues,+ contentType,+ canonSelections: {+ characters: preview.canonPreview?.characters || [],+ places: preview.canonPreview?.places || [],+ objects: preview.canonPreview?.objects || [],+ },+ arc: pickArcFields(preview.arcPreview),+ seasons: preview.seasonsPreview || [],+ }, { silent: true }).catch((err) => { toast.error(err?.message || 'Import failed'); return null; });+ if (!committed) { setCommitting(false); return; }+ const session = await createStorySession({+ intakeMode: 'import',+ title: seriesName.trim() || universeName.trim(),+ // Seed from the extracted arc so the idea step has context and the+ // universe-aesthetic expand has a real starter (the imported universe+ // otherwise only has a name).+ seedIdea: (preview.arcPreview?.summary || preview.arcPreview?.logline || '').slice(0, 4000),+ universeId: preview.universe.id,+ seriesId: preview.series.id,+ }, { silent: true }).catch((err) => { toast.error(err?.message || 'Failed to start the builder'); return null; });+ setCommitting(false);+ if (session) onCreated(session);+ };++ const canon = preview?.canonPreview || {};+ const issueCount = preview?.issueProposals?.length || 0;++ return (+ <div className="p-4 space-y-3">+ <p className="text-sm text-gray-400">+ Paste a finished story (comic script, screenplay, novel, or short story). It's reverse-engineered into a+ universe, plot arc, characters, and issues — then you review and lock each stage in the builder.+ </p>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <div>+ <label htmlFor="imp-uni" className="block text-sm text-gray-400 mb-1">Universe name</label>+ <input id="imp-uni" type="text" value={universeName} onChange={(e) => setUniverseName(e.target.value)}+ placeholder="e.g. Giant" className="w-full bg-port-bg border border-port-border rounded px-3 py-2" />+ </div>+ <div>+ <label htmlFor="imp-ser" className="block text-sm text-gray-400 mb-1">Series name</label>+ <input id="imp-ser" type="text" value={seriesName} onChange={(e) => setSeriesName(e.target.value)}+ placeholder="e.g. Giant" className="w-full bg-port-bg border border-port-border rounded px-3 py-2" />+ </div>+ </div>+ <div>+ <label htmlFor="imp-type" className="block text-sm text-gray-400 mb-1">Content type</label>+ <select id="imp-type" value={contentType} onChange={(e) => setContentType(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2">+ {types.map((t) => <option key={t} value={t}>{CONTENT_TYPE_LABELS[t] || t}</option>)}+ </select>+ </div>+ <div>+ <label htmlFor="imp-src" className="block text-sm text-gray-400 mb-1">+ Source text <span className="text-gray-600">({source.length.toLocaleString()} chars)</span>+ </label>+ <textarea id="imp-src" value={source} onChange={(e) => setSource(e.target.value)} rows={8}+ placeholder="Paste the full script / manuscript here…"+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 font-mono text-xs" />+ </div>++ {!preview ? (+ <button onClick={analyze} disabled={analyzing}+ className="inline-flex items-center gap-2 bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white px-4 py-2 rounded">+ {analyzing ? <Loader2 className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4" />}+ {analyzing ? 'Analyzing… (this can take a minute)' : 'Analyze'}+ </button>+ ) : (+ <div className="border border-port-border rounded p-3 space-y-2 bg-port-bg">+ <div className="text-sm font-medium">+ Extracted “{preview.universe?.name}”+ {preview.isExistingUniverse && <span className="text-xs text-port-warning ml-2">(existing universe — will merge)</span>}+ </div>+ <div className="text-xs text-gray-400 flex flex-wrap gap-x-4 gap-y-1">+ <span>{(canon.characters || []).length} characters</span>+ <span>{(canon.places || []).length} places</span>+ <span>{(canon.objects || []).length} objects</span>+ <span>{(preview.seasonsPreview || []).length} volumes</span>+ <span className={issueCount === 0 ? 'text-port-error' : ''}>{issueCount} issues</span>+ </div>+ {preview.arcPreview?.logline && <div className="text-xs text-gray-300 italic">“{preview.arcPreview.logline}”</div>}+ {(preview.issueSplitFailed || issueCount === 0) && (+ <div className="text-xs text-port-warning flex items-center gap-2">+ <AlertTriangle className="w-3.5 h-3.5" /> Issue split didn’t produce issues.+ <button onClick={retryIssues} disabled={retrying} className="underline hover:text-port-accent disabled:opacity-50">+ {retrying ? 'Retrying…' : 'Retry issue split'}+ </button>+ </div>+ )}+ <div className="flex items-center gap-2 pt-1">+ <button onClick={importAndBuild} disabled={committing || issueCount === 0}+ className="inline-flex items-center gap-2 bg-port-success hover:bg-green-600 disabled:opacity-50 text-white px-4 py-2 rounded text-sm">+ {committing ? <Loader2 className="w-4 h-4 animate-spin" /> : <Check className="w-4 h-4" />}+ Import & start building+ </button>+ <button onClick={() => setPreview(null)} disabled={committing}+ className="text-sm text-gray-400 hover:text-white px-2">Re-analyze</button>+ </div>+ </div>+ )}+ </div>+ );+}+// ── Stale / status helpers ─────────────────────────────────────────────────const STATUS_BADGE = {diff --git a/client/src/pages/StoryBuilder.test.jsx b/client/src/pages/StoryBuilder.test.jsxindex 35bf650aa2..96d8e66c71 100644--- a/client/src/pages/StoryBuilder.test.jsx+++ b/client/src/pages/StoryBuilder.test.jsx@@ -31,6 +31,10 @@ const api = vi.hoisted(() => ({getUniverse: vi.fn(),getPipelineSeries: vi.fn(),listPipelineIssues: vi.fn(),+ analyzeImport: vi.fn(),+ commitImport: vi.fn(),+ retryImporterIssues: vi.fn(),+ IMPORTER_CONTENT_TYPES: ['short-story', 'novel', 'screenplay', 'comic-script'],}));vi.mock('../services/api', () => api);@@ -49,6 +53,11 @@ beforeEach(() => {vi.clearAllMocks();api.getStoryBuilderSteps.mockResolvedValue({ steps: STEPS });api.listStorySessions.mockResolvedValue([]);+ // Benign default so a post-import navigation that mounts the detail view+ // (which calls getStorySession) doesn't reject; the detail tests override it.+ api.getStorySession.mockResolvedValue({+ id: 'stb-x', title: 'X', currentStep: 'idea', steps: mkSteps(), staleSteps: [], universeId: null, seriesId: null,+ });api.setStoryCurrentStep.mockResolvedValue({});api.lockStoryStep.mockResolvedValue({});api.unlockStoryStep.mockResolvedValue({});@@ -61,10 +70,71 @@ beforeEach(() => {});describe('StoryBuilder — index', () => {- it('renders the create form', async () => {+ it('renders the seed create form by default', async () => {+ renderAt('/story-builder');+ expect(await screen.findByLabelText('Universe / story name')).toBeTruthy();+ expect(screen.getByText('Start from an idea')).toBeTruthy();+ expect(screen.getByText('Import a finished work')).toBeTruthy();+ });++ it('import tab: analyze → preview → import & build creates an import-mode session', async () => {+ const { fireEvent } = await import('@testing-library/react');+ api.analyzeImport.mockResolvedValue({+ universe: { id: 'u9', name: 'Giant' },+ series: { id: 's9' },+ canonPreview: { characters: [{ name: 'Kessa' }], places: [], objects: [] },+ arcPreview: { logline: 'A giant wakes.', summary: 'spine' },+ seasonsPreview: [{ number: 1, title: 'Vol 1' }],+ issueProposals: [{ title: 'Issue 1' }],+ issueSplitFailed: false,+ });+ api.commitImport.mockResolvedValue({ universe: { id: 'u9' }, series: { id: 's9' }, createdIssueIds: ['iss-1'] });+ api.createStorySession.mockResolvedValue({ id: 'stb-import', currentStep: 'idea' });++ renderAt('/story-builder');+ fireEvent.click(await screen.findByText('Import a finished work'));+ fireEvent.change(await screen.findByLabelText('Universe name'), { target: { value: 'Giant' } });+ fireEvent.change(screen.getByLabelText('Series name'), { target: { value: 'Giant' } });+ fireEvent.change(screen.getByLabelText(/Source text/), { target: { value: 'PAGE ONE...' } });+ fireEvent.click(screen.getByRole('button', { name: /^Analyze$/ }));++ await waitFor(() => expect(screen.getByText(/Extracted/)).toBeTruthy());+ expect(api.analyzeImport).toHaveBeenCalledWith(+ expect.objectContaining({ universeName: 'Giant', contentType: 'comic-script', source: 'PAGE ONE...' }),+ expect.objectContaining({ silent: true }),+ );++ fireEvent.click(screen.getByRole('button', { name: /Import & start building/ }));+ await waitFor(() => expect(api.createStorySession).toHaveBeenCalledWith(+ expect.objectContaining({ intakeMode: 'import', universeId: 'u9', seriesId: 's9', title: 'Giant' }),+ expect.objectContaining({ silent: true }),+ ));+ // commit included all extracted canon + the arc + seasons + issues+ expect(api.commitImport).toHaveBeenCalledWith(+ expect.objectContaining({+ universeId: 'u9', seriesId: 's9', contentType: 'comic-script',+ issues: [{ title: 'Issue 1' }],+ }),+ expect.objectContaining({ silent: true }),+ );+ });++ it('import tab: blocks "Import & build" when no issues were extracted, offers retry', async () => {+ const { fireEvent } = await import('@testing-library/react');+ api.analyzeImport.mockResolvedValue({+ universe: { id: 'u9', name: 'Giant' }, series: { id: 's9' },+ canonPreview: { characters: [], places: [], objects: [] },+ arcPreview: { logline: 'x' }, seasonsPreview: [],+ issueProposals: [], issueSplitFailed: true,+ });renderAt('/story-builder');- expect(await screen.findByText('Start a new story')).toBeTruthy();- expect(screen.getByLabelText('Universe / story name')).toBeTruthy();+ fireEvent.click(await screen.findByText('Import a finished work'));+ fireEvent.change(await screen.findByLabelText('Universe name'), { target: { value: 'Giant' } });+ fireEvent.change(screen.getByLabelText('Series name'), { target: { value: 'Giant' } });+ fireEvent.change(screen.getByLabelText(/Source text/), { target: { value: 'x' } });+ fireEvent.click(screen.getByRole('button', { name: /^Analyze$/ }));+ await waitFor(() => expect(screen.getByText(/Retry issue split/)).toBeTruthy());+ expect(screen.getByRole('button', { name: /Import & start building/ }).disabled).toBe(true);});});