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: Unified Story Builder (seed-mode) + series reader map
Adam Eivy981437ae13ce
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c4eda4d910..2311cf58b9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,6 +8,9 @@ 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.)+- **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).+## Changed## Fixeddiff --git a/PLAN.md b/PLAN.mdindex f0d12485c4..72b4b4dc67 100644--- a/PLAN.md+++ b/PLAN.md@@ -188,6 +188,17 @@ Surfaced by the multi-reviewer release gate for v2.11.0. The correctness/contrac- [ ] [comic-allcaps-continuation-vs-cue] **`normalizeBareComicScript` in `server/lib/comicScriptParser.js` (~line 193) can misread a short all-caps continuation line (e.g. a bare `STOP` on its own line, mid-balloon) as a new speaker cue.** The continuation branch's `!BARE_SPEAKER_LINE.test(t)` guard exists so a genuine second speaker (`GIANT` … `KESSA`) opens a new balloon — but an all-caps shouted continuation with no punctuation matches the same shape and gets treated as a cue instead of GIANT's next line. This is the inherent flip-side of the two-speaker fix: an all-caps line in *continuation* position is genuinely ambiguous between "shout" and "new cue," and the current heuristic favors "new cue" (the more common multi-speaker-panel case; shouts usually carry `!`/`?` which already excludes them). A proper fix needs one-line lookahead (a real cue is followed by its own dialogue line; a trailing shout is followed by a marker/EOF) — which means converting the `for…of` line loop to indexed iteration. Deferred from the v2.11.0 release review (gemini) as IMPROVEMENT: flipping the heuristic instead would regress the more-common multi-speaker case. Surfaced 2026-05-27.- [ ] [voice-taskcomplete-announce-once-guard] **`onTaskUpdated` in `server/services/voice/proactiveTriggers.js` (~line 193) re-announces if an already-completed voice-dispatched task is updated again.** The spoken "your coding task is done" line keys on `tasks:changed action:'updated'` + terminal status (`completed`/`blocked`) + `voiceDispatch`, with no record of already-announced task ids — so any future caller that runs `updateTask` on an already-completed voice-dispatched task (e.g. attaching a PR URL or metadata *after* marking it completed) would re-fire the announcement. The comment claims it "announces once (at its terminal outcome)," which holds only because no current caller re-updates completed tasks. Fix: track announced task ids in a `Set` in the closure (clear on unwire) and skip if already announced, OR gate on the previous→terminal status *transition* if the event carries the prior status. Low severity (no current re-update path; worst case is a duplicate spoken line, not data loss) — deferred per YAGNI since the path doesn't exist today. Surfaced 2026-05-27.+### Unified Story Builder — deferred follow-ups (2026-05-27)++The 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-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.+- [ ] [story-builder-embed-arccanvas] **Embed `ArcCanvas` / `StoryShapes` inline instead of read-only field blocks.** The plotArc + readerMap steps currently render read-only `FieldBlock`s + a deep-link to the Pipeline for editing. The plan called for reusing `client/src/components/pipeline/ArcCanvas.jsx` and the Vonnegut `StoryShapes` sparkline inline (and a beat timeline for the reader map). Embed them so editing happens in-builder. Deferred because `ArcCanvas` has a wide prop surface; the deep-link covers editing for v1.+- [ ] [story-builder-session-sync] **Optional cross-machine resumable sessions.** Sessions are intentionally local-only in v1 (excluded from peer sync — see `storyBuilder.js` header). If cross-machine resume is wanted later, key the staleness model on a content hash carried in the session (the integrity helper already produces one) rather than live-record diffing, so a peer's universe edit doesn't false-positive-stale the local session.+## Future Ideas- **Identity Context Injection** — per-task-type digital twin preamble toggle.diff --git a/client/src/App.jsx b/client/src/App.jsxindex c04d277c2c..9de5f8d467 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -77,6 +77,7 @@ const WritersRoomGuide = lazyWithReload(() => import('./pages/WritersRoomGuide')const Pipeline = lazyWithReload(() => import('./pages/Pipeline'));const Sharing = lazyWithReload(() => import('./pages/Sharing'));const Importer = lazyWithReload(() => import('./pages/Importer'));+const StoryBuilder = lazyWithReload(() => import('./pages/StoryBuilder'));const PipelineSeries = lazyWithReload(() => import('./pages/PipelineSeries'));const PipelineSeriesRoadmap = lazyWithReload(() => import('./pages/PipelineSeriesRoadmap'));const PipelineIssue = lazyWithReload(() => import('./pages/PipelineIssue'));@@ -266,6 +267,9 @@ export default function App() {<Route path="sharing" element={<Sharing />} /><Route path="sharing/:section" element={<Sharing />} /><Route path="importer" element={<Importer />} />+ <Route path="story-builder" element={<StoryBuilder />} />+ <Route path="story-builder/:storyId" element={<Navigate to="idea" replace />} />+ <Route path="story-builder/:storyId/:step" element={<StoryBuilder />} /><Route path="pipeline" element={<Pipeline />} /><Route path="pipeline/series/:seriesId" element={<PipelineSeries />} /><Route path="pipeline/series/:seriesId/roadmap" element={<PipelineSeriesRoadmap />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 04b6b03c84..38b22ba6c4 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -200,6 +200,7 @@ const navItems = [{ to: '/media', label: 'Media Gen', icon: Layers },{ to: '/pipeline', label: 'Series Pipeline', icon: WorkflowIcon, dynamic: 'pipelineSeries' },{ to: '/sharing', label: 'Sharing', icon: Share2 },+ { to: '/story-builder', label: 'Story Builder', icon: Wand2 },{ to: '/universes', label: 'Universes', icon: Globe, dynamic: 'universes' },{ to: '/writers-room', label: 'Writers Room', icon: NotebookPen }]@@ -1039,6 +1040,10 @@ export default function Layout() {// (list/table) takes the normal padded+scrolling main, mirroring// the Series Pipeline index (/pipeline is not full-width either).location.pathname.startsWith('/universes/') ||+ // Story Builder DETAIL (/story-builder/:id/:step) is a full-width+ // stepper that owns its own scroll; the bare /story-builder index+ // (list + create form) takes the normal padded+scrolling main.+ location.pathname.startsWith('/story-builder/') ||location.pathname.startsWith('/writers-room') ||location.pathname.startsWith('/agents') ||location.pathname === '/shell' ||diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsxnew file mode 100644index 0000000000..ed2713c657--- /dev/null+++ b/client/src/pages/StoryBuilder.jsx@@ -0,0 +1,517 @@+import { useState, useEffect, useCallback } from 'react';+import { useParams, useNavigate, Link } from 'react-router-dom';+import {+ Sparkles, Lock, Unlock, Check, ChevronRight, ChevronLeft, AlertTriangle,+ Plus, RefreshCw, Loader2, ExternalLink, Wand2,+} from 'lucide-react';+import toast from '../components/ui/Toast';+import { useLockToggle } from '../hooks/useLockToggle';+import {+ getStoryBuilderSteps, listStorySessions, getStorySession, createStorySession,+ setStoryCurrentStep, lockStoryStep, unlockStoryStep,+ generateStoryStep, refineStoryStep, setStoryIssueLock,+ getUniverse, getPipelineSeries, listPipelineIssues,+} from '../services/api';++// ── Index view: list existing sessions + create a new one ──────────────────++function StoryBuilderIndex() {+ const navigate = useNavigate();+ const [sessions, setSessions] = useState([]);+ const [title, setTitle] = useState('');+ const [seedIdea, setSeedIdea] = useState('');+ const [creating, setCreating] = useState(false);++ useEffect(() => {+ listStorySessions({ silent: true }).then(setSessions).catch(() => setSessions([]));+ }, []);++ 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() })+ .catch((err) => { toast.error(err?.message || 'Failed to create'); return null; });+ setCreating(false);+ if (created) navigate(`/story-builder/${created.id}/idea`);+ };++ return (+ <div className="max-w-3xl mx-auto space-y-6">+ <header>+ <h1 className="text-2xl font-bold flex items-center gap-2">+ <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.+ </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"+ />+ </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>+ </section>++ {sessions.length > 0 && (+ <section className="space-y-2">+ <h2 className="font-semibold text-gray-300">Continue a story</h2>+ {sessions.map((s) => (+ <Link+ key={s.id} to={`/story-builder/${s.id}/${s.currentStep || 'idea'}`}+ className="flex items-center justify-between bg-port-card border border-port-border rounded-lg px-4 py-3 hover:border-port-accent"+ >+ <span className="font-medium">{s.title}</span>+ <span className="text-xs text-gray-500">at “{s.currentStep}” <ChevronRight className="w-4 h-4 inline" /></span>+ </Link>+ ))}+ </section>+ )}+ </div>+ );+}++// ── Stale / status helpers ─────────────────────────────────────────────────++const STATUS_BADGE = {+ pending: { label: 'Not started', cls: 'text-gray-500' },+ 'in-progress': { label: 'In progress', cls: 'text-port-warning' },+ ready: { label: 'Ready', cls: 'text-port-accent' },+ locked: { label: 'Locked', cls: 'text-port-success' },+};++// ── Per-step content panels ────────────────────────────────────────────────++function FieldBlock({ label, value }) {+ return (+ <div>+ <div className="text-xs uppercase tracking-wide text-gray-500 mb-0.5">{label}</div>+ <div className="text-sm text-gray-200 whitespace-pre-wrap">{value || <span className="text-gray-600 italic">— empty —</span>}</div>+ </div>+ );+}++function ReaderMapView({ readerMap }) {+ if (!readerMap) return <p className="text-gray-600 italic text-sm">No reader map yet. Generate one to plan the audience experience.</p>;+ const Section = ({ title, items, render }) => (+ items?.length ? (+ <div>+ <div className="text-xs uppercase tracking-wide text-gray-500 mb-1">{title} ({items.length})</div>+ <ul className="space-y-1">{items.map((it) => <li key={it.id} className="text-sm text-gray-300">{render(it)}</li>)}</ul>+ </div>+ ) : null+ );+ return (+ <div className="space-y-3">+ <Section title="Hooks" items={readerMap.hooks} render={(h) => `${h.atArcPosition != null ? `@${h.atArcPosition} · ` : ''}${h.label}${h.note ? ` — ${h.note}` : ''}`} />+ <Section title="Payoffs" items={readerMap.payoffs} render={(p) => `${p.atArcPosition != null ? `@${p.atArcPosition} · ` : ''}${p.label}`} />+ <Section title="Beats" items={readerMap.beats} render={(b) => `[${b.kind}${b.intensity != null ? ` ${Math.round(b.intensity * 100)}%` : ''}] ${b.note || ''}`} />+ <Section title="Cliffhangers" items={readerMap.cliffhangers} render={(c) => `after #${c.atIssueBoundary ?? '?'} — ${c.note || ''}`} />+ </div>+ );+}++function RefineBox({ onRefine, busy, disabled }) {+ const [feedback, setFeedback] = useState('');+ return (+ <div className="border-t border-port-border pt-3 mt-3">+ <label className="block text-xs text-gray-500 mb-1">AI refinement feedback</label>+ <div className="flex gap-2">+ <input+ type="text" value={feedback} onChange={(e) => setFeedback(e.target.value)}+ placeholder="e.g. make the midpoint reveal land harder"+ disabled={disabled}+ className="flex-1 bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm disabled:opacity-50"+ />+ <button+ onClick={() => onRefine(feedback)} disabled={busy || disabled}+ className="inline-flex items-center gap-1 bg-port-card border border-port-border hover:border-port-accent px-3 py-1.5 rounded text-sm disabled:opacity-50"+ >+ {busy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Wand2 className="w-4 h-4" />} Refine+ </button>+ </div>+ </div>+ );+}++function StepPanel({ session, universe, series, issues, stepId, locked, onChanged }) {+ const [busy, setBusy] = useState(false);+ const arc = series?.arc || {};++ const runGenerate = async () => {+ setBusy(true);+ const res = await generateStoryStep(session.id, stepId, {}, { silent: true })+ .catch((err) => { toast.error(err?.message || 'Generation failed'); return null; });+ setBusy(false);+ if (res) { toast.success('Generated'); onChanged(); }+ };+ const runRefine = async (feedback, entryId) => {+ setBusy(true);+ const res = await refineStoryStep(session.id, stepId, { feedback, entryId }, { silent: true })+ .catch((err) => { toast.error(err?.message || 'Refine failed'); return null; });+ setBusy(false);+ if (res) {+ toast.success(res.changes?.length ? `Refined — ${res.changes.length} change(s)` : 'Refined');+ onChanged();+ }+ };++ const genButton = (label = 'Generate with AI') => (+ <button+ onClick={runGenerate} disabled={busy || locked}+ className="inline-flex items-center gap-2 bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white px-3 py-1.5 rounded text-sm"+ >+ {busy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4" />} {label}+ </button>+ );++ if (stepId === 'idea') {+ return (+ <div className="space-y-3">+ <FieldBlock label="Working title" value={session.title} />+ <FieldBlock label="Starter idea" value={session.seedIdea} />+ {!locked && genButton('Expand idea with AI')}+ <p className="text-xs text-gray-500">Expanding seeds the universe starter prompt and series premise for the next steps.</p>+ </div>+ );+ }+ if (stepId === 'universeAesthetic') {+ return (+ <div className="space-y-3">+ <FieldBlock label="Logline" value={universe?.logline} />+ <FieldBlock label="Premise" value={universe?.premise} />+ <FieldBlock label="Style notes" value={universe?.styleNotes} />+ <FieldBlock label="Influences — embrace" value={(universe?.influences?.embrace || []).join(', ')} />+ <FieldBlock label="Influences — avoid" value={(universe?.influences?.avoid || []).join(', ')} />+ <div className="flex items-center gap-2">+ {!locked && genButton('Expand aesthetic')}+ {universe?.id && (+ <Link to={`/universes/${universe.id}`} className="inline-flex items-center gap-1 text-sm text-gray-400 hover:text-port-accent">+ <ExternalLink className="w-4 h-4" /> Deep-edit in Universe Builder+ </Link>+ )}+ </div>+ {!locked && <RefineBox onRefine={(fb) => runRefine(fb)} busy={busy} />}+ </div>+ );+ }+ if (stepId === 'plotArc') {+ return (+ <div className="space-y-3">+ <FieldBlock label="Arc logline" value={arc.logline} />+ <FieldBlock label="Arc summary" value={arc.summary} />+ <FieldBlock label="Protagonist arc" value={arc.protagonistArc} />+ <FieldBlock label="Themes" value={(arc.themes || []).join(', ')} />+ <FieldBlock label="Emotional shape (Vonnegut)" value={arc.shape} />+ <div className="flex items-center gap-2">+ {!locked && genButton('Generate plot arc')}+ {series?.id && (+ <Link to={`/pipeline/series/${series.id}`} className="inline-flex items-center gap-1 text-sm text-gray-400 hover:text-port-accent">+ <ExternalLink className="w-4 h-4" /> Deep-edit on the Arc Canvas+ </Link>+ )}+ </div>+ </div>+ );+ }+ if (stepId === 'readerMap') {+ return (+ <div className="space-y-3">+ <ReaderMapView readerMap={arc.readerMap} />+ {!locked && genButton('Generate reader map')}+ {!locked && arc.readerMap && <RefineBox onRefine={(fb) => runRefine(fb)} busy={busy} />}+ </div>+ );+ }+ if (stepId === 'characters') {+ const cast = universe?.characters || [];+ return (+ <div className="space-y-3">+ {cast.length === 0 && (+ <p className="text-gray-600 italic text-sm">+ No characters yet. Add them in the <Link to={universe?.id ? `/universes/${universe.id}` : '/universes'} className="text-port-accent">Universe Builder</Link> or after generating the arc.+ </p>+ )}+ {cast.map((c) => (+ <div key={c.id} className="bg-port-bg border border-port-border rounded p-2 flex items-start justify-between gap-2">+ <div>+ <div className="font-medium text-sm">{c.name} {c.locked && <Lock className="w-3 h-3 inline text-port-success" />}</div>+ <div className="text-xs text-gray-400">{c.physicalDescription || (Array.isArray(c.descriptor) ? c.descriptor.map((d) => d.value).join(', ') : '')}</div>+ </div>+ {!locked && (+ <button+ onClick={() => runRefine('', c.id)} disabled={busy}+ className="text-xs inline-flex items-center gap-1 border border-port-border rounded px-2 py-1 hover:border-port-accent disabled:opacity-50"+ >+ <Wand2 className="w-3 h-3" /> Refine+ </button>+ )}+ </div>+ ))}+ </div>+ );+ }+ if (stepId === 'issues') {+ return <IssuesPanel session={session} series={series} issues={issues} onChanged={onChanged} />;+ }+ if (stepId === 'production') {+ const locks = session.steps?.issues?.issueLocks || {};+ const done = (issues || []).filter((i) => locks[i.id]?.locked);+ return (+ <div className="space-y-3">+ <p className="text-sm text-gray-400">Render each completed issue. Production happens on the Pipeline issue page.</p>+ {done.length === 0 && <p className="text-gray-600 italic text-sm">Lock at least one issue on the previous step first.</p>}+ {done.map((i) => (+ <div key={i.id} className="flex items-center justify-between bg-port-bg border border-port-border rounded px-3 py-2">+ <span className="text-sm">#{i.number} {i.title}</span>+ <Link to={`/pipeline/issues/${i.id}/storyboards`} className="text-sm text-port-accent inline-flex items-center gap-1">+ Open production <ExternalLink className="w-4 h-4" />+ </Link>+ </div>+ ))}+ </div>+ );+ }+ return null;+}++function IssuesPanel({ session, series, issues, onChanged }) {+ const locks = session.steps?.issues?.issueLocks || {};+ const [busyId, setBusyId] = useState(null);++ const toggleIssue = async (issueId, next) => {+ setBusyId(issueId);+ const res = await setStoryIssueLock(session.id, issueId, next, { silent: true })+ .catch((err) => { toast.error(err?.message || 'Failed'); return null; });+ setBusyId(null);+ if (res) { toast.success(next ? 'Issue marked done' : 'Issue reopened'); onChanged(); }+ };++ return (+ <div className="space-y-3">+ <div className="flex items-center justify-between">+ <p className="text-sm text-gray-400">Complete issues one at a time. Lock issue #1 before moving to #2.</p>+ {series?.id && (+ <Link to={`/pipeline/series/${series.id}`} className="text-sm text-port-accent inline-flex items-center gap-1">+ Plan issues in Pipeline <ExternalLink className="w-4 h-4" />+ </Link>+ )}+ </div>+ {(!issues || issues.length === 0) && (+ <p className="text-gray-600 italic text-sm">No issues yet — generate seasons on the plot-arc step, then plan issues in the Pipeline.</p>+ )}+ {(issues || []).map((i) => {+ const isLocked = locks[i.id]?.locked;+ return (+ <div key={i.id} className="flex items-center justify-between bg-port-bg border border-port-border rounded px-3 py-2">+ <div className="flex items-center gap-2">+ {isLocked ? <Check className="w-4 h-4 text-port-success" /> : <span className="w-4 h-4" />}+ <span className="text-sm">#{i.number} {i.title}</span>+ <span className="text-xs text-gray-500">{i.status}</span>+ </div>+ <div className="flex items-center gap-2">+ <Link to={`/pipeline/issues/${i.id}/idea`} className="text-xs text-gray-400 hover:text-port-accent inline-flex items-center gap-1">+ Open <ExternalLink className="w-3 h-3" />+ </Link>+ <button+ onClick={() => toggleIssue(i.id, !isLocked)} disabled={busyId === i.id}+ className={`text-xs inline-flex items-center gap-1 border rounded px-2 py-1 disabled:opacity-50 ${isLocked ? 'border-port-success text-port-success' : 'border-port-border hover:border-port-accent'}`}+ >+ {busyId === i.id ? <Loader2 className="w-3 h-3 animate-spin" /> : (isLocked ? <Unlock className="w-3 h-3" /> : <Lock className="w-3 h-3" />)}+ {isLocked ? 'Reopen' : 'Mark done'}+ </button>+ </div>+ </div>+ );+ })}+ </div>+ );+}++// ── Detail view: stepper + active panel ─────────────────────────────────────++function StoryBuilderDetail({ storyId, stepParam }) {+ const navigate = useNavigate();+ const [steps, setSteps] = useState([]);+ const [session, setSession] = useState(null);+ const [staleSteps, setStaleSteps] = useState([]);+ const [universe, setUniverse] = useState(null);+ const [series, setSeries] = useState(null);+ const [issues, setIssues] = useState([]);+ const [loading, setLoading] = useState(true);++ const reload = useCallback(async () => {+ const s = await getStorySession(storyId, { silent: true }).catch(() => null);+ if (!s) { setSession(null); setLoading(false); return; }+ setSession(s);+ setStaleSteps(s.staleSteps || []);+ const [u, ser] = await Promise.all([+ s.universeId ? getUniverse(s.universeId).catch(() => null) : Promise.resolve(null),+ s.seriesId ? getPipelineSeries(s.seriesId).catch(() => null) : Promise.resolve(null),+ ]);+ setUniverse(u);+ setSeries(ser);+ if (s.seriesId) {+ const iss = await listPipelineIssues(s.seriesId).catch(() => []);+ setIssues(Array.isArray(iss) ? iss : (iss?.items || []));+ }+ setLoading(false);+ }, [storyId]);++ useEffect(() => { getStoryBuilderSteps({ silent: true }).then((r) => setSteps(r.steps || [])).catch(() => {}); }, []);+ useEffect(() => { setLoading(true); reload(); }, [reload]);++ const stepIds = steps.map((s) => s.id);+ const activeStepId = stepIds.includes(stepParam) ? stepParam : (session?.currentStep || 'idea');+ const activeIdx = stepIds.indexOf(activeStepId);+ const activeStep = steps[activeIdx];+ const stepState = session?.steps?.[activeStepId] || { status: 'pending', locked: false };+ const isStale = staleSteps.includes(activeStepId);++ // A step is reachable when every earlier step is locked AND not stale.+ const reachable = useCallback((idx) => {+ if (idx <= 0) return true;+ for (let i = 0; i < idx; i++) {+ const id = stepIds[i];+ if (session?.steps?.[id]?.locked !== true) return false;+ if (staleSteps.includes(id)) return false;+ }+ return true;+ }, [stepIds, session, staleSteps]);++ const lock = useLockToggle({+ patchFn: (next) => (next ? lockStoryStep(storyId, activeStepId, { silent: true }) : unlockStoryStep(storyId, activeStepId, { silent: true })),+ onSuccess: () => reload(),+ lockedMessage: `${activeStep?.label || 'Step'} locked`,+ unlockedMessage: `${activeStep?.label || 'Step'} unlocked`,+ errorMessage: 'Failed to update lock',+ });++ const goToStep = async (id, idx) => {+ if (!reachable(idx)) { toast.error('Lock the earlier steps first'); return; }+ // Persist the current-step pointer (server re-gates); navigate optimistically.+ await setStoryCurrentStep(storyId, id, { silent: true }).catch(() => {});+ navigate(`/story-builder/${storyId}/${id}`);+ };++ if (loading) return <div className="p-6 text-gray-400 flex items-center gap-2"><Loader2 className="w-5 h-5 animate-spin" /> Loading…</div>;+ if (!session) return <div className="p-6 text-gray-400">Session not found. <Link to="/story-builder" className="text-port-accent">Back to Story Builder</Link></div>;++ return (+ <div className="h-full overflow-y-auto p-4 md:p-6">+ <div className="max-w-5xl mx-auto">+ <header className="mb-4">+ <Link to="/story-builder" className="text-xs text-gray-500 hover:text-port-accent">← All stories</Link>+ <h1 className="text-2xl font-bold flex items-center gap-2 mt-1">+ <Sparkles className="w-6 h-6 text-port-accent" /> {session.title}+ </h1>+ </header>++ <div className="grid grid-cols-1 md:grid-cols-[220px_1fr] gap-6">+ {/* Step rail */}+ <nav className="space-y-1">+ {steps.map((s, idx) => {+ const st = session.steps?.[s.id] || { status: 'pending', locked: false };+ const stale = staleSteps.includes(s.id);+ const isActive = s.id === activeStepId;+ const canGo = reachable(idx);+ return (+ <button+ key={s.id} onClick={() => goToStep(s.id, idx)} disabled={!canGo}+ className={`w-full text-left px-3 py-2 rounded border flex items-center justify-between gap-2 ${+ isActive ? 'border-port-accent bg-port-card' : 'border-transparent hover:bg-port-card'+ } ${!canGo ? 'opacity-40 cursor-not-allowed' : ''}`}+ >+ <span className="flex items-center gap-2 text-sm">+ {st.locked ? <Lock className="w-3.5 h-3.5 text-port-success" /> : <span className="w-3.5 h-3.5 rounded-full border border-gray-600 inline-block" />}+ {s.label}+ </span>+ {stale && <AlertTriangle className="w-3.5 h-3.5 text-port-warning" title="Stale — re-review" />}+ </button>+ );+ })}+ </nav>++ {/* Active step */}+ <section className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">+ <div className="flex items-start justify-between">+ <div>+ <h2 className="text-lg font-semibold">{activeStep?.label}</h2>+ <p className="text-sm text-gray-400">{activeStep?.description}</p>+ </div>+ <span className={`text-xs ${STATUS_BADGE[stepState.status]?.cls}`}>{STATUS_BADGE[stepState.status]?.label}</span>+ </div>++ {isStale && (+ <div className="flex items-center gap-2 text-sm text-port-warning bg-port-warning/10 border border-port-warning/30 rounded px-3 py-2">+ <AlertTriangle className="w-4 h-4" /> An earlier step changed after you locked this — re-review and re-lock to continue.+ </div>+ )}++ <StepPanel+ session={session} universe={universe} series={series} issues={issues}+ stepId={activeStepId} locked={stepState.locked} onChanged={reload}+ />++ {/* Footer: lock + navigation */}+ <div className="flex items-center justify-between border-t border-port-border pt-3 mt-3">+ <button+ onClick={() => lock.toggle(stepState.locked)} disabled={lock.busy}+ className={`inline-flex items-center gap-2 px-3 py-1.5 rounded text-sm disabled:opacity-50 ${+ stepState.locked ? 'bg-port-card border border-port-success text-port-success' : 'bg-port-success hover:bg-green-600 text-white'+ }`}+ >+ {lock.busy ? <Loader2 className="w-4 h-4 animate-spin" /> : (stepState.locked ? <Unlock className="w-4 h-4" /> : <Check className="w-4 h-4" />)}+ {stepState.locked ? 'Unlock to revise' : 'Lock & continue'}+ </button>++ <div className="flex items-center gap-2">+ {activeIdx > 0 && (+ <button onClick={() => goToStep(stepIds[activeIdx - 1], activeIdx - 1)} className="inline-flex items-center gap-1 text-sm text-gray-400 hover:text-white">+ <ChevronLeft className="w-4 h-4" /> Back+ </button>+ )}+ {activeIdx < steps.length - 1 && (+ <button+ onClick={() => goToStep(stepIds[activeIdx + 1], activeIdx + 1)}+ disabled={!stepState.locked || isStale}+ className="inline-flex items-center gap-1 text-sm bg-port-accent hover:bg-blue-600 disabled:opacity-40 text-white px-3 py-1.5 rounded"+ >+ Next <ChevronRight className="w-4 h-4" />+ </button>+ )}+ </div>+ </div>+ </section>+ </div>+ </div>+ </div>+ );+}++export default function StoryBuilder() {+ const { storyId, step } = useParams();+ if (!storyId) return <StoryBuilderIndex />;+ return <StoryBuilderDetail storyId={storyId} stepParam={step} />;+}diff --git a/client/src/pages/StoryBuilder.test.jsx b/client/src/pages/StoryBuilder.test.jsxnew file mode 100644index 0000000000..35bf650aa2--- /dev/null+++ b/client/src/pages/StoryBuilder.test.jsx@@ -0,0 +1,103 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter, Routes, Route } from 'react-router-dom';++const STEPS = [+ { id: 'idea', label: 'Idea', description: 'Capture a starter idea.' },+ { id: 'universeAesthetic', label: 'Universe Aesthetic', description: 'Lock the look.' },+ { id: 'plotArc', label: 'Plot Arc', description: 'Expand the arc.' },+ { id: 'readerMap', label: 'Reader Map', description: 'Plan the reader experience.' },+ { id: 'characters', label: 'Characters', description: 'Lock the cast.' },+ { id: 'issues', label: 'Issues', description: 'Complete issues.' },+ { id: 'production', label: 'Production', description: 'Render.' },+];++const mkSteps = (overrides = {}) => Object.fromEntries(STEPS.map((s) => [+ s.id, overrides[s.id] || { status: 'pending', locked: false, lockedAt: null, upstreamHash: null },+]));++const api = vi.hoisted(() => ({+ getStoryBuilderSteps: vi.fn(),+ listStorySessions: vi.fn(),+ getStorySession: vi.fn(),+ createStorySession: vi.fn(),+ updateStorySession: vi.fn(),+ setStoryCurrentStep: vi.fn(),+ lockStoryStep: vi.fn(),+ unlockStoryStep: vi.fn(),+ generateStoryStep: vi.fn(),+ refineStoryStep: vi.fn(),+ setStoryIssueLock: vi.fn(),+ getUniverse: vi.fn(),+ getPipelineSeries: vi.fn(),+ listPipelineIssues: vi.fn(),+}));+vi.mock('../services/api', () => api);++import StoryBuilder from './StoryBuilder';++const renderAt = (path) => render(+ <MemoryRouter initialEntries={[path]}>+ <Routes>+ <Route path="/story-builder" element={<StoryBuilder />} />+ <Route path="/story-builder/:storyId/:step" element={<StoryBuilder />} />+ </Routes>+ </MemoryRouter>,+);++beforeEach(() => {+ vi.clearAllMocks();+ api.getStoryBuilderSteps.mockResolvedValue({ steps: STEPS });+ api.listStorySessions.mockResolvedValue([]);+ api.setStoryCurrentStep.mockResolvedValue({});+ api.lockStoryStep.mockResolvedValue({});+ api.unlockStoryStep.mockResolvedValue({});+ api.generateStoryStep.mockResolvedValue({ result: {} });+ api.refineStoryStep.mockResolvedValue({ result: {}, changes: [] });+ api.setStoryIssueLock.mockResolvedValue({});+ api.getUniverse.mockResolvedValue({ id: 'u1', logline: 'L', premise: 'P', styleNotes: 'S', influences: { embrace: [], avoid: [] }, characters: [] });+ api.getPipelineSeries.mockResolvedValue({ id: 's1', arc: { logline: 'AL', summary: 'AS', readerMap: { hooks: [{ id: 'rm-1', label: 'Why?' }] } } });+ api.listPipelineIssues.mockResolvedValue([]);+});++describe('StoryBuilder — index', () => {+ it('renders the create form', async () => {+ renderAt('/story-builder');+ expect(await screen.findByText('Start a new story')).toBeTruthy();+ expect(screen.getByLabelText('Universe / story name')).toBeTruthy();+ });+});++describe('StoryBuilder — detail stepper', () => {+ it('gates the Next button until the active step is locked', async () => {+ api.getStorySession.mockResolvedValue({+ id: 'stb-1', title: 'Salt Run', currentStep: 'idea', seedIdea: 'seed',+ universeId: 'u1', seriesId: 's1', steps: mkSteps(), staleSteps: [],+ });+ renderAt('/story-builder/stb-1/idea');+ await waitFor(() => expect(screen.getByRole('heading', { name: 'Idea' })).toBeTruthy());+ // Idea not locked → primary action is "Lock & continue" and Next is disabled.+ expect(screen.getByText('Lock & continue')).toBeTruthy();+ const next = screen.getByRole('button', { name: /Next/i });+ expect(next.disabled).toBe(true);+ });++ it('shows the stale warning + "Unlock to revise" when an upstream step changed', async () => {+ api.getStorySession.mockResolvedValue({+ id: 'stb-1', title: 'Salt Run', currentStep: 'readerMap', seedIdea: 'seed',+ universeId: 'u1', seriesId: 's1',+ steps: mkSteps({+ idea: { status: 'locked', locked: true },+ universeAesthetic: { status: 'locked', locked: true },+ plotArc: { status: 'locked', locked: true },+ readerMap: { status: 'locked', locked: true, upstreamHash: 'old' },+ }),+ staleSteps: ['readerMap'],+ });+ renderAt('/story-builder/stb-1/readerMap');+ await waitFor(() => expect(screen.getByRole('heading', { name: 'Reader Map' })).toBeTruthy());+ expect(screen.getByText(/re-review and re-lock/i)).toBeTruthy();+ // Locked step → the action flips to "Unlock to revise".+ expect(screen.getByText('Unlock to revise')).toBeTruthy();+ });+});diff --git a/client/src/services/README.md b/client/src/services/README.mdindex bf38ede41c..1a33457c27 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -95,6 +95,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiAsk.js` | Ask page (chat-like). || `apiGSD.js` | "Get Stuff Done" integration. || `apiImporter.js` | Manuscript / chat importer. |+| `apiStoryBuilder.js` | Unified Story Builder conductor (sessions, step lock/unlock, generate/refine). || `apiOpenClaw.js` | File browser / picker backend. || `apiPalette.js` | Command-palette manifest + action dispatch. || `apiVoice.js` | Voice synthesis / processing. |diff --git a/client/src/services/api.js b/client/src/services/api.jsindex bd3591fd85..0d0f651908 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -48,6 +48,7 @@ export * from './apiPeerSync.js';export * from './apiSyncReview.js';export * from './apiCreativeDirector.js';export * from './apiImporter.js';+export * from './apiStoryBuilder.js';export * from './apiVoice.js';// Default export for simplified imports (get/post/put/delete helpers)diff --git a/client/src/services/apiStoryBuilder.js b/client/src/services/apiStoryBuilder.jsnew file mode 100644index 0000000000..f1ce2d127a--- /dev/null+++ b/client/src/services/apiStoryBuilder.js@@ -0,0 +1,58 @@+import { request } from './apiCore.js';++// Unified Story Builder — conductor API. Mirrors apiImporter.js. The server is+// the single source of truth for the step manifest (GET /story-builder/steps),+// so the client stepper doesn't hardcode the order.++export const getStoryBuilderSteps = (options = {}) => request('/story-builder/steps', options);++export const listStorySessions = (options = {}) => request('/story-builder', options);++export const getStorySession = (id, options = {}) => request(`/story-builder/${id}`, options);++export const createStorySession = (payload, options = {}) => request('/story-builder', {+ method: 'POST',+ body: JSON.stringify(payload),+ ...options,+});++export const updateStorySession = (id, patch, options = {}) => request(`/story-builder/${id}`, {+ method: 'PATCH',+ body: JSON.stringify(patch),+ ...options,+});++export const deleteStorySession = (id, options = {}) => request(`/story-builder/${id}`, {+ method: 'DELETE',+ ...options,+});++export const setStoryCurrentStep = (id, stepId, options = {}) =>+ request(`/story-builder/${id}/current-step/${stepId}`, { method: 'POST', ...options });++export const lockStoryStep = (id, stepId, options = {}) =>+ request(`/story-builder/${id}/steps/${stepId}/lock`, { method: 'POST', ...options });++export const unlockStoryStep = (id, stepId, options = {}) =>+ request(`/story-builder/${id}/steps/${stepId}/unlock`, { method: 'POST', ...options });++export const generateStoryStep = (id, stepId, payload = {}, options = {}) =>+ request(`/story-builder/${id}/steps/${stepId}/generate`, {+ method: 'POST',+ body: JSON.stringify(payload),+ ...options,+ });++export const refineStoryStep = (id, stepId, payload = {}, options = {}) =>+ request(`/story-builder/${id}/steps/${stepId}/refine`, {+ method: 'POST',+ body: JSON.stringify(payload),+ ...options,+ });++export const setStoryIssueLock = (id, issueId, locked, options = {}) =>+ request(`/story-builder/${id}/issues/${issueId}/lock`, {+ method: 'POST',+ body: JSON.stringify({ locked }),+ ...options,+ });diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex 88ca23e030..d590344b36 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -228,6 +228,27 @@"returnsJson": true,"variables": []},+ "story-builder-idea-expand": {+ "name": "Story Builder — Idea Expand",+ "description": "Expand a one-line seed idea into a working title, logline, and a world-and-arc-ready premise for the Unified Story Builder's first step (seed intake mode). Seeds the universe starter prompt and the series premise.",+ "model": "default",+ "returnsJson": true,+ "variables": []+ },+ "story-builder-reader-map": {+ "name": "Story Builder — Reader Map",+ "description": "Plan the reader/viewer's experience across a series arc — hooks, payoffs, emotional beats, and cliffhangers — built on the protagonist arc and Vonnegut shape. Distinct from the protagonist arc; lives at series.arc.readerMap.",+ "model": "default",+ "returnsJson": true,+ "variables": []+ },+ "story-builder-reader-map-refine": {+ "name": "Story Builder — Reader Map Refine",+ "description": "Refine an existing reader map against free-text feedback, returning the full revised map plus a changes list and rationale (the AI-feedback affordance for the Story Builder reader-map step).",+ "model": "default",+ "returnsJson": true,+ "variables": []+ },"pipeline-arc-overview": {"name": "Pipeline — Series Arc Overview","description": "Plan the top-level multi-season story spine for a series from its bible: a series-level logline, summary, themes, protagonist arc, and a 2–5 season breakdown with per-season loglines, ending hooks, and episode-count targets. Runs at `heavy` tier — most expensive single call in the pipeline.",diff --git a/data.reference/prompts/stages/story-builder-idea-expand.md b/data.reference/prompts/stages/story-builder-idea-expand.mdnew file mode 100644index 0000000000..ea4a6e09d7--- /dev/null+++ b/data.reference/prompts/stages/story-builder-idea-expand.md@@ -0,0 +1,30 @@+# Story Builder — Idea Expand++You are a story development partner helping a creator turn a one-line seed idea into a workable starting point for a serialized story (comic / TV). Stay faithful to the seed's intent — expand and sharpen it, don't replace it with your own concept.++## The seed++{{#universeName}}- Working universe name: {{universeName}}{{/universeName}}+- Seed idea: {{seedIdea}}++## Task++Expand the seed into a concrete launch point:++1. **title** — a short, evocative working title for the story/series (≤ 80 chars).+2. **logline** — one sentence capturing the hook and central tension (≤ 280 chars).+3. **expandedIdea** — 1–2 paragraphs that develop the seed into a premise the creator can build a world and arc from: who/what it's about, the central conflict, the tone, and what makes it serialized (why there's more than one issue). This text seeds both the universe's starter prompt and the series premise, so make it world-and-arc ready.++Do not invent canon names, plot specifics, or a full arc — that comes in later steps. Just give a strong, faithful launch point.++## Output++Return ONLY a JSON object (no prose, no code fence):++```json+{+ "title": "string",+ "logline": "string",+ "expandedIdea": "string"+}+```diff --git a/data.reference/prompts/stages/story-builder-reader-map-refine.md b/data.reference/prompts/stages/story-builder-reader-map-refine.mdnew file mode 100644index 0000000000..3483d2afda--- /dev/null+++ b/data.reference/prompts/stages/story-builder-reader-map-refine.md@@ -0,0 +1,41 @@+# Story Builder — Reader Map Refine++You are refining an existing **reader map** (the roadmap of what the audience feels and wonders across a serialized story) in response to specific feedback. Apply the feedback surgically — keep what works, change only what the feedback calls for.++## Current reader map++```json+{{currentReaderMapJson}}+```++## Story context (for grounding)++{{#arcSummary}}- Arc summary: {{arcSummary}}{{/arcSummary}}+{{#protagonistArc}}- Protagonist arc: {{protagonistArc}}{{/protagonistArc}}++### Emotional backbone (Vonnegut shape)++{{shapeGuidance}}++## Feedback to apply++{{#feedback}}{{feedback}}{{/feedback}}{{^feedback}}(no specific feedback — tighten pacing: ensure every hook has a payoff, escalate intensity toward act breaks, and place cliffhangers at issue boundaries.){{/feedback}}++## Task++Return the FULL revised reader map (not a diff). Preserve entries the feedback doesn't touch. Beat `kind` must be one of: {{beatKindsCsv}}. `intensity` is 0.0–1.0. Leave `resolvesHookId` as `null`. Also return a short `changes` list (≤ 12 bullet strings) describing what you changed, and a one-sentence `rationale`.++## Output++Return ONLY a JSON object (no prose, no code fence):++```json+{+ "hooks": [{ "label": "string", "atArcPosition": 0, "note": "string" }],+ "payoffs": [{ "label": "string", "atArcPosition": 0, "resolvesHookId": null, "note": "string" }],+ "beats": [{ "kind": "hook|reveal|payoff|emotional|cliffhanger", "atArcPosition": 0, "intensity": 0.5, "note": "string" }],+ "cliffhangers": [{ "atIssueBoundary": 1, "note": "string" }],+ "changes": ["string"],+ "rationale": "string"+}+```diff --git a/data.reference/prompts/stages/story-builder-reader-map.md b/data.reference/prompts/stages/story-builder-reader-map.mdnew file mode 100644index 0000000000..0432a7cd68--- /dev/null+++ b/data.reference/prompts/stages/story-builder-reader-map.md@@ -0,0 +1,63 @@+# Story Builder — Reader Map++You are a developmental editor planning the **reader/viewer's experience** of a serialized story — distinct from the protagonist's internal arc. The protagonist arc describes how the *character* changes; the **reader map** describes what the *audience* feels and wonders as they move through the content: the questions you plant (hooks), where you pay them off, the emotional beats, and the cliffhangers between issues.++## The series++- Series: {{series.name}}+{{#series.logline}}- Logline: {{series.logline}}{{/series.logline}}+{{#series.premise}}- Premise: {{series.premise}}{{/series.premise}}++## Story arc (the protagonist spine — build the reader map ON TOP of this)++{{#arc.logline}}- Arc logline: {{arc.logline}}{{/arc.logline}}+{{#arc.summary}}- Arc summary: {{arc.summary}}{{/arc.summary}}+{{#arc.protagonistArc}}- Protagonist arc: {{arc.protagonistArc}}{{/arc.protagonistArc}}+{{#arc.themesCsv}}- Themes: {{arc.themesCsv}}{{/arc.themesCsv}}++### Emotional backbone (Vonnegut shape)++{{shapeGuidance}}++The reader's emotional beats should track this fortune curve — the audience's felt highs and lows should mirror, anticipate, or deliberately counterpoint the protagonist's fortune at each point along the arc.++## Volume / issue boundaries (place cliffhangers at the gaps)++{{issueBoundaries}}++{{#hasLinkedWorld}}+## Linked world++- World: {{worldName}}+{{#worldLogline}}- World logline: {{worldLogline}}{{/worldLogline}}+{{/hasLinkedWorld}}++## Existing reader map (if any — improve, don't discard wholesale)++```json+{{existingReaderMapJson}}+```++## Task++Produce a reader map: the roadmap of the audience's experience across the whole arc. Use **arc positions** as a 0-based ordinal scale along the arc (0 = opening, higher = later; you can think of them as issue/episode numbers when volume boundaries are given above).++1. **Hooks** — the open questions / promises / mysteries you plant to pull the reader forward. Each: a short `label`, the `atArcPosition` where it's planted, and a `note` on why it grips.+2. **Payoffs** — where each promise is resolved or subverted. Each: a `label`, the `atArcPosition` where it lands, an optional `note`. Leave `resolvesHookId` as `null` (the app links payoffs to hooks).+3. **Beats** — the felt emotional moments along the way. Each: a `kind` (one of: {{beatKindsCsv}}), the `atArcPosition`, an `intensity` from 0.0 to 1.0 (how strongly the reader feels it), and a `note`.+4. **Cliffhangers** — the unresolved tension at issue/volume boundaries that makes the reader pick up the next issue. Each: the `atIssueBoundary` (the issue number AFTER which it lands) and a `note`.++Pace deliberately: plant hooks early, escalate intensity toward act breaks, and make sure every major hook has a payoff. Cliffhangers should sit at the boundaries above.++## Output++Return ONLY a JSON object (no prose, no code fence):++```json+{+ "hooks": [{ "label": "string", "atArcPosition": 0, "note": "string" }],+ "payoffs": [{ "label": "string", "atArcPosition": 0, "resolvesHookId": null, "note": "string" }],+ "beats": [{ "kind": "hook|reveal|payoff|emotional|cliffhanger", "atArcPosition": 0, "intensity": 0.5, "note": "string" }],+ "cliffhangers": [{ "atIssueBoundary": 1, "note": "string" }]+}+```diff --git a/scripts/migrations/043-story-builder-prompts.js b/scripts/migrations/043-story-builder-prompts.jsnew file mode 100644index 0000000000..ab027dc4c9--- /dev/null+++ b/scripts/migrations/043-story-builder-prompts.js@@ -0,0 +1,88 @@+/**+ * Seed the Unified Story Builder prompt stages into existing installs.+ *+ * Multi-file variant of `041-editorial-analysis-stage.js`: copies the three+ * `.md` templates from `data.reference/prompts/stages/` and merges their+ * stage-config entries into `data/prompts/stage-config.json`. Boot runs+ * migrations (server/index.js) but NOT `setup-data.js`, so an upgrade that+ * pulls + `pm2 restart`s (rather than running `update.sh`) would otherwise+ * leave the new Story Builder stages unseeded and the first reader-map /+ * idea-expand generation would throw "Stage not found".+ */++import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';+import { dirname, join } from 'path';++// Each prompt file's basename doubles as its stage-config key (sans `.md`).+const STAGES = [+ 'story-builder-idea-expand',+ 'story-builder-reader-map',+ 'story-builder-reader-map-refine',+];++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(`📝 story-builder prompt: ${filename} already present`);+ continue;+ }+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);+ if (!sampleExists) {+ console.warn(`⚠️ story-builder: sample missing for ${filename} — skipping copy`);+ continue;+ }+ try {+ await copyFile(samplePath, dataPath);+ console.log(`✅ seeded ${filename}`);+ } catch (err) {+ console.warn(`⚠️ story-builder: copy failed for ${filename}: ${err.message}`);+ }+ }++ // 2. Merge any 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('⚠️ story-builder: 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(`⚠️ story-builder: sample stage-config missing ${key} — skipping`);+ continue;+ }+ installed.stages[key] = sample.stages[key];+ added += 1;+ }+ if (added === 0) {+ console.log('📝 story-builder stage-config: all entries already present');+ return;+ }+ await mkdir(dirname(installedConfigPath), { recursive: true });+ await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');+ const action = installedExists ? 'merged' : 'created';+ console.log(`📝 story-builder stage-config (${action}): ${added} added`);+ } catch (err) {+ console.warn(`⚠️ story-builder: stage-config merge failed: ${err.message}`);+ }+ },+};diff --git a/scripts/migrations/043-story-builder-prompts.test.js b/scripts/migrations/043-story-builder-prompts.test.jsnew file mode 100644index 0000000000..c0e79349f5--- /dev/null+++ b/scripts/migrations/043-story-builder-prompts.test.js@@ -0,0 +1,73 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './043-story-builder-prompts.js';++const STAGES = ['story-builder-idea-expand', 'story-builder-reader-map', 'story-builder-reader-map-refine'];+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++describe('migration 043 — seed Story Builder prompts', () => {+ let rootDir;+ let installedStagesDir;+ let installedConfigPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-043-'));+ // Seed the data.reference fixtures the migration copies FROM.+ const refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');+ mkdirSync(refStagesDir, { recursive: true });+ for (const key of STAGES) {+ writeFileSync(join(refStagesDir, `${key}.md`), `# ${key}\n\nbody for ${key}\n`);+ }+ const refConfig = { stages: {} };+ for (const key of STAGES) {+ refConfig.stages[key] = { name: key, model: 'default', returnsJson: true, variables: [] };+ }+ writeFileSync(join(rootDir, 'data.reference', 'prompts', 'stage-config.json'), JSON.stringify(refConfig, null, 2) + '\n');++ installedStagesDir = join(rootDir, 'data', 'prompts', 'stages');+ installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('seeds all three prompt files + stage-config entries on a fresh install', async () => {+ await migration.up({ rootDir });+ for (const key of STAGES) {+ expect(existsSync(join(installedStagesDir, `${key}.md`))).toBe(true);+ }+ const config = readJson(installedConfigPath);+ for (const key of STAGES) {+ expect(config.stages[key]).toBeTruthy();+ }+ });++ it('merges into an existing stage-config without clobbering other stages', async () => {+ mkdirSync(installedStagesDir, { recursive: true });+ writeFileSync(installedConfigPath, JSON.stringify({ stages: { 'pipeline-prose': { name: 'Prose' } } }, null, 2) + '\n');+ await migration.up({ rootDir });+ const config = readJson(installedConfigPath);+ expect(config.stages['pipeline-prose']).toBeTruthy();+ for (const key of STAGES) {+ expect(config.stages[key]).toBeTruthy();+ }+ });++ it('is idempotent and preserves a user-customized installed prompt', async () => {+ mkdirSync(installedStagesDir, { recursive: true });+ // User already customized one of the prompts — the migration must not overwrite it.+ const customPath = join(installedStagesDir, 'story-builder-reader-map.md');+ writeFileSync(customPath, '# CUSTOM reader map\n');+ await migration.up({ rootDir });+ expect(readFileSync(customPath, 'utf-8')).toContain('CUSTOM');+ // Second run is a clean no-op.+ await migration.up({ rootDir });+ expect(readFileSync(customPath, 'utf-8')).toContain('CUSTOM');+ const config = readJson(installedConfigPath);+ expect(Object.keys(config.stages).filter((k) => STAGES.includes(k))).toHaveLength(3);+ });+});diff --git a/server/index.js b/server/index.jsindex 8fedce32ea..756598e7b4 100644--- a/server/index.js+++ b/server/index.js@@ -106,6 +106,7 @@ import { initStoryboardsFilenameHook } from './services/pipeline/storyboardsFileimport { initSeasonCoverFilenameHook } from './services/pipeline/seasonCoverFilenameHook.js';import pipelineRoutes from './routes/pipeline.js';import importerRoutes from './routes/importer.js';+import storyBuilderRoutes from './routes/storyBuilder.js';import { initMediaJobQueue } from './services/mediaJobQueue/index.js';import { recoverInFlightProjects } from './services/creativeDirector/recovery.js';import imageVideoModelsRoutes from './routes/imageVideoModels.js';@@ -453,6 +454,7 @@ app.use('/api/universe-builder', universeBuilderRoutes);app.use('/api/pipeline', pipelineRoutes);app.use('/api/conflict-journal', conflictJournalRoutes);app.use('/api/importer', importerRoutes);+app.use('/api/story-builder', storyBuilderRoutes);app.use('/api/image-video/models', imageVideoModelsRoutes);app.use('/api/loras', lorasRoutes);// AUTOMATIC1111-compatible surface for tailnet clients — gated bydiff --git a/server/lib/README.md b/server/lib/README.mdindex 232ceb6422..ec3caa9f04 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -41,7 +41,9 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|| `storyBible.js` | Canonical Character / Place / Object shapes + `BIBLE_LIMITS`. |-| `storyArc.js` | Canonical Arc + Season shapes for pipeline arc planning. |+| `storyArc.js` | Canonical Arc + Season + Reader-Map shapes for pipeline arc planning. |+| `storyBuilderSteps.js` | Unified Story Builder ordered step definitions + helpers (`STEPS`, `STEP_IDS`, `STEP_STATUSES`, `isValidStepId`, `stepIndex`). |+| `storyBuilderIntegrity.js` | Pure staleness hashing for the Story Builder (`hashUpstream`, `computeStaleSteps`). || `canonPrompt.js` | Per-kind field-precedence rules; SHORT/RICH/PREVIEW spec tables; `flattenCanonDescriptorFragments` / `mapCanonDescriptorFragments` / `descriptorForCanonEntry`. || `scenePrompt.js` | Scene-prompt composer + bible matchers (chars/places/objects in text). || `sceneExtractor.js` | Split prose or teleplay into scene list via LLM. |diff --git a/server/lib/index.js b/server/lib/index.jsindex e6ffe936a9..adc55601a4 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -40,6 +40,8 @@ export * from './sceneExtractor.js';export * from './scenePrompt.js';export * from './seasonStructure.js';export * from './storyArc.js';+export * from './storyBuilderIntegrity.js';+export * from './storyBuilderSteps.js';// `storyBible.js` re-exports `normalizeSlugline` from `scenePrompt.js` for// back-compat — namespace it so the canonical scenePrompt export wins flat.export * as storyBible from './storyBible.js';diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 6133f4f2c9..23e649e411 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -23,6 +23,7 @@ export const NAV_COMMANDS = [{ id: 'nav.create.pipeline', path: '/pipeline', label: 'Series Pipeline', section: 'Create', aliases: ['series', 'pipeline', 'production', 'series-pipeline', 'production-pipeline'], keywords: ['series', 'issue', 'episode', 'comic', 'script', 'prose', 'storyboard', 'narrative', 'workflow'] },{ id: 'nav.create.sharing', path: '/sharing', label: 'Sharing', section: 'Create', aliases: ['sharing', 'share', 'buckets', 'share-buckets'], keywords: ['google drive', 'dropbox', 'icloud', 'syncthing', 'export', 'import', 'collaborate', 'federation', 'peer', 'cross-network'] },{ id: 'nav.create.sharing-duplicates', path: '/sharing/duplicates', label: 'Duplicates', section: 'Create', aliases: ['duplicates', 'duplicate-universes', 'duplicate-series', 'dedupe', 'merge-duplicates'], keywords: ['duplicate', 'merge', 'rename', 'same name', 'two copies', 'reconcile', 'collision'] },+ { id: 'nav.create.story-builder', path: '/story-builder', label: 'Story Builder', section: 'Create', aliases: ['story-builder', 'storybuilder', 'guided', 'new-story', 'story-wizard'], keywords: ['idea', 'universe', 'arc', 'reader map', 'guided', 'wizard', 'linear', 'lock', 'front door', 'episode', 'series'] },{ id: 'nav.create.sharing-conflicts', path: '/sharing/conflicts', label: 'Conflicts', section: 'Create', aliases: ['conflicts', 'sync-conflicts', 'edit-conflicts', 'conflict-journal'], keywords: ['conflict', 'overwrite', 'lost edit', 'restore', 'merge fields', 'last write wins', 'diverged', 'recover'] },{ id: 'nav.media.loras', path: '/media/loras', label: 'LoRAs', section: 'Create', aliases: ['loras', 'lora', 'lora-manager', 'civitai'], keywords: ['lora', 'civitai', 'fine-tune', 'style adapter', 'realstagram', 'photoreal', 'flux lora'] },{ id: 'nav.media.settings', path: '/media/image?settings=1', label: 'Media Gen Settings', section: 'Create', aliases: ['media-settings', 'image-gen-settings', 'sd-settings', 'video-gen-settings'] },diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 19e1f675ba..97861b1d6e 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -34,7 +34,12 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// v1 = post-split. Migrations 035/036 introduced the pipeline collection// layout for issues and series.pipelineIssues: 1,- pipelineSeries: 1,+ // v2 = `series.arc.readerMap` added (Unified Story Builder). Additive ++ // gracefully-degrading, but version-gated so a not-yet-upgraded peer can't+ // round-trip a series through its readerMap-unaware sanitizer and LWW-strip+ // the field back onto a newer peer. Per-category gate → only series sync+ // pauses with old peers; issues/universes keep flowing.+ pipelineSeries: 2,mediaCollections: 1,// NOTE: `videoHistory` is intentionally NOT listed here. The version gate// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (thediff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.jsindex fd9d3bc49f..d32a2b20d4 100644--- a/server/lib/schemaVersions.test.js+++ b/server/lib/schemaVersions.test.js@@ -23,7 +23,8 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {it('declares pipeline collection layout versions', () => {expect(PORTOS_SCHEMA_VERSIONS.pipelineIssues).toBe(1);- expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(1);+ // pipelineSeries bumped to 2 when series.arc.readerMap was added.+ expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(2);});it('declares mediaCollections layout version', () => {@@ -37,7 +38,7 @@ describe('buildPortosMeta', () => {expect(meta.portosVersion).toMatch(/^\d+\.\d+\.\d+/);expect(meta.schemaVersions.universes).toBe(5);expect(meta.schemaVersions.pipelineIssues).toBe(1);- expect(meta.schemaVersions.pipelineSeries).toBe(1);+ expect(meta.schemaVersions.pipelineSeries).toBe(2);});it('overrides merge into schemaVersions', async () => {@@ -190,7 +191,7 @@ describe('scopeVersionDiff', () => {// Sender is ahead on mediaCollections only; a universe transfer scopes to// ['universes'] and stays compatible even though the union diff is not.const union = compareSchemaVersions(- { universes: 5, pipelineSeries: 1, pipelineIssues: 1, mediaCollections: 2 },+ { universes: 5, pipelineSeries: 2, pipelineIssues: 1, mediaCollections: 2 },PORTOS_SCHEMA_VERSIONS,);expect(union.compatible).toBe(false); // mediaCollections 2 > 1diff --git a/server/lib/storyArc.js b/server/lib/storyArc.jsindex e32835542a..b6125969a8 100644--- a/server/lib/storyArc.js+++ b/server/lib/storyArc.js@@ -39,6 +39,25 @@ export const ARC_LIMITS = Object.freeze({export const ARC_STATUSES = Object.freeze(['draft', 'verified']);export const SEASON_STATUSES = Object.freeze(['draft', 'verified', 'in-production', 'complete']);+// Reader map — the audience-facing companion to the protagonist arc. Where+// `arc.protagonistArc` + `arc.shape` describe the *character's* emotional+// fortune, the reader map describes what the *reader/viewer* experiences as+// they move through the content: questions planted (hooks), their resolutions+// (payoffs), the felt emotional beats, and the cliffhangers between issues.+// Lives at `series.arc.readerMap`; built on top of the Vonnegut `shape`.+export const READER_MAP_LIMITS = Object.freeze({+ LABEL_MAX: 200,+ NOTE_MAX: 1000,+ HOOKS_MAX: 60,+ PAYOFFS_MAX: 60,+ BEATS_MAX: 200,+ CLIFFHANGERS_MAX: 60,+ ARC_POSITION_MAX: 9999,+ ISSUE_BOUNDARY_MAX: 9999,+});+export const READER_MAP_BEAT_KINDS = Object.freeze(['hook', 'reveal', 'payoff', 'emotional', 'cliffhanger']);+export const READER_MAP_STATUSES = Object.freeze(['draft', 'verified']);+// Per-episode arc roles produced by the season-episodes generator and// persisted on the issue so downstream stages (idea-expansion in particular)// know whether they're writing a pilot vs. midpoint vs. finale episode.@@ -227,6 +246,92 @@ function cleanThemes(raw) {return out;}+// Reader-map entry ids are minted as `rm-<uuid>` so payoffs can reference the+// hook they resolve (`resolvesHookId`) and the client can key list rows.+const RM_ID_RE = /^rm-[a-zA-Z0-9-]+$/;+const ensureRmId = (raw) => (isStr(raw) && RM_ID_RE.test(raw) ? raw : `rm-${randomUUID()}`);++// Optional non-negative integer position. Absent / non-finite → null so the+// caller can distinguish "no position pinned" from position 0.+const optPosition = (raw, max) => (Number.isFinite(raw) ? Math.max(0, Math.min(max, Math.floor(raw))) : null);++// Clamp a beat's reader-intensity to [0,1]; non-finite → null (unspecified).+const clampIntensity = (raw) => (Number.isFinite(raw) ? Math.max(0, Math.min(1, raw)) : null);++function sanitizeReaderHook(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const label = trimTo(raw.label, READER_MAP_LIMITS.LABEL_MAX);+ const note = trimTo(raw.note, READER_MAP_LIMITS.NOTE_MAX);+ if (!label && !note) return null;+ return { id: ensureRmId(raw.id), label, atArcPosition: optPosition(raw.atArcPosition, READER_MAP_LIMITS.ARC_POSITION_MAX), note };+}++function sanitizeReaderPayoff(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const label = trimTo(raw.label, READER_MAP_LIMITS.LABEL_MAX);+ const note = trimTo(raw.note, READER_MAP_LIMITS.NOTE_MAX);+ if (!label && !note) return null;+ return {+ id: ensureRmId(raw.id),+ label,+ atArcPosition: optPosition(raw.atArcPosition, READER_MAP_LIMITS.ARC_POSITION_MAX),+ resolvesHookId: isStr(raw.resolvesHookId) && RM_ID_RE.test(raw.resolvesHookId) ? raw.resolvesHookId : null,+ note,+ };+}++function sanitizeReaderBeat(raw) {+ if (!raw || typeof raw !== 'object') return null;+ // Unknown `kind` drops the whole beat — a beat with no classified kind can't+ // be placed on the reader-map timeline meaningfully.+ const kind = READER_MAP_BEAT_KINDS.includes(raw.kind) ? raw.kind : null;+ if (!kind) return null;+ return {+ id: ensureRmId(raw.id),+ kind,+ atArcPosition: optPosition(raw.atArcPosition, READER_MAP_LIMITS.ARC_POSITION_MAX),+ intensity: clampIntensity(raw.intensity),+ note: trimTo(raw.note, READER_MAP_LIMITS.NOTE_MAX),+ };+}++function sanitizeReaderCliffhanger(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const note = trimTo(raw.note, READER_MAP_LIMITS.NOTE_MAX);+ const atIssueBoundary = optPosition(raw.atIssueBoundary, READER_MAP_LIMITS.ISSUE_BOUNDARY_MAX);+ if (!note && atIssueBoundary == null) return null;+ return { id: ensureRmId(raw.id), atIssueBoundary, note };+}++function cleanReaderMapList(rawList, fn, cap) {+ if (!Array.isArray(rawList)) return [];+ const out = [];+ for (const raw of rawList) {+ const v = fn(raw);+ if (v) out.push(v);+ if (out.length >= cap) break;+ }+ return out;+}++/**+ * Sanitize the optional `series.arc.readerMap` field. Returns `null` when the+ * map carries no identifying content (all four lists empty) so callers store+ * `null` to mean "no reader map yet" — mirroring `sanitizeArc`. Drops malformed+ * entries, caps each list, coerces ids to `rm-<uuid>`, clamps `intensity` to+ * [0,1], and drops beats with an unknown `kind`.+ */+export function sanitizeReaderMap(raw) {+ if (raw == null || typeof raw !== 'object') return null;+ const hooks = cleanReaderMapList(raw.hooks, sanitizeReaderHook, READER_MAP_LIMITS.HOOKS_MAX);+ const payoffs = cleanReaderMapList(raw.payoffs, sanitizeReaderPayoff, READER_MAP_LIMITS.PAYOFFS_MAX);+ const beats = cleanReaderMapList(raw.beats, sanitizeReaderBeat, READER_MAP_LIMITS.BEATS_MAX);+ const cliffhangers = cleanReaderMapList(raw.cliffhangers, sanitizeReaderCliffhanger, READER_MAP_LIMITS.CLIFFHANGERS_MAX);+ if (hooks.length === 0 && payoffs.length === 0 && beats.length === 0 && cliffhangers.length === 0) return null;+ const status = READER_MAP_STATUSES.includes(raw.status) ? raw.status : 'draft';+ return { hooks, payoffs, beats, cliffhangers, status };+}+/*** Sanitize the optional `series.arc` field. Returns `null` if the input is* empty (no identifying fields) — callers store `null` to mean "no arc yet."@@ -247,9 +352,12 @@ export function sanitizeArc(raw) {// `shape` counts as identifying content: it's an explicit narrative// decision the user made at create time and shouldn't silently vanish.const shape = isStr(raw.shape) && ARC_SHAPE_IDS.includes(raw.shape) ? raw.shape : null;- if (!logline && !summary && !protagonistArc && themes.length === 0 && !shape) return null;+ // The reader map is identifying content too — an arc that has only a reader+ // map (e.g. the Story Builder generated it before any logline) must survive.+ const readerMap = sanitizeReaderMap(raw.readerMap);+ if (!logline && !summary && !protagonistArc && themes.length === 0 && !shape && !readerMap) return null;const status = ARC_STATUSES.includes(raw.status) ? raw.status : 'draft';- return { logline, summary, protagonistArc, themes, shape, status };+ return { logline, summary, protagonistArc, themes, shape, readerMap, status };}/**diff --git a/server/lib/storyArc.test.js b/server/lib/storyArc.test.jsindex a3a9afc116..5fc78000c9 100644--- a/server/lib/storyArc.test.js+++ b/server/lib/storyArc.test.js@@ -15,9 +15,12 @@ const {sanitizeSeason,sanitizeSeasonList,buildSeason,+ sanitizeReaderMap,ARC_LIMITS,ARC_SHAPES,ARC_SHAPE_IDS,+ READER_MAP_LIMITS,+ READER_MAP_BEAT_KINDS,getArcShape,renderArcShapeGuidance,describeArcShapePositionForSeason,@@ -45,6 +48,7 @@ describe('storyArc — sanitizeArc', () => {protagonistArc: '',themes: [],shape: null,+ readerMap: null,status: 'draft',});});@@ -84,6 +88,77 @@ describe('storyArc — sanitizeArc', () => {const many = Array.from({ length: ARC_LIMITS.THEMES_PER_ARC_MAX + 5 }, (_, i) => `t${i}`);expect(sanitizeArc({ logline: 'x', themes: many }).themes).toHaveLength(ARC_LIMITS.THEMES_PER_ARC_MAX);});++ it('includes readerMap (null when absent) and survives an arc with only a reader map', () => {+ expect(sanitizeArc({ logline: 'x' }).readerMap).toBe(null);+ const arc = sanitizeArc({ readerMap: { hooks: [{ label: 'Who is the masked figure?' }] } });+ expect(arc).not.toBe(null);+ expect(arc.logline).toBe('');+ expect(arc.readerMap.hooks).toHaveLength(1);+ // An empty reader map alone is NOT identifying content.+ expect(sanitizeArc({ readerMap: { hooks: [], payoffs: [], beats: [], cliffhangers: [] } })).toBe(null);+ });+});++describe('storyArc — sanitizeReaderMap', () => {+ it('returns null for non-objects and empty maps', () => {+ expect(sanitizeReaderMap(null)).toBe(null);+ expect(sanitizeReaderMap('x')).toBe(null);+ expect(sanitizeReaderMap({})).toBe(null);+ expect(sanitizeReaderMap({ hooks: [], payoffs: [], beats: [], cliffhangers: [] })).toBe(null);+ });++ it('round-trips hooks/payoffs/beats/cliffhangers with minted ids', () => {+ const map = sanitizeReaderMap({+ hooks: [{ label: 'Why did the city fall?', atArcPosition: 0, note: 'opening mystery' }],+ payoffs: [{ label: 'The fall was an inside job', atArcPosition: 5 }],+ beats: [{ kind: 'reveal', atArcPosition: 3, intensity: 0.8, note: 'midpoint twist' }],+ cliffhangers: [{ atIssueBoundary: 1, note: 'the door opens' }],+ });+ expect(map.status).toBe('draft');+ expect(map.hooks[0].id).toMatch(/^rm-/);+ expect(map.payoffs[0].atArcPosition).toBe(5);+ expect(map.payoffs[0].resolvesHookId).toBe(null);+ expect(map.beats[0].kind).toBe('reveal');+ expect(map.cliffhangers[0].atIssueBoundary).toBe(1);+ });++ it('drops beats with an unknown kind and clamps intensity to [0,1]', () => {+ const map = sanitizeReaderMap({+ beats: [+ { kind: 'bogus', note: 'dropped' },+ { kind: 'emotional', intensity: 5, note: 'over' },+ { kind: 'hook', intensity: -2, note: 'under' },+ { kind: 'payoff', note: 'no intensity' },+ ],+ });+ expect(map.beats).toHaveLength(3);+ expect(map.beats.find((b) => b.note === 'over').intensity).toBe(1);+ expect(map.beats.find((b) => b.note === 'under').intensity).toBe(0);+ expect(map.beats.find((b) => b.note === 'no intensity').intensity).toBe(null);+ });++ it('preserves valid status and falls back to draft otherwise', () => {+ expect(sanitizeReaderMap({ hooks: [{ label: 'x' }], status: 'verified' }).status).toBe('verified');+ expect(sanitizeReaderMap({ hooks: [{ label: 'x' }], status: 'bogus' }).status).toBe('draft');+ });++ it('caps each list at its limit', () => {+ const manyHooks = Array.from({ length: READER_MAP_LIMITS.HOOKS_MAX + 10 }, (_, i) => ({ label: `h${i}` }));+ expect(sanitizeReaderMap({ hooks: manyHooks }).hooks).toHaveLength(READER_MAP_LIMITS.HOOKS_MAX);+ });++ it('keeps resolvesHookId only when it is an rm- id', () => {+ const ok = sanitizeReaderMap({ payoffs: [{ label: 'p', resolvesHookId: 'rm-abc' }] });+ expect(ok.payoffs[0].resolvesHookId).toBe('rm-abc');+ const bad = sanitizeReaderMap({ payoffs: [{ label: 'p', resolvesHookId: 'hook-1' }] });+ expect(bad.payoffs[0].resolvesHookId).toBe(null);+ });++ it('exposes a non-empty beat-kind vocabulary', () => {+ expect(READER_MAP_BEAT_KINDS).toContain('hook');+ expect(READER_MAP_BEAT_KINDS).toContain('cliffhanger');+ });});describe('storyArc — sanitizeSeason', () => {diff --git a/server/lib/storyBuilderIntegrity.js b/server/lib/storyBuilderIntegrity.jsnew file mode 100644index 0000000000..268dea589a--- /dev/null+++ b/server/lib/storyBuilderIntegrity.js@@ -0,0 +1,63 @@+/**+ * Unified Story Builder — integrity / staleness hashing.+ *+ * Pure, side-effect-free. When a Story Builder step is locked we snapshot a+ * hash of its *upstream inputs* (the whitelisted universe/series fields the+ * step's content was derived from). If those inputs later change — because the+ * user unlocked an earlier step and revised it — the locked downstream step is+ * "stale" and must be re-reviewed before the wizard advances. Content is never+ * destroyed; only the lock's trust is invalidated.+ *+ * The comparison is computed on read (in the route handler), never persisted:+ * the stored `upstreamHash` is frozen at lock time, and the current hash is+ * recomputed from live records each time the session is fetched.+ */++import { createHash } from 'crypto';++// Canonical, sorted-key projection so key-order churn (or a re-serialized+// record) doesn't change the hash. Recurses arrays + plain objects; leaves+// primitives untouched. Mirrors the canonical-stringify intent of+// `contentHashForRecord` in conflictJournal.js.+function canonical(value) {+ if (Array.isArray(value)) return value.map(canonical);+ if (value && typeof value === 'object') {+ return Object.keys(value)+ .sort()+ .reduce((acc, k) => {+ acc[k] = canonical(value[k]);+ return acc;+ }, {});+ }+ return value;+}++/**+ * Hash a step's upstream inputs. `stepId` is folded into the payload so two+ * steps that happen to share identical inputs still get distinct hashes (the+ * comparison is per-step anyway, but this keeps the helper collision-proof).+ * Only ever pass whitelisted SEMANTIC fields here — never `updatedAt` or other+ * churn, or every save would false-positive a staleness flag.+ */+export function hashUpstream(stepId, inputs) {+ const payload = JSON.stringify({ stepId, inputs: canonical(inputs ?? null) });+ return createHash('sha256').update(payload).digest('hex');+}++/**+ * Given a session and a map of current upstream hashes (`{ [stepId]: hash }`),+ * return the ids of locked steps whose frozen `upstreamHash` no longer matches.+ * Unlocked steps are never flagged. A step with no current hash available is+ * skipped (we can't compare what we couldn't compute).+ */+export function computeStaleSteps(session, currentHashes = {}) {+ const steps = session?.steps || {};+ const stale = [];+ for (const [stepId, state] of Object.entries(steps)) {+ if (!state || state.locked !== true) continue;+ const current = currentHashes[stepId];+ if (current == null) continue;+ if (state.upstreamHash !== current) stale.push(stepId);+ }+ return stale;+}diff --git a/server/lib/storyBuilderIntegrity.test.js b/server/lib/storyBuilderIntegrity.test.jsnew file mode 100644index 0000000000..e84c6aa911--- /dev/null+++ b/server/lib/storyBuilderIntegrity.test.js@@ -0,0 +1,75 @@+import { describe, it, expect } from 'vitest';+import { hashUpstream, computeStaleSteps } from './storyBuilderIntegrity.js';++describe('storyBuilderIntegrity — hashUpstream', () => {+ it('is deterministic for the same inputs', () => {+ const a = hashUpstream('plotArc', { logline: 'x', themes: ['a', 'b'] });+ const b = hashUpstream('plotArc', { logline: 'x', themes: ['a', 'b'] });+ expect(a).toBe(b);+ expect(a).toMatch(/^[0-9a-f]{64}$/);+ });++ it('is independent of object key order', () => {+ const a = hashUpstream('s', { logline: 'x', summary: 'y', nested: { p: 1, q: 2 } });+ const b = hashUpstream('s', { nested: { q: 2, p: 1 }, summary: 'y', logline: 'x' });+ expect(a).toBe(b);+ });++ it('changes when a semantic field changes', () => {+ const a = hashUpstream('s', { logline: 'x' });+ const b = hashUpstream('s', { logline: 'y' });+ expect(a).not.toBe(b);+ });++ it('is sensitive to array order (order is semantic for beats/seasons)', () => {+ const a = hashUpstream('s', { beats: [1, 2, 3] });+ const b = hashUpstream('s', { beats: [3, 2, 1] });+ expect(a).not.toBe(b);+ });++ it('namespaces by stepId so identical inputs for different steps differ', () => {+ expect(hashUpstream('a', { x: 1 })).not.toBe(hashUpstream('b', { x: 1 }));+ });++ it('handles null/undefined inputs without throwing', () => {+ expect(hashUpstream('s', null)).toBe(hashUpstream('s', undefined));+ });+});++describe('storyBuilderIntegrity — computeStaleSteps', () => {+ const session = {+ steps: {+ idea: { locked: true, upstreamHash: 'h-idea' },+ universeAesthetic: { locked: true, upstreamHash: 'h-univ' },+ plotArc: { locked: false, upstreamHash: 'h-arc' },+ readerMap: { locked: true, upstreamHash: 'h-reader' },+ },+ };++ it('flags only locked steps whose hash drifted', () => {+ const stale = computeStaleSteps(session, {+ idea: 'h-idea', // unchanged+ universeAesthetic: 'h-univ-CHANGED', // drifted → stale+ plotArc: 'h-arc-CHANGED', // changed but NOT locked → ignored+ readerMap: 'h-reader-CHANGED', // drifted → stale+ });+ expect(stale.sort()).toEqual(['readerMap', 'universeAesthetic']);+ });++ it('never flags unlocked steps even when drifted', () => {+ const stale = computeStaleSteps(session, { plotArc: 'totally-different' });+ expect(stale).not.toContain('plotArc');+ });++ it('skips steps with no current hash available', () => {+ const stale = computeStaleSteps(session, { idea: 'h-idea' });+ // universeAesthetic + readerMap have no current hash → not flagged+ expect(stale).toEqual([]);+ });++ it('returns empty for an empty/missing session', () => {+ expect(computeStaleSteps(null, {})).toEqual([]);+ expect(computeStaleSteps({}, {})).toEqual([]);+ expect(computeStaleSteps({ steps: {} }, { a: 'b' })).toEqual([]);+ });+});diff --git a/server/lib/storyBuilderSteps.js b/server/lib/storyBuilderSteps.jsnew file mode 100644index 0000000000..87f1607ec0--- /dev/null+++ b/server/lib/storyBuilderSteps.js@@ -0,0 +1,59 @@+/**+ * Unified Story Builder — shared step definitions.+ *+ * Single source of truth for the linear wizard's ordered steps, consumed by+ * both the server (state machine + gating in `services/storyBuilder.js`) and+ * the client (stepper UI, echoed via the API). The Story Builder is a thin+ * *conductor* over the existing universe / series / issue records — these+ * steps describe the review-and-lock gates, not new content models.+ *+ * Ordering IS the dependency graph: each step's "upstream" is every step+ * before it. Unlocking step K flags every locked step after K as stale+ * (see `storyBuilderIntegrity.js`).+ */++export const STEP_STATUSES = Object.freeze(['pending', 'in-progress', 'ready', 'locked']);++export const STEPS = Object.freeze([+ {+ id: 'idea',+ label: 'Idea',+ description: 'Name the universe and capture a starter idea — type a seed or import a finished work.',+ },+ {+ id: 'universeAesthetic',+ label: 'Universe Aesthetic',+ description: 'Lock the world’s look and feel: logline, premise, style notes, and visual influences.',+ },+ {+ id: 'plotArc',+ label: 'Plot Arc',+ description: 'Expand the idea into a multi-season arc and pick its emotional shape.',+ },+ {+ id: 'readerMap',+ label: 'Reader Map',+ description: 'Plan the reader’s experience — hooks, payoffs, emotional beats, and cliffhangers.',+ },+ {+ id: 'characters',+ label: 'Characters',+ description: 'Review and lock the cast that recurs across the series.',+ },+ {+ id: 'issues',+ label: 'Issues',+ description: 'Break the arc into issues/episodes and complete them one at a time.',+ },+ {+ id: 'production',+ label: 'Production',+ description: 'Render each completed issue to comic pages and video.',+ },+]);++export const STEP_IDS = Object.freeze(STEPS.map((s) => s.id));++export const isValidStepId = (id) => STEP_IDS.includes(id);++export const stepIndex = (id) => STEP_IDS.indexOf(id);diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 19a9585a03..9fbe570d79 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1769,3 +1769,46 @@ export const issuesListQuerySchema = z.object({offset: z.preprocess((v) => (v === undefined ? 0 : Number(v)), z.number().int().min(0)).default(0),limit: z.preprocess((v) => (v === undefined ? 1000 : Number(v)), z.number().int().min(1).max(1000)).default(1000),});++// =============================================================================+// UNIFIED STORY BUILDER SCHEMAS+// =============================================================================++const storyProviderField = z.preprocess(emptyToUndefined, z.string().trim().max(120).optional());+const storyModelField = z.preprocess(emptyToUndefined, z.string().trim().max(200).optional());++export const storySessionCreateSchema = z.object({+ title: z.string().trim().min(1).max(200),+ intakeMode: z.enum(['seed', 'import']).optional().default('seed'),+ seedIdea: z.string().trim().max(4000).optional().default(''),+ // Import mode supplies pre-created ids; seed mode mints shells server-side.+ universeId: z.preprocess(emptyToUndefined, z.string().trim().max(64).optional()),+ seriesId: z.preprocess(emptyToUndefined, z.string().trim().max(64).optional()),+}).strict();++export const storySessionUpdateSchema = z.object({+ title: z.string().trim().min(1).max(200).optional(),+ seedIdea: z.string().trim().max(4000).optional(),+ currentStep: z.string().trim().max(40).optional(),+ llm: z.object({+ provider: z.string().trim().max(80).nullable().optional(),+ model: z.string().trim().max(200).nullable().optional(),+ }).optional(),+}).strict();++export const storyStepGenerateSchema = z.object({+ providerId: storyProviderField,+ model: storyModelField,+}).strict();++export const storyStepRefineSchema = z.object({+ feedback: z.string().trim().max(4000).optional().default(''),+ // For per-entry refine (e.g. a single character on the characters step).+ entryId: z.preprocess(emptyToUndefined, z.string().trim().max(64).optional()),+ providerId: storyProviderField,+ model: storyModelField,+}).strict();++export const storyIssueLockSchema = z.object({+ locked: z.boolean(),+}).strict();diff --git a/server/routes/storyBuilder.js b/server/routes/storyBuilder.jsnew file mode 100644index 0000000000..a067769481--- /dev/null+++ b/server/routes/storyBuilder.js@@ -0,0 +1,121 @@+import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import {+ validateRequest,+ storySessionCreateSchema,+ storySessionUpdateSchema,+ storyStepGenerateSchema,+ storyStepRefineSchema,+ storyIssueLockSchema,+} from '../lib/validation.js';+import { STEPS, isValidStepId } from '../lib/storyBuilderSteps.js';+import {+ listStorySessions,+ getStorySessionView,+ createStorySession,+ updateStorySession,+ deleteStorySession,+ lockStep,+ unlockStep,+ setCurrentStep,+ setIssueLock,+ generateStep,+ refineStep,+ ERR_NOT_FOUND,+ ERR_VALIDATION,+} from '../services/storyBuilder.js';++const router = Router();++const SERVICE_ERROR_STATUS = {+ [ERR_NOT_FOUND]: 404,+ [ERR_VALIDATION]: 400,+};+const mapServiceError = (err) => {+ const status = SERVICE_ERROR_STATUS[err?.code];+ if (status) return new ServerError(err.message, { status, code: err.code });+ return err;+};++// Echo the step manifest so the client stepper doesn't hardcode the order /+// labels (single source of truth is server/lib/storyBuilderSteps.js).+router.get('/steps', (_req, res) => {+ res.json({ steps: STEPS });+});++router.get('/', asyncHandler(async (_req, res) => {+ res.json(await listStorySessions());+}));++router.post('/', asyncHandler(async (req, res) => {+ const input = validateRequest(storySessionCreateSchema, req.body || {});+ const created = await createStorySession(input).catch((err) => { throw mapServiceError(err); });+ res.status(201).json(created);+}));++router.get('/:id', asyncHandler(async (req, res) => {+ const view = await getStorySessionView(req.params.id).catch((err) => { throw mapServiceError(err); });+ // Flatten the session with the computed (non-persisted) staleSteps array.+ res.json({ ...view.session, staleSteps: view.staleSteps });+}));++router.patch('/:id', asyncHandler(async (req, res) => {+ const input = validateRequest(storySessionUpdateSchema, req.body || {});+ const updated = await updateStorySession(req.params.id, input).catch((err) => { throw mapServiceError(err); });+ res.json(updated);+}));++router.delete('/:id', asyncHandler(async (req, res) => {+ const result = await deleteStorySession(req.params.id).catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++// ── Step state machine ─────────────────────────────────────────────────────++function assertStep(stepId) {+ if (!isValidStepId(stepId)) {+ throw new ServerError(`Unknown step: ${stepId}`, { status: 400, code: ERR_VALIDATION });+ }+}++router.post('/:id/current-step/:stepId', asyncHandler(async (req, res) => {+ assertStep(req.params.stepId);+ const updated = await setCurrentStep(req.params.id, req.params.stepId).catch((err) => { throw mapServiceError(err); });+ res.json(updated);+}));++router.post('/:id/steps/:stepId/lock', asyncHandler(async (req, res) => {+ assertStep(req.params.stepId);+ const updated = await lockStep(req.params.id, req.params.stepId).catch((err) => { throw mapServiceError(err); });+ res.json(updated);+}));++router.post('/:id/steps/:stepId/unlock', asyncHandler(async (req, res) => {+ assertStep(req.params.stepId);+ const updated = await unlockStep(req.params.id, req.params.stepId).catch((err) => { throw mapServiceError(err); });+ res.json(updated);+}));++router.post('/:id/steps/:stepId/generate', asyncHandler(async (req, res) => {+ assertStep(req.params.stepId);+ const input = validateRequest(storyStepGenerateSchema, req.body || {});+ const result = await generateStep(req.params.id, req.params.stepId, input).catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++router.post('/:id/steps/:stepId/refine', asyncHandler(async (req, res) => {+ assertStep(req.params.stepId);+ const input = validateRequest(storyStepRefineSchema, req.body || {});+ const result = await refineStep(req.params.id, req.params.stepId, input).catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++// ── Per-issue locks (issues step loop) ───────────────────────────────────────++router.post('/:id/issues/:issueId/lock', asyncHandler(async (req, res) => {+ const { locked } = validateRequest(storyIssueLockSchema, req.body || {});+ const updated = await setIssueLock(req.params.id, req.params.issueId, locked).catch((err) => { throw mapServiceError(err); });+ res.json(updated);+}));++export default router;diff --git a/server/routes/storyBuilder.test.js b/server/routes/storyBuilder.test.jsnew file mode 100644index 0000000000..a96cc55a9c--- /dev/null+++ b/server/routes/storyBuilder.test.js@@ -0,0 +1,122 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++// Stub the conductor service — this test verifies routing, validation, and+// service dispatch, not the service logic (covered by storyBuilder.test.js).+const svc = {+ listStorySessions: vi.fn(async () => [{ id: 'stb-1' }]),+ getStorySessionView: vi.fn(async () => ({ session: { id: 'stb-1', title: 'X' }, staleSteps: ['readerMap'] })),+ createStorySession: vi.fn(async (input) => ({ id: 'stb-new', ...input })),+ updateStorySession: vi.fn(async (id, patch) => ({ id, ...patch })),+ deleteStorySession: vi.fn(async (id) => ({ id })),+ lockStep: vi.fn(async (id, stepId) => ({ id, locked: stepId })),+ unlockStep: vi.fn(async (id, stepId) => ({ id, unlocked: stepId })),+ setCurrentStep: vi.fn(async (id, stepId) => ({ id, currentStep: stepId })),+ setIssueLock: vi.fn(async (id, issueId, locked) => ({ id, issueId, locked })),+ generateStep: vi.fn(async () => ({ result: { ok: true } })),+ refineStep: vi.fn(async () => ({ result: { ok: true }, changes: ['c'], rationale: 'r' })),+ getStorySession: vi.fn(async () => ({ id: 'stb-1' })),+ ERR_NOT_FOUND: 'STORY_BUILDER_NOT_FOUND',+ ERR_VALIDATION: 'STORY_BUILDER_VALIDATION',+};+vi.mock('../services/storyBuilder.js', () => svc);++const { default: storyBuilderRoutes } = await import('./storyBuilder.js');++const makeApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/story-builder', storyBuilderRoutes);+ app.use(errorMiddleware);+ return app;+};++beforeEach(() => vi.clearAllMocks());++describe('GET /api/story-builder/steps', () => {+ it('returns the ordered step manifest', async () => {+ const res = await request(makeApp()).get('/api/story-builder/steps');+ expect(res.status).toBe(200);+ expect(Array.isArray(res.body.steps)).toBe(true);+ expect(res.body.steps[0].id).toBe('idea');+ expect(res.body.steps.find((s) => s.id === 'readerMap')).toBeTruthy();+ });+});++describe('POST /api/story-builder', () => {+ it('creates a session (201) and dispatches to the service', async () => {+ const res = await request(makeApp()).post('/api/story-builder').send({ title: 'Salt Run', seedIdea: 'seed' });+ expect(res.status).toBe(201);+ expect(svc.createStorySession).toHaveBeenCalledWith(expect.objectContaining({ title: 'Salt Run' }));+ });++ it('rejects a missing title with 400', async () => {+ const res = await request(makeApp()).post('/api/story-builder').send({ seedIdea: 'x' });+ expect(res.status).toBe(400);+ expect(svc.createStorySession).not.toHaveBeenCalled();+ });++ it('rejects unknown fields (strict schema)', async () => {+ const res = await request(makeApp()).post('/api/story-builder').send({ title: 'X', bogus: 1 });+ expect(res.status).toBe(400);+ });+});++describe('GET /api/story-builder/:id', () => {+ it('flattens the session with the computed staleSteps', async () => {+ const res = await request(makeApp()).get('/api/story-builder/stb-1');+ expect(res.status).toBe(200);+ expect(res.body.id).toBe('stb-1');+ expect(res.body.staleSteps).toEqual(['readerMap']);+ });++ it('maps a service NOT_FOUND to 404', async () => {+ svc.getStorySessionView.mockRejectedValueOnce(Object.assign(new Error('nope'), { code: svc.ERR_NOT_FOUND }));+ const res = await request(makeApp()).get('/api/story-builder/stb-x');+ expect(res.status).toBe(404);+ });+});++describe('step state machine routes', () => {+ it('locks a valid step', async () => {+ const res = await request(makeApp()).post('/api/story-builder/stb-1/steps/plotArc/lock').send({});+ expect(res.status).toBe(200);+ expect(svc.lockStep).toHaveBeenCalledWith('stb-1', 'plotArc');+ });++ it('rejects an unknown step id with 400 before touching the service', async () => {+ const res = await request(makeApp()).post('/api/story-builder/stb-1/steps/bogus/lock').send({});+ expect(res.status).toBe(400);+ expect(svc.lockStep).not.toHaveBeenCalled();+ });++ it('advances the current step', async () => {+ const res = await request(makeApp()).post('/api/story-builder/stb-1/current-step/universeAesthetic').send({});+ expect(res.status).toBe(200);+ expect(svc.setCurrentStep).toHaveBeenCalledWith('stb-1', 'universeAesthetic');+ });++ it('generates and refines a step', async () => {+ const g = await request(makeApp()).post('/api/story-builder/stb-1/steps/readerMap/generate').send({});+ expect(g.status).toBe(200);+ expect(svc.generateStep).toHaveBeenCalledWith('stb-1', 'readerMap', expect.any(Object));+ const r = await request(makeApp()).post('/api/story-builder/stb-1/steps/readerMap/refine').send({ feedback: 'tighter' });+ expect(r.status).toBe(200);+ expect(r.body.changes).toEqual(['c']);+ });+});++describe('per-issue lock route', () => {+ it('locks an issue', async () => {+ const res = await request(makeApp()).post('/api/story-builder/stb-1/issues/iss-1/lock').send({ locked: true });+ expect(res.status).toBe(200);+ expect(svc.setIssueLock).toHaveBeenCalledWith('stb-1', 'iss-1', true);+ });++ it('requires the locked boolean', async () => {+ const res = await request(makeApp()).post('/api/story-builder/stb-1/issues/iss-1/lock').send({});+ expect(res.status).toBe(400);+ });+});diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex 11bdbf3d4a..bccdc8bd68 100644--- a/server/services/dataSync.pipelineUniverse.test.js+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -882,12 +882,12 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {const result = await dataSync.applyRemote('pipeline', {series: [{ id: 'ser-1', name: 'Foundry', updatedAt: '2026-05-17T11:00:00Z' }],issues: [],- }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 2, pipelineIssues: 1, mediaCollections: 1 } } });+ }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 3, pipelineIssues: 1, mediaCollections: 1 } } });expect(result.applied).toBe(false);expect(result.blockedBySchema).toBeDefined();// The reported gap is scoped to the relevant category — NOT mis-attributed.expect(result.blockedBySchema.ahead).toEqual([- { category: 'pipelineSeries', senderV: 2, receiverV: 1 },+ { category: 'pipelineSeries', senderV: 3, receiverV: 2 },]);expect(readSeriesState()).toEqual([]); // nothing written});diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.jsindex 6578e445bf..f70c1870a2 100644--- a/server/services/pipeline/arcPlanner.js+++ b/server/services/pipeline/arcPlanner.js@@ -31,11 +31,14 @@ import {sanitizeSeasonList,sanitizeSeason,buildSeason,+ sanitizeReaderMap,ARC_ROLES as ARC_ROLE_LIST,ARC_SHAPE_IDS,+ READER_MAP_BEAT_KINDS,renderArcShapeGuidance,renderArcShapePositionSummary,} from '../../lib/storyArc.js';+import { runPromptRefineRaw } from './refineHelpers.js';import { recommendStructure, describeStructure } from '../../lib/seasonStructure.js';import { LENGTH_PROFILE_NAMES, DEFAULT_LENGTH_PROFILE } from '../../lib/issueLength.js';import { getUniverse } from '../universeBuilder.js';@@ -270,6 +273,10 @@ export async function generateArcOverview(seriesId, options = {}) {themes: content?.themes,protagonistArc: content?.protagonistArc || '',shape: content?.shape ?? series.arc?.shape ?? null,+ // The arc-overview prompt doesn't author the reader map — preserve any+ // existing one (like `shape`) so regenerating the arc never silently wipes+ // a reader map the user already built on the next step.+ readerMap: series.arc?.readerMap ?? null,status: 'draft',});const seasons = shapeSeasonOutlines(content?.seasonOutlines);@@ -283,6 +290,107 @@ export async function generateArcOverview(seriesId, options = {}) {};}+// Reader-map context: the protagonist arc + the Vonnegut shape backbone + the+// planned volume boundaries (so the LLM can place cliffhangers at issue gaps).+// Mirrors buildArcOverviewContext's world+arc projection.+async function buildReaderMapContext(series, preloadedWorld) {+ const arc = series.arc || {};+ const world = await resolveWorldContext(series, preloadedWorld);+ const seasons = Array.isArray(series.seasons) ? series.seasons : [];+ const issueBoundaries = seasons.length === 0+ ? '(no volumes planned yet — pace hooks/payoffs across a single-volume arc)'+ : seasons+ .slice()+ .sort((a, b) => (a.number || 0) - (b.number || 0))+ .map((s) => `Volume ${s.number} — ${s.title || 'Untitled'} (~${s.episodeCountTarget || '?'} issues): ${s.logline || '(no logline)'}`)+ .join('\n');+ return {+ series: { name: series.name, logline: series.logline, premise: series.premise },+ ...world,+ arc: {+ logline: arc.logline || '',+ summary: arc.summary || '',+ protagonistArc: arc.protagonistArc || '',+ themesCsv: Array.isArray(arc.themes) ? arc.themes.join(', ') : '',+ shape: arc.shape || '',+ },+ shapeGuidance: renderArcShapeGuidance(arc.shape) || SHAPE_GUIDANCE_NONE,+ issueBoundaries,+ beatKindsCsv: READER_MAP_BEAT_KINDS.join(', '),+ existingReaderMapJson: arc.readerMap ? JSON.stringify(arc.readerMap, null, 2) : '(none yet)',+ };+}++// The reader map is authored AFTER the plot arc is approved, so a frozen arc+// (`locked.arc`, which protects the core arc fields from the arc-overview+// regenerator) must NOT block reader-map work — only the reader-map field lock+// (`locked.arcFields.readerMap`) does. The locked arc is read as INPUT here.+function assertReaderMapUnlocked(series) {+ if (series.locked?.arcFields?.readerMap === true) {+ throw makeErr('Reader map is locked — unlock it before regenerating', ERR_VALIDATION);+ }+}++/**+ * Generate the reader map (audience experience roadmap) from the series arc.+ * Extraction-only like generateArcOverview — returns the sanitized readerMap;+ * the caller persists it by merging into `series.arc` (preserving the other+ * arc fields) via updateSeries.+ */+export async function generateReaderMap(seriesId, options = {}) {+ const series = await getSeries(seriesId);+ assertReaderMapUnlocked(series);+ const ctx = await buildReaderMapContext(series);+ const { content, runId, providerId, model } = await runStagedLLM(+ 'story-builder-reader-map',+ ctx,+ {+ providerOverride: options.providerOverride,+ modelOverride: options.modelOverride,+ returnsJson: true,+ source: 'story-builder-reader-map',+ },+ );+ const readerMap = sanitizeReaderMap({+ hooks: content?.hooks,+ payoffs: content?.payoffs,+ beats: content?.beats,+ cliffhangers: content?.cliffhangers,+ status: 'draft',+ });+ return { readerMap, raw: content, runId, providerId, model };+}++/**+ * Refine an existing reader map against free-text feedback (the same AI-+ * feedback affordance as image-prompt refine). Returns the regenerated+ * readerMap plus `changes` (a short bullet list) and `rationale`.+ */+export async function refineReaderMap(seriesId, feedback, options = {}) {+ const series = await getSeries(seriesId);+ assertReaderMapUnlocked(series);+ const arc = series.arc || {};+ const { content, rationale, runId, providerId, model } = await runPromptRefineRaw({+ templateName: 'story-builder-reader-map-refine',+ variables: {+ currentReaderMapJson: arc.readerMap ? JSON.stringify(arc.readerMap, null, 2) : '{}',+ feedback: typeof feedback === 'string' ? feedback.trim().slice(0, 4000) : '',+ arcSummary: arc.summary || '',+ protagonistArc: arc.protagonistArc || '',+ shapeGuidance: renderArcShapeGuidance(arc.shape) || SHAPE_GUIDANCE_NONE,+ beatKindsCsv: READER_MAP_BEAT_KINDS.join(', '),+ },+ options,+ source: 'story-builder-reader-map-refine',+ logTag: `Story Builder reader-map refine series=${seriesId.slice(0, 8)}`,+ });+ const readerMap = sanitizeReaderMap({ ...content, status: 'draft' });+ const changes = Array.isArray(content.changes)+ ? content.changes.map((c) => String(c).slice(0, 240)).filter(Boolean).slice(0, 12)+ : [];+ return { readerMap, changes, rationale, runId, providerId, model };+}+/*** Build the context for one season's episode breakdown. `priorSeasonsContext`* gives the LLM granular per-episode continuity — without it the verifier anddiff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.jsindex e4ebf8898f..bc544ac9ed 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -1340,3 +1340,84 @@ describe('arcPlanner — generateComicCoverConcepts', () => {expect(stored.stages.comicPages.backCover.script).toBe('LLM back');});});++describe('arcPlanner — generateReaderMap', () => {+ beforeEach(() => {+ fileStore.clear();+ uuidCounter = 0;+ stageRunnerSpy = undefined;+ });++ it('runs the reader-map prompt and returns a sanitized readerMap', async () => {+ const s = await setupSeries({ arc: { logline: 'rise', summary: 'spine', shape: 'man-in-hole' } });+ stageRunnerSpy = vi.fn(async () => ({+ content: {+ hooks: [{ label: 'Who silenced the foundry?', atArcPosition: 0, note: 'opening' }],+ payoffs: [{ label: 'It was the guild', atArcPosition: 6 }],+ beats: [{ kind: 'bogus', note: 'dropped' }, { kind: 'reveal', atArcPosition: 3, intensity: 9 }],+ cliffhangers: [{ atIssueBoundary: 1, note: 'door opens' }],+ },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ const out = await planner.generateReaderMap(s.id);+ expect(stageRunnerSpy).toHaveBeenCalledWith('story-builder-reader-map', expect.any(Object), expect.objectContaining({ returnsJson: true }));+ expect(out.readerMap.hooks).toHaveLength(1);+ expect(out.readerMap.payoffs[0].atArcPosition).toBe(6);+ // bogus-kind beat dropped, intensity clamped+ expect(out.readerMap.beats).toHaveLength(1);+ expect(out.readerMap.beats[0].intensity).toBe(1);+ expect(out.readerMap.cliffhangers[0].note).toBe('door opens');+ });++ it('is NOT blocked by a locked arc (reader map is authored after the arc is approved)', async () => {+ const s = await setupSeries({ locked: { arc: true }, arc: { logline: 'x', summary: 'y' } });+ stageRunnerSpy = vi.fn(async () => ({+ content: { hooks: [{ label: 'h' }], payoffs: [], beats: [], cliffhangers: [] },+ runId: 'r', providerId: 'p', model: 'm',+ }));+ const out = await planner.generateReaderMap(s.id);+ expect(out.readerMap.hooks).toHaveLength(1);+ });++ it('throws only when the readerMap field itself is locked', async () => {+ const s = await setupSeries({ locked: { arcFields: { readerMap: true } } });+ await expect(planner.generateReaderMap(s.id)).rejects.toMatchObject({ code: 'PIPELINE_ARC_VALIDATION' });+ });+});++describe('arcPlanner — refineReaderMap', () => {+ beforeEach(() => {+ fileStore.clear();+ uuidCounter = 0;+ stageRunnerSpy = undefined;+ });++ it('returns the revised readerMap plus changes and rationale', async () => {+ const s = await setupSeries({+ arc: { logline: 'rise', summary: 'spine', readerMap: { hooks: [{ label: 'old hook' }] } },+ });+ stageRunnerSpy = vi.fn(async () => ({+ content: {+ hooks: [{ label: 'sharper hook', atArcPosition: 0 }],+ payoffs: [],+ beats: [{ kind: 'emotional', intensity: 0.5 }],+ cliffhangers: [],+ changes: ['rewrote the opening hook'],+ rationale: 'tightened the front',+ },+ runId: 'r', providerId: 'p', model: 'm',+ }));++ const out = await planner.refineReaderMap(s.id, 'make the first hook sharper');+ expect(stageRunnerSpy).toHaveBeenCalledWith('story-builder-reader-map-refine', expect.any(Object), expect.objectContaining({ returnsJson: true }));+ expect(out.readerMap.hooks[0].label).toBe('sharper hook');+ expect(out.changes).toEqual(['rewrote the opening hook']);+ expect(out.rationale).toBe('tightened the front');+ });++ it('throws when the readerMap field is locked', async () => {+ const s = await setupSeries({ locked: { arcFields: { readerMap: true } } });+ await expect(planner.refineReaderMap(s.id, 'x')).rejects.toMatchObject({ code: 'PIPELINE_ARC_VALIDATION' });+ });+});diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex 062be7e3a6..db4c194743 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -87,7 +87,7 @@ export const LOCKABLE_STAGES = Object.freeze(['arc']);// while preserving locked ones verbatim. Sibling to the binary `locked.arc`// (which freezes everything); the two stack — `locked.arc: true` always wins.export const ARC_LOCKABLE_FIELDS = Object.freeze([- 'logline', 'summary', 'protagonistArc', 'themes', 'shape',+ 'logline', 'summary', 'protagonistArc', 'themes', 'shape', 'readerMap',]);const sanitizeSeriesLocked = (raw = {}) => {diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.jsindex c7f5a18696..c07402ca6f 100644--- a/server/services/pipeline/series.test.js+++ b/server/services/pipeline/series.test.js@@ -461,5 +461,31 @@ describe('pipeline series service', () => {await expect(svc.setArcFieldLock(s.id, 'bogus', true)).rejects.toMatchObject({ code: svc.ERR_VALIDATION });});++ it('setArcFieldLock accepts readerMap as a lockable arc field', async () => {+ const s = await svc.createSeries({ name: 'X' });+ const locked = await svc.setArcFieldLock(s.id, 'readerMap', true);+ expect(locked.locked.arcFields).toEqual({ readerMap: true });+ const cleared = await svc.setArcFieldLock(s.id, 'readerMap', false);+ expect(cleared.locked.arcFields).toBeUndefined();+ });+ });++ describe('arc.readerMap', () => {+ it('persists a reader map through an arc-replace update and re-read', async () => {+ const s = await svc.createSeries({ name: 'X', arc: { logline: 'spine' } });+ const updated = await svc.updateSeries(s.id, {+ arc: { logline: 'spine', readerMap: { hooks: [{ label: 'who?' }], beats: [{ kind: 'reveal', intensity: 0.6 }] } },+ });+ expect(updated.arc.readerMap.hooks).toHaveLength(1);+ expect(updated.arc.readerMap.beats[0].kind).toBe('reveal');+ const fresh = await svc.getSeries(s.id);+ expect(fresh.arc.readerMap.hooks[0].label).toBe('who?');+ });++ it('arc is null and readerMap absent on a fresh series with no arc', async () => {+ const s = await svc.createSeries({ name: 'X' });+ expect(s.arc).toBe(null);+ });});});diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.jsindex bf2fcc719d..eb44f5edf1 100644--- a/server/services/sharing/integration.test.js+++ b/server/services/sharing/integration.test.js@@ -2057,7 +2057,7 @@ describe('sharing round-trip', () => {const result = await importer.processManifest(bucket.id, exp.filename);expect(result.skipped).toBe(true);expect(result.reason).toBe('portos-schema-ahead');- expect(result.ahead).toEqual([{ category: 'pipelineSeries', senderV: 99, receiverV: 1 }]);+ expect(result.ahead).toEqual([{ category: 'pipelineSeries', senderV: 99, receiverV: 2 }]);expect(result.producedByVersion).toBe('99.0.0');// Series stayed tombstoned (or absent) — apply was refused.await expect(series.getSeries(s.id)).rejects.toThrow();@@ -2073,7 +2073,7 @@ describe('sharing round-trip', () => {const exp = await exporter.exportSeries(s.id, bucket.id);const manifestPath = join(tempBucket, 'manifests', exp.filename);const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));- manifest.portosSchemaVersions = { universes: 99, pipelineSeries: 1, pipelineIssues: 1, mediaCollections: 99 };+ manifest.portosSchemaVersions = { universes: 99, pipelineSeries: 2, pipelineIssues: 1, mediaCollections: 99 };writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));await series.deleteSeries(s.id);simulateRemoteSender(tempBucket, exp.filename);diff --git a/server/services/storyBuilder.js b/server/services/storyBuilder.jsnew file mode 100644index 0000000000..1a8a737c5e--- /dev/null+++ b/server/services/storyBuilder.js@@ -0,0 +1,519 @@+/**+ * Unified Story Builder — conductor service.+ *+ * The Story Builder is a thin *conductor* over the existing universe / series /+ * issue records. It owns ONE lightweight record (the "session") that tracks+ * per-step status + locks + integrity hashes plus two FKs (`universeId`,+ * `seriesId`). All real content lives in the universe and series records and is+ * mutated through their existing services — this service never duplicates it.+ *+ * Sessions are LOCAL-ONLY: they reference peer-syncable records by FK, but the+ * lock/integrity bookkeeping is a private workflow artifact. We deliberately do+ * NOT register a sync schema version, do NOT add the type to+ * RECORD_TYPE_CATEGORIES, and do NOT auto-subscribe peers on create — syncing a+ * session would create cross-install staleness false-positives. The+ * tombstone/origin/ephemeral fields are carried only for on-disk shape parity.+ *+ * Persisted to data/story-builder/{id}/index.json.+ */++import { join } from 'path';+import { randomUUID } from 'crypto';+import { PATHS } from '../lib/fileUtils.js';+import { createCollectionStore } from '../lib/collectionStore.js';+import { isStr, trimTo } from '../lib/storyBible.js';+import { sanitizeOrigin } from '../lib/sharingOrigin.js';+import { sanitizeSoftDeleteFields } from '../lib/syncWire.js';+import { runStagedLLM } from '../lib/stageRunner.js';+import {+ STEP_IDS, STEP_STATUSES, isValidStepId, stepIndex,+} from '../lib/storyBuilderSteps.js';+import { hashUpstream, computeStaleSteps } from '../lib/storyBuilderIntegrity.js';+import { createUniverse, getUniverse, updateUniverse } from './universeBuilder.js';+import { expandWorldTemplate } from './universeBuilderExpand.js';+import { refineWorldPrompts } from './universeBuilderRefine.js';+import { refineUniverseCharacter } from './universeCanon.js';+import {+ createSeries, getSeries, updateSeries, setArcFieldLock,+} from './pipeline/series.js';+import { generateArcOverview, generateReaderMap, refineReaderMap } from './pipeline/arcPlanner.js';++const TYPE_SCHEMA_VERSION = 1;++let _store = null;+const store = () => {+ if (_store && _store.dir === join(PATHS.data, 'story-builder')) return _store;+ _store = createCollectionStore({+ dir: join(PATHS.data, 'story-builder'),+ type: 'storyBuilder',+ schemaVersion: TYPE_SCHEMA_VERSION,+ sanitizeRecord: sanitizeSession,+ idPattern: /^stb-[A-Za-z0-9-]+$/,+ });+ return _store;+};+export const storyBuilderStore = () => store();++export const ERR_NOT_FOUND = 'STORY_BUILDER_NOT_FOUND';+export const ERR_VALIDATION = 'STORY_BUILDER_VALIDATION';+const makeErr = (message, code) => Object.assign(new Error(message), { code });++const SESSION_ID_RE = /^stb-[A-Za-z0-9-]+$/;+export const TITLE_MAX = 200;+export const SEED_MAX = 4000;+export const INTAKE_MODES = Object.freeze(['seed', 'import']);++// The universe aesthetic step freezes these universe lock keys.+export const AESTHETIC_LOCK_FIELDS = Object.freeze([+ 'logline', 'premise', 'styleNotes', 'influencesEmbrace', 'influencesAvoid',+]);++const nowIso = () => new Date().toISOString();++function sanitizeStepState(raw) {+ const status = STEP_STATUSES.includes(raw?.status) ? raw.status : 'pending';+ const locked = raw?.locked === true;+ return {+ status: locked ? 'locked' : status,+ locked,+ lockedAt: locked && isStr(raw?.lockedAt) ? raw.lockedAt : null,+ upstreamHash: locked && isStr(raw?.upstreamHash) ? raw.upstreamHash : null,+ };+}++function sanitizeIssueLocks(raw) {+ if (!raw || typeof raw !== 'object') return {};+ const out = {};+ for (const [issueId, state] of Object.entries(raw)) {+ if (!isStr(issueId)) continue;+ if (state?.locked !== true) continue;+ out[issueId] = {+ locked: true,+ lockedAt: isStr(state.lockedAt) ? state.lockedAt : nowIso(),+ upstreamHash: isStr(state.upstreamHash) ? state.upstreamHash : null,+ };+ }+ return out;+}++function sanitizeSteps(raw) {+ const steps = {};+ for (const id of STEP_IDS) {+ steps[id] = sanitizeStepState(raw?.[id]);+ }+ // Per-issue locks ride on the `issues` step.+ const issueLocks = sanitizeIssueLocks(raw?.issues?.issueLocks);+ if (Object.keys(issueLocks).length > 0) steps.issues.issueLocks = issueLocks;+ return steps;+}++export function sanitizeSession(raw) {+ if (!raw || typeof raw !== 'object') return null;+ if (!isStr(raw.id) || !raw.id) return null;+ const title = trimTo(raw.title, TITLE_MAX);+ if (!title) return null;+ const intakeMode = INTAKE_MODES.includes(raw.intakeMode) ? raw.intakeMode : 'seed';+ const currentStep = isValidStepId(raw.currentStep) ? raw.currentStep : STEP_IDS[0];+ const llm = raw.llm && typeof raw.llm === 'object'+ ? { provider: trimTo(raw.llm.provider, 80) || null, model: trimTo(raw.llm.model, 200) || null }+ : { provider: null, model: null };+ const createdAt = isStr(raw.createdAt) ? raw.createdAt : nowIso();+ const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;+ return {+ id: raw.id,+ title,+ intakeMode,+ seedIdea: trimTo(raw.seedIdea, SEED_MAX),+ universeId: trimTo(raw.universeId, 64) || null,+ seriesId: trimTo(raw.seriesId, 64) || null,+ currentStep,+ steps: sanitizeSteps(raw.steps),+ llm,+ origin: sanitizeOrigin(raw.origin),+ createdAt,+ updatedAt,+ ...sanitizeSoftDeleteFields(raw),+ ...(raw.ephemeral === true ? { ephemeral: true } : {}),+ };+}++// ── CRUD ────────────────────────────────────────────────────────────────++export async function listStorySessions({ includeDeleted = false } = {}) {+ const sessions = await store().loadAll();+ const filtered = includeDeleted ? sessions : sessions.filter((s) => !s.deleted);+ return [...filtered].sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));+}++export async function getStorySession(id, { includeDeleted = false } = {}) {+ const found = await store().loadOne(id);+ if (!found) throw makeErr(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);+ if (found.deleted && !includeDeleted) throw makeErr(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);+ return found;+}++/**+ * Create a session. Seed mode mints fresh universe + series shells the+ * conductor will fill in step by step. Import mode expects the caller to have+ * already created/linked the universe + series (via the importer) and passes+ * their ids in.+ */+export async function createStorySession(input = {}) {+ const title = trimTo(input.title, TITLE_MAX);+ if (!title) throw makeErr(`Title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION);+ const intakeMode = INTAKE_MODES.includes(input.intakeMode) ? input.intakeMode : 'seed';+ const seedIdea = trimTo(input.seedIdea, SEED_MAX);++ let universeId = trimTo(input.universeId, 64) || null;+ let seriesId = trimTo(input.seriesId, 64) || null;++ if (intakeMode === 'seed') {+ // Mint the shells the wizard fills in. The universe name doubles as the+ // working title; the seed idea seeds the universe starter prompt.+ if (!universeId) {+ const universe = await createUniverse({ name: title, starterPrompt: seedIdea || '' });+ universeId = universe.id;+ }+ if (!seriesId) {+ const series = await createSeries({ name: title, universeId, premise: seedIdea || '' });+ seriesId = series.id;+ }+ }++ const now = nowIso();+ const created = sanitizeSession({+ id: `stb-${randomUUID()}`,+ title,+ intakeMode,+ seedIdea,+ universeId,+ seriesId,+ currentStep: STEP_IDS[0],+ steps: {},+ llm: input.llm || null,+ createdAt: now,+ updatedAt: now,+ // Import mode pre-fills content before review — mark every step "ready" so+ // the user walks through reviewing + locking each, rather than generating.+ ...(intakeMode === 'import' ? { steps: Object.fromEntries(STEP_IDS.map((id) => [id, { status: 'ready' }])) } : {}),+ });+ await store().saveOne(created.id, created);+ return created;+}++export async function updateStorySession(id, patch = {}) {+ return store().queueRecordWrite(id, async () => {+ const cur = await store().loadOne(id);+ if (!cur || cur.deleted) throw makeErr(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);+ const next = sanitizeSession({+ ...cur,+ ...('title' in patch ? { title: patch.title } : {}),+ ...('seedIdea' in patch ? { seedIdea: patch.seedIdea } : {}),+ ...('currentStep' in patch ? { currentStep: patch.currentStep } : {}),+ ...('llm' in patch ? { llm: { ...(cur.llm || {}), ...(patch.llm || {}) } } : {}),+ updatedAt: nowIso(),+ });+ if (!next) throw makeErr('Invalid session payload', ERR_VALIDATION);+ await store().saveOneNow(next.id, next);+ return next;+ });+}++export async function deleteStorySession(id) {+ return store().queueRecordWrite(id, async () => {+ const cur = await store().loadOne(id);+ if (!cur || cur.deleted) throw makeErr(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);+ const now = nowIso();+ await store().saveOneNow(id, { ...cur, deleted: true, deletedAt: now, updatedAt: now });+ return { id };+ });+}++// ── Integrity (staleness) ─────────────────────────────────────────────────++// Project the whitelisted SEMANTIC upstream fields per step. Never include+// `updatedAt` or other churn — only fields whose change should invalidate a+// downstream lock.+function projectAesthetic(universe) {+ const inf = universe?.influences || {};+ return {+ logline: universe?.logline || '',+ premise: universe?.premise || '',+ styleNotes: universe?.styleNotes || '',+ influencesEmbrace: Array.isArray(inf.embrace) ? inf.embrace : [],+ influencesAvoid: Array.isArray(inf.avoid) ? inf.avoid : [],+ };+}+function projectArc(series) {+ const arc = series?.arc || {};+ return {+ logline: arc.logline || '',+ summary: arc.summary || '',+ protagonistArc: arc.protagonistArc || '',+ themes: Array.isArray(arc.themes) ? arc.themes : [],+ shape: arc.shape || null,+ };+}+function projectCast(universe) {+ return (Array.isArray(universe?.characters) ? universe.characters : [])+ .map((c) => ({ name: c?.name || '', descriptor: c?.descriptor ?? null }));+}++function buildUpstreamInputs(session, universe, series) {+ const aesthetic = projectAesthetic(universe);+ const arc = projectArc(series);+ const readerMap = series?.arc?.readerMap || null;+ const cast = projectCast(universe);+ return {+ idea: { intakeMode: session.intakeMode, seedIdea: session.seedIdea || '' },+ universeAesthetic: { seedIdea: session.seedIdea || '' },+ plotArc: { aesthetic, seedIdea: session.seedIdea || '' },+ readerMap: { arc },+ characters: { readerMap, arcSummary: arc.summary, aesthetic },+ issues: { arc, readerMap, cast },+ production: { arc, readerMap, cast },+ };+}++/**+ * Compute the current upstream hash for every step from the live universe ++ * series records. Pure-on-read — does not mutate the session.+ */+export async function computeCurrentHashes(session) {+ const universe = session.universeId ? await getUniverse(session.universeId).catch(() => null) : null;+ const series = session.seriesId ? await getSeries(session.seriesId).catch(() => null) : null;+ const inputs = buildUpstreamInputs(session, universe, series);+ const hashes = {};+ for (const id of STEP_IDS) hashes[id] = hashUpstream(id, inputs[id]);+ return { hashes, universe, series };+}++/**+ * Load a session augmented with the computed `staleSteps` array (the locked+ * steps whose upstream inputs have drifted since lock time). This is the shape+ * the route serves to the client.+ */+export async function getStorySessionView(id) {+ const session = await getStorySession(id);+ const { hashes, universe, series } = await computeCurrentHashes(session);+ const staleSteps = computeStaleSteps(session, hashes);+ return { session, staleSteps, universe, series };+}++// ── State machine: lock / unlock ──────────────────────────────────────────++// Apply (or release) the underlying record lock that backs a step, so the+// existing generate guards (locked-arc, locked-readerMap, locked-canon) take+// effect. Best-effort per step; the session lock is the source of truth for+// the wizard gate, the record lock is the enforcement at the generator.+async function applyUnderlyingLock(session, stepId, locked) {+ if (stepId === 'universeAesthetic' && session.universeId) {+ const universe = await getUniverse(session.universeId).catch(() => null);+ if (!universe) return;+ const nextLocked = { ...(universe.locked || {}) };+ for (const f of AESTHETIC_LOCK_FIELDS) {+ if (locked) nextLocked[f] = true;+ else delete nextLocked[f];+ }+ await updateUniverse(session.universeId, { locked: nextLocked });+ } else if (stepId === 'plotArc' && session.seriesId) {+ const series = await getSeries(session.seriesId).catch(() => null);+ if (!series) return;+ const nextLocked = { ...(series.locked || {}) };+ if (locked) nextLocked.arc = true;+ else delete nextLocked.arc;+ await updateSeries(session.seriesId, { locked: nextLocked });+ } else if (stepId === 'readerMap' && session.seriesId) {+ await setArcFieldLock(session.seriesId, 'readerMap', locked);+ } else if (stepId === 'characters' && session.universeId) {+ const universe = await getUniverse(session.universeId).catch(() => null);+ if (!universe || !Array.isArray(universe.characters)) return;+ const characters = universe.characters.map((c) => ({ ...c, locked }));+ await updateUniverse(session.universeId, { characters });+ }+}++export async function lockStep(id, stepId) {+ if (!isValidStepId(stepId)) throw makeErr(`Unknown step: ${stepId}`, ERR_VALIDATION);+ const session = await getStorySession(id);+ const { hashes } = await computeCurrentHashes(session);+ await applyUnderlyingLock(session, stepId, true);+ return store().queueRecordWrite(id, async () => {+ const cur = await store().loadOne(id);+ if (!cur || cur.deleted) throw makeErr(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);+ const steps = { ...cur.steps };+ steps[stepId] = {+ ...steps[stepId],+ status: 'locked',+ locked: true,+ lockedAt: nowIso(),+ upstreamHash: hashes[stepId],+ };+ const next = sanitizeSession({ ...cur, steps, updatedAt: nowIso() });+ await store().saveOneNow(next.id, next);+ return next;+ });+}++export async function unlockStep(id, stepId) {+ if (!isValidStepId(stepId)) throw makeErr(`Unknown step: ${stepId}`, ERR_VALIDATION);+ const session = await getStorySession(id);+ await applyUnderlyingLock(session, stepId, false);+ return store().queueRecordWrite(id, async () => {+ const cur = await store().loadOne(id);+ if (!cur || cur.deleted) throw makeErr(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);+ const steps = { ...cur.steps };+ steps[stepId] = { status: 'ready', locked: false, lockedAt: null, upstreamHash: null };+ const next = sanitizeSession({ ...cur, steps, updatedAt: nowIso() });+ await store().saveOneNow(next.id, next);+ return next;+ });+}++/**+ * Set the wizard's current step. Gated: cannot advance to a step unless every+ * earlier step is locked AND no earlier locked step is stale.+ */+export async function setCurrentStep(id, stepId) {+ if (!isValidStepId(stepId)) throw makeErr(`Unknown step: ${stepId}`, ERR_VALIDATION);+ const session = await getStorySession(id);+ const target = stepIndex(stepId);+ const cur = stepIndex(session.currentStep);+ if (target > cur) {+ const { hashes } = await computeCurrentHashes(session);+ const stale = computeStaleSteps(session, hashes);+ for (let i = 0; i < target; i++) {+ const earlier = STEP_IDS[i];+ if (session.steps[earlier]?.locked !== true) {+ throw makeErr(`Cannot advance: step "${earlier}" must be locked first`, ERR_VALIDATION);+ }+ if (stale.includes(earlier)) {+ throw makeErr(`Cannot advance: step "${earlier}" is stale — re-review and re-lock it`, ERR_VALIDATION);+ }+ }+ }+ return updateStorySession(id, { currentStep: stepId });+}++// ── Per-issue locks (issues step loop) ────────────────────────────────────++export async function setIssueLock(id, issueId, locked) {+ if (!isStr(issueId) || !issueId) throw makeErr('issueId is required', ERR_VALIDATION);+ return store().queueRecordWrite(id, async () => {+ const cur = await store().loadOne(id);+ if (!cur || cur.deleted) throw makeErr(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);+ const steps = { ...cur.steps };+ const issueLocks = { ...(steps.issues?.issueLocks || {}) };+ if (locked) issueLocks[issueId] = { locked: true, lockedAt: nowIso(), upstreamHash: null };+ else delete issueLocks[issueId];+ steps.issues = { ...steps.issues, issueLocks };+ const next = sanitizeSession({ ...cur, steps, updatedAt: nowIso() });+ await store().saveOneNow(next.id, next);+ return next;+ });+}++// ── Generate / refine delegation ──────────────────────────────────────────++// Each step's generate delegates to the existing service that owns its content,+// then persists into the universe/series record. Returns the LLM result so the+// route can surface runId / changes / rationale.+export async function generateStep(id, stepId, options = {}) {+ const session = await getStorySession(id);+ if (stepId === 'idea') {+ const { content, runId, providerId, model } = await runStagedLLM(+ 'story-builder-idea-expand',+ { universeName: session.title, seedIdea: session.seedIdea || '' },+ { providerOverride: options.providerId, modelOverride: options.model, returnsJson: true, source: 'story-builder-idea-expand' },+ );+ const expandedIdea = isStr(content?.expandedIdea) ? content.expandedIdea.trim() : '';+ const logline = isStr(content?.logline) ? content.logline.trim() : '';+ // Seed the universe starter + series premise/logline from the expansion.+ if (session.universeId && expandedIdea) {+ await updateUniverse(session.universeId, { starterPrompt: expandedIdea, ...(logline ? { logline } : {}) });+ }+ if (session.seriesId) {+ await updateSeries(session.seriesId, { ...(logline ? { logline } : {}), ...(expandedIdea ? { premise: expandedIdea } : {}) });+ }+ return { result: content, runId, providerId, model };+ }+ if (stepId === 'universeAesthetic') {+ if (!session.universeId) throw makeErr('No universe linked', ERR_VALIDATION);+ const universe = await getUniverse(session.universeId);+ const expanded = await expandWorldTemplate({+ starterPrompt: universe.starterPrompt || session.seedIdea || universe.name,+ influences: universe.influences,+ logline: universe.logline,+ premise: universe.premise,+ styleNotes: universe.styleNotes,+ locked: universe.locked,+ providerId: options.providerId,+ model: options.model,+ });+ const updated = await updateUniverse(session.universeId, {+ logline: expanded.logline,+ premise: expanded.premise,+ styleNotes: expanded.styleNotes,+ ...(expanded.influences ? { influences: expanded.influences } : {}),+ });+ return { result: updated, providerId: expanded.providerId, model: expanded.model };+ }+ if (stepId === 'plotArc') {+ if (!session.seriesId) throw makeErr('No series linked', ERR_VALIDATION);+ const { arc, seasons, runId, providerId, model } = await generateArcOverview(session.seriesId, {+ providerOverride: options.providerId, modelOverride: options.model,+ });+ const updated = await updateSeries(session.seriesId, { arc, seasons });+ return { result: updated, runId, providerId, model };+ }+ if (stepId === 'readerMap') {+ if (!session.seriesId) throw makeErr('No series linked', ERR_VALIDATION);+ const { readerMap, runId, providerId, model } = await generateReaderMap(session.seriesId, {+ providerOverride: options.providerId, modelOverride: options.model,+ });+ const series = await getSeries(session.seriesId);+ const updated = await updateSeries(session.seriesId, { arc: { ...(series.arc || {}), readerMap } });+ return { result: updated, runId, providerId, model };+ }+ throw makeErr(`Generate is not supported for step "${stepId}"`, ERR_VALIDATION);+}++export async function refineStep(id, stepId, { feedback, entryId, providerId, model } = {}) {+ const session = await getStorySession(id);+ if (stepId === 'universeAesthetic') {+ if (!session.universeId) throw makeErr('No universe linked', ERR_VALIDATION);+ const universe = await getUniverse(session.universeId);+ const refined = await refineWorldPrompts({+ starterPrompt: universe.starterPrompt || universe.name,+ logline: universe.logline,+ premise: universe.premise,+ styleNotes: universe.styleNotes,+ influences: universe.influences,+ locked: universe.locked,+ feedback,+ providerId,+ model,+ });+ const updated = await updateUniverse(session.universeId, {+ logline: refined.logline,+ premise: refined.premise,+ styleNotes: refined.styleNotes,+ ...(refined.influences ? { influences: refined.influences } : {}),+ });+ return { result: updated, changes: refined.changes || [], rationale: refined.rationale || '' };+ }+ if (stepId === 'readerMap') {+ if (!session.seriesId) throw makeErr('No series linked', ERR_VALIDATION);+ const { readerMap, changes, rationale, runId } = await refineReaderMap(session.seriesId, feedback, { providerId, model });+ const series = await getSeries(session.seriesId);+ const updated = await updateSeries(session.seriesId, { arc: { ...(series.arc || {}), readerMap } });+ return { result: updated, changes, rationale, runId };+ }+ if (stepId === 'characters') {+ if (!session.universeId) throw makeErr('No universe linked', ERR_VALIDATION);+ if (!isStr(entryId)) throw makeErr('entryId is required to refine a character', ERR_VALIDATION);+ const out = await refineUniverseCharacter(session.universeId, entryId, { providerId, model });+ return { result: out.universe, changes: out.changes || [], rationale: out.rationale || '' };+ }+ throw makeErr(`Refine is not supported for step "${stepId}"`, ERR_VALIDATION);+}diff --git a/server/services/storyBuilder.test.js b/server/services/storyBuilder.test.jsnew file mode 100644index 0000000000..d1b8cec97c--- /dev/null+++ b/server/services/storyBuilder.test.js@@ -0,0 +1,179 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { mockNoPeerSync, mockNoPeers } from '../lib/mockPathsDataRoot.js';++// In-memory file store shared by all collection stores (storyBuilder, universe,+// series) — mirrors the arcPlanner.test.js fixture so create paths persist.+const fileStore = new Map();+let stageRunnerSpy;++vi.mock('../lib/fileUtils.js', () => ({+ tryReadFile: vi.fn().mockResolvedValue(null),+ PATHS: { data: '/mock/data' },+ ensureDir: vi.fn().mockResolvedValue(undefined),+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),+ readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),+}));++let uuidCounter = 0;+vi.mock('crypto', async () => {+ const actual = await vi.importActual('crypto');+ return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };+});++vi.mock('../instances.js', () => mockNoPeers());+vi.mock('../sharing/peerSync.js', () => mockNoPeerSync());++vi.mock('../lib/stageRunner.js', () => ({+ runStagedLLM: vi.fn((...args) => stageRunnerSpy(...args)),+ extractJson: (raw) => JSON.parse(raw),+}));++const sb = await import('./storyBuilder.js');+const seriesSvc = await import('./pipeline/series.js');+const universeSvc = await import('./universeBuilder.js');++beforeEach(() => {+ fileStore.clear();+ uuidCounter = 0;+ stageRunnerSpy = undefined;+});++describe('storyBuilder — CRUD', () => {+ it('seed mode mints universe + series shells and starts on the idea step', async () => {+ const s = await sb.createStorySession({ title: 'Salt Run', seedIdea: 'a foundry city goes silent' });+ expect(s.id).toMatch(/^stb-/);+ expect(s.intakeMode).toBe('seed');+ expect(s.universeId).toMatch(/^univ-|^uni-|.+/); // minted+ expect(s.seriesId).toMatch(/^ser-/);+ expect(s.currentStep).toBe('idea');+ // Every step starts pending + unlocked.+ expect(s.steps.idea).toEqual({ status: 'pending', locked: false, lockedAt: null, upstreamHash: null });+ // The shells actually exist.+ const universe = await universeSvc.getUniverse(s.universeId);+ expect(universe.name).toBe('Salt Run');+ const series = await seriesSvc.getSeries(s.seriesId);+ expect(series.premise).toBe('a foundry city goes silent');+ });++ it('import mode does not mint shells and marks all steps ready', async () => {+ const universe = await universeSvc.createUniverse({ name: 'U' });+ const series = await seriesSvc.createSeries({ name: 'S', universeId: universe.id });+ const s = await sb.createStorySession({+ title: 'Imported', intakeMode: 'import', universeId: universe.id, seriesId: series.id,+ });+ expect(s.universeId).toBe(universe.id);+ expect(s.seriesId).toBe(series.id);+ expect(s.steps.idea.status).toBe('ready');+ expect(s.steps.readerMap.status).toBe('ready');+ });++ it('rejects a blank title', async () => {+ await expect(sb.createStorySession({ title: ' ' })).rejects.toMatchObject({ code: sb.ERR_VALIDATION });+ });++ it('lists, gets, updates, and soft-deletes', async () => {+ const s = await sb.createStorySession({ title: 'X' });+ expect((await sb.listStorySessions()).map((x) => x.id)).toContain(s.id);+ const updated = await sb.updateStorySession(s.id, { title: 'Renamed' });+ expect(updated.title).toBe('Renamed');+ await sb.deleteStorySession(s.id);+ await expect(sb.getStorySession(s.id)).rejects.toMatchObject({ code: sb.ERR_NOT_FOUND });+ expect((await sb.listStorySessions()).map((x) => x.id)).not.toContain(s.id);+ });+});++describe('storyBuilder — lock state machine + gating', () => {+ it('lockStep stamps an upstreamHash and flips status to locked', async () => {+ const s = await sb.createStorySession({ title: 'X', seedIdea: 'seed' });+ const locked = await sb.lockStep(s.id, 'idea');+ expect(locked.steps.idea.locked).toBe(true);+ expect(locked.steps.idea.upstreamHash).toMatch(/^[0-9a-f]{64}$/);+ expect(locked.steps.idea.lockedAt).toBeTruthy();+ });++ it('cannot advance to a step until every earlier step is locked', async () => {+ const s = await sb.createStorySession({ title: 'X' });+ // idea not locked → cannot jump to universeAesthetic+ await expect(sb.setCurrentStep(s.id, 'universeAesthetic')).rejects.toMatchObject({ code: sb.ERR_VALIDATION });+ await sb.lockStep(s.id, 'idea');+ const moved = await sb.setCurrentStep(s.id, 'universeAesthetic');+ expect(moved.currentStep).toBe('universeAesthetic');+ // plotArc still blocked — universeAesthetic not locked+ await expect(sb.setCurrentStep(s.id, 'plotArc')).rejects.toMatchObject({ code: sb.ERR_VALIDATION });+ });++ it('moving backward is always allowed', async () => {+ const s = await sb.createStorySession({ title: 'X' });+ await sb.lockStep(s.id, 'idea');+ await sb.setCurrentStep(s.id, 'universeAesthetic');+ const back = await sb.setCurrentStep(s.id, 'idea');+ expect(back.currentStep).toBe('idea');+ });++ it('unlockStep clears the lock and releases the underlying series arc lock', async () => {+ const s = await sb.createStorySession({ title: 'X' });+ await sb.lockStep(s.id, 'plotArc');+ let series = await seriesSvc.getSeries(s.seriesId);+ expect(series.locked.arc).toBe(true);+ const after = await sb.unlockStep(s.id, 'plotArc');+ expect(after.steps.plotArc.locked).toBe(false);+ series = await seriesSvc.getSeries(s.seriesId);+ expect(series.locked.arc).toBeUndefined();+ });+});++describe('storyBuilder — integrity / staleness', () => {+ it('flags a locked downstream step stale when an upstream record changes', async () => {+ const s = await sb.createStorySession({ title: 'X' });+ // Give the series an arc + reader map, then lock the readerMap step.+ await seriesSvc.updateSeries(s.seriesId, {+ arc: { logline: 'spine', summary: 'sum', readerMap: { hooks: [{ label: 'h' }] } },+ });+ await sb.lockStep(s.id, 'readerMap');+ let view = await sb.getStorySessionView(s.id);+ expect(view.staleSteps).not.toContain('readerMap');+ // Now change an upstream arc field the readerMap depends on.+ await seriesSvc.updateSeries(s.seriesId, {+ arc: { logline: 'CHANGED spine', summary: 'sum', readerMap: { hooks: [{ label: 'h' }] } },+ });+ view = await sb.getStorySessionView(s.id);+ expect(view.staleSteps).toContain('readerMap');+ });++ it('does not flag unlocked steps as stale', async () => {+ const s = await sb.createStorySession({ title: 'X' });+ await seriesSvc.updateSeries(s.seriesId, { arc: { logline: 'a', summary: 'b' } });+ const view = await sb.getStorySessionView(s.id);+ expect(view.staleSteps).toEqual([]);+ });+});++describe('storyBuilder — generate delegation', () => {+ it('generateStep(plotArc) persists the arc onto the series', async () => {+ const s = await sb.createStorySession({ title: 'X' });+ stageRunnerSpy = vi.fn(async () => ({+ content: { logline: 'arc logline', summary: 'arc summary', shape: 'man-in-hole', seasonOutlines: [] },+ runId: 'r', providerId: 'p', model: 'm',+ }));+ await sb.generateStep(s.id, 'plotArc');+ const series = await seriesSvc.getSeries(s.seriesId);+ expect(series.arc.logline).toBe('arc logline');+ expect(series.arc.shape).toBe('man-in-hole');+ });++ it('generateStep(readerMap) works even after the plot arc is locked', async () => {+ const s = await sb.createStorySession({ title: 'X' });+ await seriesSvc.updateSeries(s.seriesId, { arc: { logline: 'spine', summary: 'sum' } });+ await sb.lockStep(s.id, 'plotArc'); // sets series.locked.arc = true+ stageRunnerSpy = vi.fn(async () => ({+ content: { hooks: [{ label: 'why?' }], payoffs: [], beats: [], cliffhangers: [] },+ runId: 'r', providerId: 'p', model: 'm',+ }));+ await sb.generateStep(s.id, 'readerMap');+ const series = await seriesSvc.getSeries(s.seriesId);+ expect(series.arc.readerMap.hooks[0].label).toBe('why?');+ // The locked arc core fields are untouched.+ expect(series.arc.logline).toBe('spine');+ expect(series.locked.arc).toBe(true);+ });+});