Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(importer): Create Suite Importer page (#253)

[._.]/ Adam Eivy7294645453f1
diff --git a/PLAN.md b/PLAN.md
index d9aa158b7a..875a3aed3d 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -19,17 +19,29 @@ V1 landed: buckets, ShareToButton on Pipeline + UniverseBuilder + MediaCollectio
- [ ] **Extend `syncOrchestrator` to cover pipeline/universe over Tailscale.** Separate ticket from buckets — same-network peers on Tailscale should be able to sync these categories without going through a bucket.
- [ ] **Multi-hop provenance chains.** Re-share authors a fresh `origin` block; chain[] would preserve full attribution. Defer until users ask.
-### Create Suite — Importer page
-
-New on-ramp to the Create pipeline. User pastes a short story / novel / screenplay / comic script + Universe Name + Series Name; the Importer LLM-extracts universe canon (characters/places/objects), the story arc, and a proposed issue split; user reviews and commits to create or extend the universe + series with prose-seeded issues ready for the visual render stages. Find-or-create on both Universe and Series names so the same import can extend an existing world. See `~/.claude/plans/i-want-to-add-vivid-bear.md` for the full design.
-
-- [ ] Page scaffold: `client/src/pages/Importer.jsx` (intake + review phases), API client `client/src/services/apiImporter.js`, lazy `<Route path="importer">` in `App.jsx`, sidebar entry in `Layout.jsx`, `nav.create.importer` in `navManifest.js`.
-- [ ] Server orchestrator `server/services/importer.js` — `analyzeImport` (no persistence) + `commitImport` (universe canon merge + series arc/seasons + issue creation with `stages.prose.output` seeded).
-- [ ] Server routes `server/routes/importer.js` + Zod schemas `importerAnalyzeSchema` / `importerCommitSchema` in `server/lib/validation.js`.
-- [ ] Three new stage prompts: `importer-canon-extract.md`, `importer-arc-extract.md`, `importer-issue-proposal.md` (in `data.sample/prompts/stages/`); content-type branching inside via Liquid `{% if %}`. Add a migration script in `scripts/migrations/` so existing installs pick them up.
-- [ ] Find-or-create logic: case-insensitive name match; series match scoped to universe; respect `series.locked.arc` (throw `ERR_VALIDATION`, mirror arcPlanner pattern).
-- [ ] Tests in `server/services/importer.test.js` — find-or-create, analyze shape, commit happy/locked/duplicate paths, route validation.
-- [ ] **Follow-up**: chunked extraction for source > 200K chars (v1 hard-rejects; capture as a separate item once we hit the limit on a real import).
+### Create Suite — Importer page (v1 shipped 2026-05-16)
+
+V1 shipped — `/importer` reverse-engineers a finished story / novel / screenplay / comic script into universe canon + series arc + prose-seeded issues. See `~/.claude/plans/i-want-to-add-vivid-bear.md` for the full design and `.changelog/NEXT.md` for the shipped notes.
+
+- [x] Page scaffold: `client/src/pages/Importer.jsx` (intake + review phases), API client `client/src/services/apiImporter.js`, lazy `<Route path="importer">` in `App.jsx`, sidebar entry in `Layout.jsx`, `nav.create.importer` in `navManifest.js`.
+- [x] Server orchestrator `server/services/importer.js` — `analyzeImport` (no persistence) + `commitImport` (universe canon merge + series arc/seasons + issue creation with `stages.prose.output` seeded).
+- [x] Server routes `server/routes/importer.js` + Zod schemas `importerAnalyzeSchema` / `importerCommitSchema` in `server/lib/validation.js`.
+- [x] Three new stage prompts: `importer-canon-extract.md`, `importer-arc-extract.md`, `importer-issue-proposal.md` (in `data.sample/prompts/stages/`); content-type branching inside via Mustache section guards (`{{#isShortStory}}…{{/isShortStory}}`) — PortOS's template engine is Mustache-only, not Liquid. The orchestrator passes per-type booleans (`isShortStory`, `isNovel`, `isScreenplay`, `isComicScript`) alongside the contentType string. Migration `015-importer-stage-prompts.js` seeds them into existing installs.
+- [x] Find-or-create logic: case-insensitive name match; series match scoped to universe; respect `series.locked.arc` (throw `ERR_LOCKED`).
+- [x] Tests in `server/services/importer.test.js` — find-or-create scoping, oversize rejection, locked-arc gating, commit happy/duplicate paths, route validation (via Zod).
+
+**Follow-ups (deferred from v1):**
+
+- [ ] **Chunked extraction for source > 200K chars.** v1 hard-rejects with `ERR_VALIDATION`. Once a real import hits the cap, lift the limit and route through a per-chunk canon extraction + rolling synopsis for arc-extract (issue-proposal still takes the full source). Investigation needed first to pick a chunk-overlap / merge strategy that doesn't double-extract recurring characters. Touch site: `server/services/importer.js#analyzeImport` (the `source.length > IMPORTER_SOURCE_CHAR_LIMIT` guard).
+- [ ] **Auto-detect content type.** Today the user picks via radio. A small `importer-classify.md` stage could run first and pre-select the radio (still user-editable). Skipped in v1 because the radio is one click.
+- [ ] **Re-running an import to *replace* (not append) an existing series.** Today the second pass extends. A destructive-confirm UX with a "Replace all" toggle would let the user blow away the previous import without manually deleting the series first. Hold until a user actually asks.
+- [ ] **Importer review UI: extract `<CanonCard>` once it lands.** Today `client/src/pages/Importer.jsx#CanonReviewSection` renders an inline minimal card. When the Phase 2 "Extract shared CanonCard" item below (under Universe-as-Canon refactor) ships, swap the inline card for the shared component so locked / source-badge / tag-chip affordances appear here automatically.
+- [ ] **[PERF] `updateAt` re-render cost in `Importer.jsx`.** The `updateAt` helper (search the file for the function name — line drifts with edits) rebuilds the full list array on every keystroke, causing `IssuesReviewSection`/`ArcReviewSection` to re-render all sibling cards simultaneously — with up to 50 issues each carrying multi-paragraph synopses + 500K-char `proseExcerpt` displays, this can feel sluggish. Fix by either (a) wrapping issue/arc cards in `React.memo` so unchanged entries bail out, or (b) moving inline edits into per-card local state that lifts on blur. Deferred from v1 PR #253 — performance not correctness.
+- [ ] **Centralise `ARC_ROLES` source-of-truth, drop client-side fallback.** `IMPORTER_ARC_ROLES_FALLBACK` in `client/src/services/apiImporter.js:14` hard-codes the arc-role enum. The server now exposes `arcRoles` via `/importer/config` + the analyze response, but the fallback will silently drift from `server/lib/storyArc.js#ARC_ROLES` if a role is added/removed and the client isn't redeployed in lockstep. The list also lives in `data.sample/prompts/stages/importer-issue-proposal.md` (hand-maintained). Pick one: (a) drop the client fallback to `[]` + show a "loading roles…" placeholder until config fetch lands, or (b) generate the prompt enum + client fallback from `storyArc.js` at build time. Deferred from PR #253 — long-term maintainability, not a current bug.
+- [ ] **Expose `ARC_SHAPE_IDS` via `/importer/config` (same drift hazard as arc-roles).** `client/src/pages/Importer.jsx` arc-shape `<select>` is populated from `STORY_SHAPES` (client-side `components/pipeline/StoryShapes`), but the server's allowed enum is `ARC_SHAPE_IDS` from `server/lib/storyArc.js` (used by `importerArcShape` + `buildArcPreview`). If `STORY_SHAPES` ever diverges, the user could pick a UI-only shape that the server rejects, or miss a valid shape. Fold this into the same fix as the arc-roles centralisation above — the `/importer/config` payload should expose both. Deferred from PR #253.
+- [ ] **Importer screenplay prompt — `targetIssueCount` default vs user-requested clarity.** `data.sample/prompts/stages/importer-issue-proposal.md:36` reads "If the screenplay contains ACT ONE/TWO/THREE breaks AND `targetIssueCount > 1`, split on act breaks; otherwise return one issue." But the orchestrator defaults `targetIssueCount` to 1 for screenplay (via `DEFAULT_TARGET_ISSUE_COUNT_HINT`) and only treats it as user-requested when the user explicitly passes it. The current prompt phrasing makes a 1-issue default look like a deliberate user request to NOT split, when in fact it's just the absence of intent. Either (a) pass a separate `isUserRequestedCount` flag into the template and gate the split logic on that, or (b) reword the prompt to distinguish "the user set targetIssueCount=N" from "default is 1". Deferred from PR #253 — needs prompt + orchestrator co-change.
+- [ ] **Importer partial-commit retry — guard against arc re-apply.** When `commitImport` rolls back issues mid-loop (throws `ERR_PARTIAL_COMMIT_ISSUES`), the universe + series ARE updated (intentional). A naive client retry resubmits the same payload; canon + seasons merge idempotently, but the `arc` field is unconditionally re-applied via `updateSeries({ arc: sanitizedArc })` — overwriting any edits the user made server-side between the failed attempt and the retry. Touch site: `server/services/importer.js#commitImport` around line 525. Possible fixes: (a) on retry, return a tagged response from the route so the client can opt to skip arc; (b) extend `ERR_PARTIAL_COMMIT_ISSUES` so the route reply tells the client "universe + series already updated — retry can safely skip those fields"; (c) version the arc and reject the second write if `series.arc.updatedAt > original.updatedAt`. Deferred from PR #253 — needs UX + API contract decision.
+- [ ] **Importer Review UI: in-place `proseExcerpt` edit affordance.** The Review phase renders the LLM-picked excerpt as a read-only char-count line. If the excerpt is wrong (overlaps a neighbor's, is empty/whitespace, includes a spurious header), the only recovery today is to abandon the flow, edit the source, and re-run Analyze — burning three heavy-tier LLM calls. Add a collapsed-by-default textarea (rendering 500K chars uncollapsed is itself a perf concern, hence collapsed) per issue card so the user can trim/correct without restarting. Touch site: `IssuesReviewSection` in `client/src/pages/Importer.jsx` (search the file for the function name — line drifts). Deferred from PR #253 — non-trivial UI + needs a "is this textarea actually editing the right thing" UX pass with the user.
### Universe-as-Canon refactor — Phase B.4 cleanup + follow-ups
diff --git a/client/src/App.jsx b/client/src/App.jsx
index a188a5d7f7..bec7532551 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -84,6 +84,7 @@ const RapidReaderPage = lazyWithReload(() => import('./pages/RapidReader'));
const WritersRoom = lazyWithReload(() => import('./pages/WritersRoom'));
const Pipeline = lazyWithReload(() => import('./pages/Pipeline'));
const Sharing = lazyWithReload(() => import('./pages/Sharing'));
+const Importer = lazyWithReload(() => import('./pages/Importer'));
const PipelineSeries = lazyWithReload(() => import('./pages/PipelineSeries'));
const PipelineIssue = lazyWithReload(() => import('./pages/PipelineIssue'));
@@ -225,6 +226,7 @@ export default function App() {
<Route path="universe-builder/:universeId/canon" element={<UniverseCanon />} />
<Route path="writers-room" element={<WritersRoom />} />
<Route path="sharing" element={<Sharing />} />
+ <Route path="importer" element={<Importer />} />
<Route path="pipeline" element={<Pipeline />} />
<Route path="pipeline/series/:seriesId" element={<PipelineSeries />} />
<Route path="pipeline/issues/:issueId" element={<Navigate to="idea" replace />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 46639353bb..60cee376b6 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -64,6 +64,7 @@ import {
Inbox,
RefreshCw,
Dog,
+ FileInput,
FilePen,
MessageCircle,
Swords,
@@ -194,6 +195,7 @@ const navItems = [
icon: Sparkles,
defaultTo: '/media',
children: [
+ { to: '/importer', label: 'Importer', icon: FileInput },
{ to: '/media', label: 'Media Gen', icon: Layers },
{ to: '/pipeline', label: 'Series Pipeline', icon: WorkflowIcon, dynamic: 'pipelineSeries' },
{ to: '/sharing', label: 'Sharing', icon: Share2 },
diff --git a/client/src/pages/Importer.jsx b/client/src/pages/Importer.jsx
new file mode 100644
index 0000000000..a8f7e8065a
--- /dev/null
+++ b/client/src/pages/Importer.jsx
@@ -0,0 +1,743 @@
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import { FileInput, Loader2, ArrowLeft, CheckCircle2, AlertTriangle } from 'lucide-react';
+import toast from '../components/ui/Toast';
+import { useAsyncAction } from '../hooks/useAsyncAction';
+import { STORY_SHAPES } from '../components/pipeline/StoryShapes';
+import {
+ analyzeImport,
+ commitImport,
+ getImporterConfig,
+ IMPORTER_CONTENT_TYPES,
+ IMPORTER_SOURCE_CHAR_LIMIT_FALLBACK,
+ IMPORTER_ARC_ROLES_FALLBACK,
+} from '../services/apiImporter';
+
+const CONTENT_TYPE_LABELS = {
+ 'short-story': 'Short Story',
+ 'novel': 'Novel',
+ 'screenplay': 'Screenplay',
+ 'comic-script': 'Comic Script',
+};
+
+// Whitelist of arc fields forwarded to the commit endpoint. The wire schema
+// (`importerArcShape`) is `.passthrough()` today and `sanitizeArc` ignores
+// unknowns, but `arcDraft` starts as a shallow clone of the LLM's arc
+// output — which still has the LLM-returned `seasons` field at the top
+// level. Without this strip the seasons would smuggle through to
+// `series.arc` if the schema ever tightens to `.strict()`.
+const ARC_FIELDS_TO_COMMIT = ['logline', 'summary', 'protagonistArc', 'themes', 'shape'];
+const pickArcFields = (arc) => {
+ if (!arc) return null;
+ const out = {};
+ for (const k of ARC_FIELDS_TO_COMMIT) {
+ if (arc[k] !== undefined) out[k] = arc[k];
+ }
+ return out;
+};
+
+const emptyIntake = () => ({
+ universeName: '',
+ seriesName: '',
+ contentType: 'short-story',
+ source: '',
+ targetIssueCount: '',
+});
+
+export default function Importer() {
+ const navigate = useNavigate();
+ const [phase, setPhase] = useState('intake'); // 'intake' | 'review'
+ const [intake, setIntake] = useState(emptyIntake);
+ const [preview, setPreview] = useState(null);
+
+ // Server-canonical config (source-char limit + arc-roles enum). Falls back
+ // to the shipped client defaults until the GET resolves. Hydrated on mount
+ // so the intake form's char-count warning + the review form's arc-role
+ // dropdown stay aligned with the server even when the server bumps the cap
+ // or extends the enum without a client redeploy.
+ const [config, setConfig] = useState({
+ sourceCharLimit: IMPORTER_SOURCE_CHAR_LIMIT_FALLBACK,
+ arcRoles: IMPORTER_ARC_ROLES_FALLBACK,
+ });
+ // Ref to the AbortController of the in-flight config GET so analyze can
+ // cancel it before firing — closes the GET-resolves-after-analyze race
+ // window where the GET's setConfig would clobber analyze-supplied values.
+ const abortConfigRef = useRef(null);
+ useEffect(() => {
+ // Silent — the fallback values are correct for the shipped client, so a
+ // transient network blip doesn't need to toast.
+ //
+ // AbortController guards against a late-resolving config GET clobbering
+ // a server-side bump that the analyze response already applied. The
+ // user can navigate to /importer, fire Analyze faster than the config
+ // GET round-trip, and the GET-vs-analyze race would otherwise overwrite
+ // analyze's setConfig with the server-default fallback values whenever
+ // the GET resolves last. Aborting on unmount + on first analyze closes
+ // the window.
+ const ac = new AbortController();
+ abortConfigRef.current = ac;
+ getImporterConfig({ silent: true, signal: ac.signal }).then((cfg) => {
+ if (ac.signal.aborted || !cfg) return;
+ setConfig({
+ sourceCharLimit: Number.isFinite(cfg.sourceCharLimit) ? cfg.sourceCharLimit : IMPORTER_SOURCE_CHAR_LIMIT_FALLBACK,
+ arcRoles: Array.isArray(cfg.arcRoles) && cfg.arcRoles.length > 0 ? cfg.arcRoles : IMPORTER_ARC_ROLES_FALLBACK,
+ });
+ }).catch((err) => {
+ // Aborts (analyze fires first, unmount) are expected — silent.
+ // Real network/server errors are NOT expected — surface them so a
+ // misconfigured /importer/config doesn't silently fall back to
+ // client defaults forever without operator feedback.
+ if (ac.signal.aborted) return;
+ console.warn(`⚠️ Importer config fetch failed — using client fallbacks: ${err?.message || err}`);
+ });
+ return () => ac.abort();
+ }, []);
+
+ // Review-phase editable state. Held separately from `preview` so the user
+ // can experiment without losing the LLM's original suggestions.
+ //
+ // `canonSelections` holds the clean (no UI flags) LLM-extracted entries.
+ // `selectedCanon` tracks which indexes are checked via parallel Sets — one
+ // per kind — so no UI flag ever touches the canon entry objects that flow
+ // to the commit payload.
+ const [canonSelections, setCanonSelections] = useState({ characters: [], places: [], objects: [] });
+ const [selectedCanon, setSelectedCanon] = useState({ characters: new Set(), places: new Set(), objects: new Set() });
+ const [arcDraft, setArcDraft] = useState(null);
+ const [seasonsDraft, setSeasonsDraft] = useState([]);
+ const [issuesDraft, setIssuesDraft] = useState([]);
+
+ const sourceLen = intake.source.length;
+ const sourceOver = sourceLen > config.sourceCharLimit;
+
+ const intakeValid = useMemo(() =>
+ intake.universeName.trim() && intake.seriesName.trim() && intake.source.trim() && !sourceOver,
+ [intake, sourceOver],
+ );
+
+ const [runAnalyze, analyzing] = useAsyncAction(async () => {
+ // Cancel any still-in-flight config GET — its setConfig would
+ // otherwise resolve AFTER analyze's setConfig (which uses the
+ // server-fresh response.limits/arcRoles) and clobber it with the
+ // potentially-stale on-mount fetch values.
+ abortConfigRef.current?.abort();
+ const payload = {
+ universeName: intake.universeName.trim(),
+ seriesName: intake.seriesName.trim(),
+ contentType: intake.contentType,
+ source: intake.source,
+ };
+ const tic = intake.targetIssueCount === '' ? null : Number(intake.targetIssueCount);
+ if (Number.isFinite(tic) && tic > 0) payload.targetIssueCount = tic;
+ const result = await analyzeImport(payload, { silent: true });
+ if (!result) return null;
+ // Seed the editable Review-phase state from the preview.
+ setPreview(result);
+ const chars = result.canonPreview?.characters || [];
+ const places = result.canonPreview?.places || [];
+ const objects = result.canonPreview?.objects || [];
+ setCanonSelections({ characters: chars, places, objects });
+ // All entries selected by default — track via index Sets, not object flags.
+ setSelectedCanon({
+ characters: new Set(chars.map((_, i) => i)),
+ places: new Set(places.map((_, i) => i)),
+ objects: new Set(objects.map((_, i) => i)),
+ });
+ // arcDraft is sent verbatim as the commit's `arc` field — strip non-arc
+ // keys (e.g. the LLM's top-level `seasons`) at seed time so they can't
+ // smuggle into series.arc if the wire schema tightens.
+ setArcDraft(pickArcFields(result.arcPreview));
+ setSeasonsDraft((result.seasonsPreview || []).map((s) => ({ ...s })));
+ setIssuesDraft((result.issueProposals || []).map((i) => ({ ...i })));
+ // Server may have surfaced an updated source-char limit or arc-roles
+ // list — accept it for the rest of this session if the analyze response
+ // carries them, so the review form stays aligned with whatever the
+ // server is currently enforcing.
+ if (result.limits?.sourceCharLimit) {
+ setConfig((c) => ({ ...c, sourceCharLimit: result.limits.sourceCharLimit }));
+ }
+ if (Array.isArray(result.arcRoles) && result.arcRoles.length > 0) {
+ setConfig((c) => ({ ...c, arcRoles: result.arcRoles }));
+ }
+ setPhase('review');
+ return result;
+ }, { errorMessage: 'Failed to analyze import' });
+
+ const [runCommit, committing] = useAsyncAction(async () => {
+ if (!preview) return null;
+ const payload = {
+ universeId: preview.universe.id,
+ seriesId: preview.series.id,
+ canonSelections: {
+ characters: canonSelections.characters.filter((_, i) => selectedCanon.characters.has(i)),
+ places: canonSelections.places.filter((_, i) => selectedCanon.places.has(i)),
+ objects: canonSelections.objects.filter((_, i) => selectedCanon.objects.has(i)),
+ },
+ arc: pickArcFields(arcDraft),
+ seasons: seasonsDraft,
+ issues: issuesDraft,
+ };
+ const result = await commitImport(payload, { silent: true });
+ if (!result) return null;
+ toast.success(`Imported ${result.createdIssueIds.length} issue${result.createdIssueIds.length === 1 ? '' : 's'} into "${result.series.name}"`);
+ // Surface season-remap warnings so the user sees when an issue landed in
+ // a different season than they (or the LLM) proposed — silent fallback
+ // would otherwise be invisible. Use the server-reported landed season
+ // metadata so the toast names the actual season (S2 — Diaspora), not a
+ // generic "first season" that can lie when seasons are sparsely numbered.
+ if (Array.isArray(result.remappedIssues) && result.remappedIssues.length > 0) {
+ const n = result.remappedIssues.length;
+ const noun = `${n} issue${n === 1 ? '' : 's'}`;
+ const landedSeasonless = result.remappedIssues.every((r) => r.actualSeasonId == null);
+ let msg;
+ if (landedSeasonless) {
+ msg = `${noun} created ungrouped — no seasons exist on this series to land them in.`;
+ } else {
+ // All remapped issues land in the same fallback season today, so
+ // the first entry's metadata describes them all.
+ const sample = result.remappedIssues[0];
+ const seasonLabel = sample.actualSeasonNumber != null
+ ? `S${sample.actualSeasonNumber}${sample.actualSeasonTitle ? ` — ${sample.actualSeasonTitle}` : ''}`
+ : 'the available season';
+ msg = `${noun} landed in ${seasonLabel} — the requested season number didn't exist.`;
+ }
+ toast.warning(msg);
+ }
+ navigate(`/pipeline/series/${result.series.id}`);
+ return result;
+ }, { errorMessage: 'Failed to commit import' });
+
+ return (
+ <div className="max-w-6xl mx-auto p-4 sm:p-6 text-port-text">
+ <header className="mb-6 flex items-start gap-3">
+ <FileInput className="w-7 h-7 text-port-accent mt-1" />
+ <div>
+ <h1 className="text-2xl font-bold">Importer</h1>
+ <p className="text-sm text-port-text-muted mt-1">
+ Reverse-engineer a finished story, novel, screenplay, or comic script into the pipeline.
+ The LLM extracts universe canon, the story arc, and a proposed issue split; you review,
+ edit, and commit.
+ </p>
+ </div>
+ </header>
+
+ {phase === 'intake' && (
+ <IntakeForm
+ intake={intake}
+ setIntake={setIntake}
+ intakeValid={intakeValid}
+ sourceLen={sourceLen}
+ sourceOver={sourceOver}
+ sourceCharLimit={config.sourceCharLimit}
+ analyzing={analyzing}
+ onAnalyze={runAnalyze}
+ />
+ )}
+
+ {phase === 'review' && preview && (
+ <ReviewPanel
+ preview={preview}
+ canonSelections={canonSelections}
+ selectedCanon={selectedCanon}
+ setSelectedCanon={setSelectedCanon}
+ arcDraft={arcDraft}
+ setArcDraft={setArcDraft}
+ seasonsDraft={seasonsDraft}
+ setSeasonsDraft={setSeasonsDraft}
+ issuesDraft={issuesDraft}
+ setIssuesDraft={setIssuesDraft}
+ arcRoles={config.arcRoles}
+ committing={committing}
+ onCommit={runCommit}
+ onBack={() => setPhase('intake')}
+ />
+ )}
+ </div>
+ );
+}
+
+function IntakeForm({ intake, setIntake, intakeValid, sourceLen, sourceOver, sourceCharLimit, analyzing, onAnalyze }) {
+ return (
+ <form
+ className="space-y-4 bg-port-card border border-port-border rounded-lg p-4 sm:p-6"
+ // Swallow default form submission so an accidental Enter in any input
+ // doesn't trigger Analyze — Analyze fires three heavy-tier LLM calls
+ // and accidental triggering costs real money. Tab to the button + Space
+ // is the keyboard path; the round-4 Enter-submits flow was reverted in
+ // round 6 after this cost trade-off was surfaced.
+ onSubmit={(e) => e.preventDefault()}
+ >
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
+ <div>
+ <label htmlFor="importer-universe-name" className="block text-sm font-medium mb-1">
+ Universe Name
+ </label>
+ <input
+ id="importer-universe-name"
+ type="text"
+ value={intake.universeName}
+ onChange={(e) => setIntake({ ...intake, universeName: e.target.value })}
+ placeholder="e.g. Cyberpunk 2099"
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm focus:outline-none focus:border-port-accent"
+ maxLength={200}
+ />
+ <p className="text-xs text-port-text-muted mt-1">Existing universe is matched by name (case-insensitive); otherwise created fresh.</p>
+ </div>
+ <div>
+ <label htmlFor="importer-series-name" className="block text-sm font-medium mb-1">
+ Series Name
+ </label>
+ <input
+ id="importer-series-name"
+ type="text"
+ value={intake.seriesName}
+ onChange={(e) => setIntake({ ...intake, seriesName: e.target.value })}
+ placeholder="e.g. The Choir Awakens"
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm focus:outline-none focus:border-port-accent"
+ maxLength={200}
+ />
+ <p className="text-xs text-port-text-muted mt-1">Series match is scoped to the universe — same name in a different universe creates a fresh series.</p>
+ </div>
+ </div>
+
+ <fieldset>
+ <legend className="block text-sm font-medium mb-2">Content Type</legend>
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
+ {IMPORTER_CONTENT_TYPES.map((ct) => (
+ <label
+ key={ct}
+ className={`flex items-center gap-2 border rounded px-3 py-2 cursor-pointer text-sm ${
+ intake.contentType === ct
+ ? 'border-port-accent bg-port-accent/10'
+ : 'border-port-border hover:border-port-text-muted'
+ }`}
+ >
+ <input
+ type="radio"
+ name="contentType"
+ value={ct}
+ checked={intake.contentType === ct}
+ onChange={() => setIntake({ ...intake, contentType: ct })}
+ className="accent-port-accent"
+ />
+ {CONTENT_TYPE_LABELS[ct]}
+ </label>
+ ))}
+ </div>
+ </fieldset>
+
+ <div>
+ <div className="flex items-center justify-between mb-1">
+ <label htmlFor="importer-source" className="block text-sm font-medium">
+ Source Text
+ </label>
+ <span className={`text-xs ${sourceOver ? 'text-port-error' : 'text-port-text-muted'}`}>
+ {sourceLen.toLocaleString()} / {sourceCharLimit.toLocaleString()} chars
+ </span>
+ </div>
+ <textarea
+ id="importer-source"
+ value={intake.source}
+ onChange={(e) => setIntake({ ...intake, source: e.target.value })}
+ placeholder="Paste the full text here…"
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm font-mono focus:outline-none focus:border-port-accent min-h-[280px]"
+ />
+ {sourceOver && (
+ <p className="text-xs text-port-error mt-1 flex items-center gap-1">
+ <AlertTriangle className="w-3 h-3" />
+ Source exceeds the v1 limit. Trim it or wait for chunked-extraction support.
+ </p>
+ )}
+ </div>
+
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
+ <div>
+ <label htmlFor="importer-target-issue-count" className="block text-sm font-medium mb-1">
+ Target Issue Count (optional)
+ </label>
+ <input
+ id="importer-target-issue-count"
+ type="number"
+ min="1"
+ max="50"
+ value={intake.targetIssueCount}
+ onChange={(e) => setIntake({ ...intake, targetIssueCount: e.target.value })}
+ placeholder="LLM decides"
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm focus:outline-none focus:border-port-accent"
+ />
+ <p className="text-xs text-port-text-muted mt-1">Leave blank to let the LLM split based on natural chapter/issue/act boundaries.</p>
+ </div>
+ </div>
+
+ <div className="flex items-center justify-end gap-2 pt-2">
+ <button
+ type="button"
+ onClick={onAnalyze}
+ disabled={!intakeValid || analyzing}
+ className="bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white px-4 py-2 rounded text-sm font-medium flex items-center gap-2"
+ >
+ {analyzing ? <Loader2 className="w-4 h-4 animate-spin" /> : <FileInput className="w-4 h-4" />}
+ {analyzing ? 'Analyzing…' : 'Analyze'}
+ </button>
+ </div>
+ </form>
+ );
+}
+
+function ReviewPanel({
+ preview, canonSelections,
+ selectedCanon, setSelectedCanon,
+ arcDraft, setArcDraft, seasonsDraft, setSeasonsDraft,
+ issuesDraft, setIssuesDraft,
+ arcRoles,
+ committing, onCommit, onBack,
+}) {
+ const toggleSelected = (kind, idx) => {
+ setSelectedCanon((sc) => {
+ const next = new Set(sc[kind]);
+ if (next.has(idx)) next.delete(idx); else next.add(idx);
+ return { ...sc, [kind]: next };
+ });
+ };
+
+ return (
+ <div className="space-y-6">
+ <div className="bg-port-card border border-port-border rounded-lg p-4 flex items-start gap-3 text-sm">
+ <CheckCircle2 className="w-5 h-5 text-port-success mt-0.5 flex-shrink-0" />
+ <div className="flex-1">
+ <div className="font-medium">
+ {preview.isExistingUniverse ? 'Adding to' : 'Creating new universe'} <span className="text-port-accent">"{preview.universe.name}"</span>
+ {' / '}
+ {preview.isExistingSeries ? 'extending series' : 'new series'} <span className="text-port-accent">"{preview.series.name}"</span>
+ </div>
+ <p className="text-xs text-port-text-muted mt-1">
+ Review the canon below, edit any issue titles or synopses, then click Commit to seed
+ the pipeline. The verbatim prose excerpt for each issue lands in <code>stages.prose.output</code>.
+ </p>
+ </div>
+ <button onClick={onBack} className="text-xs text-port-text-muted hover:text-port-text flex items-center gap-1">
+ <ArrowLeft className="w-3 h-3" /> Back
+ </button>
+ </div>
+
+ <CanonReviewSection
+ title="Characters"
+ kind="characters"
+ entries={canonSelections.characters}
+ selectedIdxs={selectedCanon.characters}
+ onToggle={(idx) => toggleSelected('characters', idx)}
+ renderSubtitle={(e) => e.role || ''}
+ renderBody={(e) => [e.physicalDescription, e.personality, e.background].filter(Boolean).join(' • ')}
+ />
+
+ <CanonReviewSection
+ title="Places"
+ kind="places"
+ entries={canonSelections.places}
+ selectedIdxs={selectedCanon.places}
+ onToggle={(idx) => toggleSelected('places', idx)}
+ renderSubtitle={(e) => e.slugline || ''}
+ renderBody={(e) => e.description || ''}
+ />
+
+ <CanonReviewSection
+ title="Objects"
+ kind="objects"
+ entries={canonSelections.objects}
+ selectedIdxs={selectedCanon.objects}
+ onToggle={(idx) => toggleSelected('objects', idx)}
+ renderSubtitle={() => ''}
+ renderBody={(e) => [e.description, e.significance].filter(Boolean).join(' • ')}
+ />
+
+ <ArcReviewSection arc={arcDraft} setArc={setArcDraft} seasons={seasonsDraft} setSeasons={setSeasonsDraft} />
+
+ <IssuesReviewSection issues={issuesDraft} setIssues={setIssuesDraft} seasons={seasonsDraft} arcRoles={arcRoles} />
+
+ <div className="sticky bottom-4 flex items-center justify-end gap-2 bg-port-card border border-port-border rounded-lg p-3 shadow-lg">
+ <button
+ onClick={onBack}
+ disabled={committing}
+ className="text-port-text-muted hover:text-port-text px-3 py-2 text-sm"
+ >
+ Back to Intake
+ </button>
+ <button
+ onClick={onCommit}
+ disabled={committing || issuesDraft.length === 0}
+ className="bg-port-success hover:bg-port-success/80 disabled:opacity-50 disabled:cursor-not-allowed text-white px-4 py-2 rounded text-sm font-medium flex items-center gap-2"
+ >
+ {committing ? <Loader2 className="w-4 h-4 animate-spin" /> : <CheckCircle2 className="w-4 h-4" />}
+ {committing ? 'Committing…' : `Commit ${issuesDraft.length} issue${issuesDraft.length === 1 ? '' : 's'}`}
+ </button>
+ </div>
+ </div>
+ );
+}
+
+function CanonReviewSection({ title, kind, entries, selectedIdxs, onToggle, renderSubtitle, renderBody }) {
+ if (entries.length === 0) {
+ return (
+ <section className="bg-port-card border border-port-border rounded-lg p-4">
+ <h2 className="text-lg font-semibold mb-2">{title}</h2>
+ <p className="text-xs text-port-text-muted">None extracted from the source.</p>
+ </section>
+ );
+ }
+ const selectedCount = selectedIdxs.size;
+ return (
+ <section className="bg-port-card border border-port-border rounded-lg p-4">
+ <div className="flex items-center justify-between mb-3">
+ <h2 className="text-lg font-semibold">
+ {title} <span className="text-sm font-normal text-port-text-muted">({selectedCount} / {entries.length} selected)</span>
+ </h2>
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
+ {entries.map((entry, idx) => (
+ <label
+ key={`${kind}-${idx}`}
+ className={`flex items-start gap-3 border rounded p-3 cursor-pointer text-sm ${
+ selectedIdxs.has(idx) ? 'border-port-accent bg-port-accent/5' : 'border-port-border opacity-60'
+ }`}
+ >
+ <input
+ type="checkbox"
+ checked={selectedIdxs.has(idx)}
+ onChange={() => onToggle(idx)}
+ className="mt-1 accent-port-accent"
+ />
+ <div className="flex-1 min-w-0">
+ <div className="font-medium truncate">{entry.name || '(unnamed)'}</div>
+ {renderSubtitle(entry) && (
+ <div className="text-xs text-port-text-muted truncate">{renderSubtitle(entry)}</div>
+ )}
+ {renderBody(entry) && (
+ <div className="text-xs text-port-text-muted mt-1 line-clamp-3">{renderBody(entry)}</div>
+ )}
+ </div>
+ </label>
+ ))}
+ </div>
+ </section>
+ );
+}
+
+// Immutably update the element at `idx` in a state-managed list.
+function updateAt(list, setList, idx, patch) {
+ setList(list.map((e, i) => i === idx ? { ...e, ...patch } : e));
+}
+
+function ArcReviewSection({ arc, setArc, seasons, setSeasons }) {
+ if (!arc && seasons.length === 0) {
+ return (
+ <section className="bg-port-card border border-port-border rounded-lg p-4">
+ <h2 className="text-lg font-semibold mb-2">Arc</h2>
+ <p className="text-xs text-port-text-muted">LLM did not produce an arc — series will be created without arc metadata.</p>
+ </section>
+ );
+ }
+ const a = arc || {};
+ return (
+ <section className="bg-port-card border border-port-border rounded-lg p-4 space-y-4">
+ <h2 className="text-lg font-semibold">Arc</h2>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
+ <div>
+ <label htmlFor="arc-logline" className="block text-sm font-medium mb-1">Logline</label>
+ <input
+ id="arc-logline"
+ type="text"
+ value={a.logline || ''}
+ onChange={(e) => setArc({ ...a, logline: e.target.value })}
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm focus:outline-none focus:border-port-accent"
+ />
+ </div>
+ <div>
+ <label htmlFor="arc-shape" className="block text-sm font-medium mb-1">Shape (Vonnegut)</label>
+ <select
+ id="arc-shape"
+ value={a.shape || ''}
+ onChange={(e) => setArc({ ...a, shape: e.target.value || undefined })}
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm focus:outline-none focus:border-port-accent"
+ >
+ <option value="">— pick one —</option>
+ {STORY_SHAPES.map((s) => (
+ <option key={s.id} value={s.id}>{s.label}</option>
+ ))}
+ </select>
+ </div>
+ </div>
+ <div>
+ <label htmlFor="arc-summary" className="block text-sm font-medium mb-1">Summary</label>
+ <textarea
+ id="arc-summary"
+ value={a.summary || ''}
+ onChange={(e) => setArc({ ...a, summary: e.target.value })}
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm focus:outline-none focus:border-port-accent min-h-[120px]"
+ />
+ </div>
+ <div>
+ <label htmlFor="arc-protagonist" className="block text-sm font-medium mb-1">Protagonist Arc</label>
+ <textarea
+ id="arc-protagonist"
+ value={a.protagonistArc || ''}
+ onChange={(e) => setArc({ ...a, protagonistArc: e.target.value })}
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm focus:outline-none focus:border-port-accent min-h-[80px]"
+ />
+ </div>
+ {seasons.length > 0 && (
+ <div>
+ <h3 className="text-sm font-medium mb-2">Seasons ({seasons.length})</h3>
+ <div className="space-y-2">
+ {seasons.map((s, idx) => (
+ <div key={`season-${idx}`} className="border border-port-border rounded p-3">
+ <div className="grid grid-cols-1 sm:grid-cols-[80px_1fr] gap-3">
+ <div>
+ <label htmlFor={`season-${idx}-number`} className="block text-xs font-medium mb-1">#</label>
+ <input
+ id={`season-${idx}-number`}
+ type="number"
+ min="1"
+ max="99"
+ value={s.number ?? ''}
+ onChange={(e) => updateAt(seasons, setSeasons, idx, {
+ // Empty input -> undefined so the service's auto-assign
+ // path picks the next free number. Avoids `Number('') = 0`
+ // landing in state and failing the `>= 1` gate at commit.
+ number: e.target.value === '' ? undefined : Number(e.target.value),
+ })}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-sm"
+ />
+ </div>
+ <div>
+ <label htmlFor={`season-${idx}-title`} className="block text-xs font-medium mb-1">Title</label>
+ <input
+ id={`season-${idx}-title`}
+ type="text"
+ value={s.title || ''}
+ onChange={(e) => updateAt(seasons, setSeasons, idx, { title: e.target.value })}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-sm"
+ />
+ </div>
+ </div>
+ <label htmlFor={`season-${idx}-synopsis`} className="block text-xs font-medium mb-1 mt-2">Synopsis</label>
+ <textarea
+ id={`season-${idx}-synopsis`}
+ value={s.synopsis || ''}
+ onChange={(e) => updateAt(seasons, setSeasons, idx, { synopsis: e.target.value })}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-sm min-h-[60px]"
+ />
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </section>
+ );
+}
+
+function IssuesReviewSection({ issues, setIssues, seasons, arcRoles }) {
+ if (issues.length === 0) {
+ return (
+ <section className="bg-port-card border border-port-border rounded-lg p-4">
+ <h2 className="text-lg font-semibold mb-2">Proposed Issues</h2>
+ <p className="text-xs text-port-error">No issues proposed — the LLM did not split the source. Re-run analyze.</p>
+ </section>
+ );
+ }
+ // Drop seasons with no finite `number` — the season-number input lets
+ // the user clear the field (storing `undefined`) and `String(undefined)`
+ // would otherwise produce `value: "undefined"`, which onChange would
+ // coerce to NaN and Zod would later reject as an opaque commit failure.
+ // The dropdown should only offer addressable seasons; user can pick the
+ // "(first season)" fallback for an issue while they fix the numberless
+ // season's number in the Arc section.
+ const numberedSeasons = seasons.filter((s) => Number.isFinite(s.number));
+ const seasonOptions = numberedSeasons.length > 1
+ ? [
+ { value: '', label: '(first season)' },
+ ...numberedSeasons.map((s) => ({ value: String(s.number), label: `S${s.number} — ${s.title || ''}` })),
+ ]
+ : null;
+ return (
+ <section className="bg-port-card border border-port-border rounded-lg p-4">
+ <h2 className="text-lg font-semibold mb-3">Proposed Issues ({issues.length})</h2>
+ <div className="space-y-3">
+ {issues.map((it, idx) => (
+ <div key={`issue-${idx}`} className="border border-port-border rounded p-3">
+ <div className="grid grid-cols-1 sm:grid-cols-[80px_1fr_140px_140px] gap-3">
+ <div>
+ <label htmlFor={`iss-${idx}-pos`} className="block text-xs font-medium mb-1">Pos</label>
+ <input
+ id={`iss-${idx}-pos`}
+ type="number"
+ min="1"
+ max="9999"
+ // Display empty when state is undefined so the field
+ // reflects state honestly: a previously-rendered idx+1
+ // would lie to the user about what the commit payload
+ // sends. The "auto" placeholder signals the service
+ // will pick the next free position on commit.
+ value={it.arcPosition ?? ''}
+ placeholder="auto"
+ onChange={(e) => updateAt(issues, setIssues, idx, {
+ // Empty input -> undefined so the service's auto-assign
+ // path picks the next free position. Avoids `Number('') = 0`
+ // landing in state and failing the `>= 1` gate at commit.
+ arcPosition: e.target.value === '' ? undefined : Number(e.target.value),
+ })}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-sm"
+ />
+ </div>
+ <div>
+ <label htmlFor={`iss-${idx}-title`} className="block text-xs font-medium mb-1">Title</label>
+ <input
+ id={`iss-${idx}-title`}
+ type="text"
+ value={it.title || ''}
+ onChange={(e) => updateAt(issues, setIssues, idx, { title: e.target.value })}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-sm"
+ />
+ </div>
+ <div>
+ <label htmlFor={`iss-${idx}-role`} className="block text-xs font-medium mb-1">Arc Role</label>
+ <select
+ id={`iss-${idx}-role`}
+ value={it.arcRole || ''}
+ onChange={(e) => updateAt(issues, setIssues, idx, { arcRole: e.target.value || undefined })}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-sm"
+ >
+ <option value="">—</option>
+ {arcRoles.map((r) => <option key={r} value={r}>{r}</option>)}
+ </select>
+ </div>
+ {seasonOptions ? (
+ <div>
+ <label htmlFor={`iss-${idx}-season`} className="block text-xs font-medium mb-1">Season</label>
+ <select
+ id={`iss-${idx}-season`}
+ value={it.seasonNumber == null ? '' : String(it.seasonNumber)}
+ onChange={(e) => updateAt(issues, setIssues, idx, {
+ seasonNumber: e.target.value === '' ? undefined : Number(e.target.value),
+ })}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-sm"
+ >
+ {seasonOptions.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
+ </select>
+ </div>
+ ) : <div />}
+ </div>
+ <label htmlFor={`iss-${idx}-syn`} className="block text-xs font-medium mb-1 mt-2">Synopsis</label>
+ <textarea
+ id={`iss-${idx}-syn`}
+ value={it.synopsis || ''}
+ onChange={(e) => updateAt(issues, setIssues, idx, { synopsis: e.target.value })}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-sm min-h-[50px]"
+ />
+ <div className="text-xs text-port-text-muted mt-1">
+ Prose excerpt: {(it.proseExcerpt || '').length.toLocaleString()} chars (verbatim from source — kept as-is)
+ </div>
+ </div>
+ ))}
+ </div>
+ </section>
+ );
+}
diff --git a/client/src/services/apiImporter.js b/client/src/services/apiImporter.js
new file mode 100644
index 0000000000..86367a4428
--- /dev/null
+++ b/client/src/services/apiImporter.js
@@ -0,0 +1,28 @@
+import { request } from './apiCore.js';
+
+// Per-content-type radio values mirror server/lib/validation.js
+// IMPORTER_CONTENT_TYPES; UI strings stay client-side.
+export const IMPORTER_CONTENT_TYPES = ['short-story', 'novel', 'screenplay', 'comic-script'];
+
+// Initial fallback for the source-char limit + arc-role list. These are the
+// values shipped with this client; on mount the Importer page fetches
+// `/importer/config` and overwrites them with whatever the server reports —
+// so a server-side bump (or a chunked-extraction follow-up that lifts the
+// cap) automatically reaches the UI without a client redeploy. Treat these
+// as last-resort defaults if the config call fails or is in flight.
+export const IMPORTER_SOURCE_CHAR_LIMIT_FALLBACK = 200_000;
+export const IMPORTER_ARC_ROLES_FALLBACK = ['pilot', 'complication', 'midpoint', 'b-plot', 'all-is-lost', 'finale'];
+
+export const getImporterConfig = (options = {}) => request('/importer/config', options);
+
+export const analyzeImport = (payload, options = {}) => request('/importer/analyze', {
+ method: 'POST',
+ body: JSON.stringify(payload),
+ ...options,
+});
+
+export const commitImport = (payload, options = {}) => request('/importer/commit', {
+ method: 'POST',
+ body: JSON.stringify(payload),
+ ...options,
+});
diff --git a/data.sample/prompts/stage-config.json b/data.sample/prompts/stage-config.json
index 98b2183e3b..9f4c0ffa96 100644
--- a/data.sample/prompts/stage-config.json
+++ b/data.sample/prompts/stage-config.json
@@ -262,6 +262,27 @@
"model": "default",
"returnsJson": true,
"variables": []
+ },
+ "importer-canon-extract": {
+ "name": "Importer — Universe Canon Extraction",
+ "description": "Reverse-engineer characters / places / objects from a finished short story / novel / screenplay / comic script. Runs at `heavy` tier — source can be book-length.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": []
+ },
+ "importer-arc-extract": {
+ "name": "Importer — Series Arc Extraction",
+ "description": "Extract series-level arc (logline / summary / themes / protagonistArc / shape) plus 1–5 seasons from a finished work. Persists into `series.arc` + `series.seasons[]`.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": []
+ },
+ "importer-issue-proposal": {
+ "name": "Importer — Issue Proposal",
+ "description": "Split a finished work into PortOS pipeline issues with titles + arcPosition + arcRole + verbatim prose excerpts. Honors source-marked issue / chapter / volume headers.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": []
}
}
}
diff --git a/data.sample/prompts/stages/importer-arc-extract.md b/data.sample/prompts/stages/importer-arc-extract.md
new file mode 100644
index 0000000000..49be81217a
--- /dev/null
+++ b/data.sample/prompts/stages/importer-arc-extract.md
@@ -0,0 +1,81 @@
+# Importer — Series Arc Extraction
+
+You are a senior story editor reverse-engineering an existing finished work into the **series-level story arc** that PortOS's pipeline persists as `series.arc` + `series.seasons[]`. The source is complete — you are not pitching new directions, you are describing the spine that's already in the text.
+
+## Source context
+
+- **Series name:** {{seriesName}}
+- **Content type:** {{contentType}}
+
+## Story shape (Vonnegut)
+
+Pick the single Vonnegut fortune curve that best describes the protagonist's trajectory across the whole work. Allowed ids (return exactly one in the `shape` field):
+
+- **`rags-to-riches`** — sustained rise. Protagonist starts low, ends high, climb is monotonic with a small dip near the climax.
+- **`tragedy`** — sustained fall. Starts high, ends low. The reverse curve.
+- **`man-in-hole`** — fall then rise. Things get bad in the middle, but the protagonist climbs back out — ends roughly even with or above the start. Most genre fiction lives here.
+- **`icarus`** — rise then fall. Triumph followed by collapse. Ends low.
+- **`cinderella`** — rise, fall, rise. Two peaks separated by a midpoint crash.
+- **`oedipus`** — fall, rise, fall. The protagonist hauls themselves up only to be undone again.
+- **`boy-meets-girl`** — relationship-arc variant: meet, lose, reunite. Three beats.
+- **`creation-story`** — slow rising arc from nothing toward order or birth. Often ensemble; less personal than rags-to-riches.
+
+Be specific: do not default to `man-in-hole` because it's the most common. If the ending is decisively down, that's `tragedy` or `icarus`; if it's a fall-then-rise but the rise is partial, it's still `man-in-hole`.
+
+## Per-content-type guidance
+
+{{#isShortStory}}
+Short stories almost always trace a single shape with one major turn. The whole story fits in one issue — your `seasons` array should typically be a single entry (`number: 1`) covering the entire piece, unless the story has explicit part breaks.
+{{/isShortStory}}
+{{#isNovel}}
+Novels typically divide into 2–4 acts or volumes. Use part / book breaks if the source has them ("Book One", "Part II"). Otherwise look for the major turning points where the protagonist's fortune pivots — those are season boundaries. 2–4 seasons is the usual range.
+{{/isNovel}}
+{{#isScreenplay}}
+Screenplays are single-episode by default — typically one season with one episode. If the screenplay carries explicit act-break headers (`ACT ONE`, `ACT TWO`, `ACT THREE`) and feels like multiple-episode material, you may split into multiple seasons; otherwise keep it as one.
+{{/isScreenplay}}
+{{#isComicScript}}
+Comic scripts mark issues / volumes explicitly with `ISSUE N` or `VOLUME N` headers. If the source uses those, mirror them as seasons (one season per volume). If unmarked, assume ~22 script pages per issue and group into ~6-issue volumes — but only use that as a fallback when explicit headers are missing.
+{{/isComicScript}}
+
+## How to shape the arc
+
+1. **`logline`** — one sentence pitching the WHOLE arc (not the opening). What is this series about, in 25 words or fewer?
+2. **`summary`** — ~300–500 words. The act structure across the whole work: where the protagonist starts, the major turns, where they land. Specific enough that someone planning a sequel could tell whether their idea fits the existing arc.
+3. **`themes`** — 2–5 short tags. The recurring concerns — `betrayal`, `legacy`, `the cost of memory`, `class & inheritance`. Keep each tag short (≤80 chars). These should be derivable from the text, not aspirational.
+4. **`protagonistArc`** — 1–2 paragraphs. Character growth across the whole work: starting moral/emotional state → ending state, and the pivot that drove the change.
+5. **`shape`** — one of the eight Vonnegut shape ids listed above.
+6. **`seasons`** — break the work into 1–5 seasons. For each:
+ - **`number`** — 1-indexed, contiguous.
+ - **`title`** — short noun phrase. Use the source's part/volume/act titles verbatim if present, else distill a 2–5 word title from the season's content.
+ - **`logline`** — one sentence; what changes in this season.
+ - **`synopsis`** — 1–2 paragraphs covering this season's major beats.
+ - **`endingHook`** — the image or line that pulls the audience into the next season. Empty string for the final season.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
+
+```json
+{
+ "logline": "string",
+ "summary": "string (~500 words, escape newlines as \\n)",
+ "protagonistArc": "string",
+ "themes": ["string"],
+ "shape": "rags-to-riches | tragedy | man-in-hole | icarus | cinderella | oedipus | boy-meets-girl | creation-story",
+ "seasons": [
+ {
+ "number": 1,
+ "title": "string",
+ "logline": "string",
+ "synopsis": "string",
+ "endingHook": "string"
+ }
+ ]
+}
+```
+
+## Source — {{contentType}}
+
+```
+{{source}}
+```
diff --git a/data.sample/prompts/stages/importer-canon-extract.md b/data.sample/prompts/stages/importer-canon-extract.md
new file mode 100644
index 0000000000..3d6e3433c1
--- /dev/null
+++ b/data.sample/prompts/stages/importer-canon-extract.md
@@ -0,0 +1,98 @@
+# Importer — Universe Canon Extraction
+
+You are a senior story editor reverse-engineering an existing finished work into the **canonical entities** (characters, places, objects) that downstream renderers and continuity passes need. The source is a complete short story, novel, screenplay, or comic script — you are not inventing anything. Your job is to read carefully, list what's actually there, and write rich enough metadata that an image-gen pipeline could render each entry without re-reading the source.
+
+## Source context
+
+- **Universe name:** {{universeName}}
+- **Series name:** {{seriesName}}
+- **Content type:** {{contentType}}
+
+{{{existingCanonBlock}}}
+
+## Per-content-type guidance
+
+{{#isShortStory}}
+Short stories are dense — every named entity is intentional. Extract every named character with a speaking role or repeated mention, every distinct setting with sensory detail in the prose, and any object that drives a plot beat or recurs across scenes. A cast of 3–8, 2–5 places, 0–4 objects is typical.
+{{/isShortStory}}
+{{#isNovel}}
+Novels carry more named entities than fit; favor recurring or POV-shifted characters over walk-ons, distinct settings over fly-by locations, and only objects with explicit narrative weight (MacGuffins, heirlooms, repeated motifs). 8–25 characters, 5–15 places, 0–10 objects is typical.
+{{/isNovel}}
+{{#isScreenplay}}
+Characters are introduced in ALL CAPS on first appearance — use that as the canonical list. Sluglines (`INT./EXT. LOCATION — TIME`) define places — group variants of the same location into one entry (e.g. `KITCHEN` + `KITCHEN — DAY` + `KITCHEN — NIGHT` → one place "Kitchen"). Objects are anything the action lines describe with specificity.
+{{/isScreenplay}}
+{{#isComicScript}}
+Comic scripts mark characters in ALL CAPS dialogue cues and panel descriptions. Settings appear in panel-description preambles (`PAGE 4 / PANEL 1: ROOFTOP — NIGHT`). Objects worth canonical entries are those a panel description lingers on (props, gadgets, symbolic items).
+{{/isComicScript}}
+
+## What to extract
+
+### Characters
+For each named character with a speaking role, POV, or recurring appearance:
+- **`name`** — canonical form (Title Case if a person, ALL CAPS only if the work uses ALL CAPS as a stylistic choice).
+- **`aliases`** — nicknames, code names, full-name variants the work uses interchangeably.
+- **`role`** — short noun phrase: `protagonist`, `antagonist`, `mentor`, `ensemble — engineer`, etc.
+- **`physicalDescription`** — 1–3 sentences. **Visual** details only: build, hair, distinguishing marks, typical wardrobe. Synthesize across appearances; if the source never describes them physically, leave empty (do NOT invent).
+- **`personality`** — 1–2 sentences capturing voice / temperament / motivation, distilled from how they act + speak.
+- **`background`** — 1–2 sentences of backstory mentioned in the source (occupation, origin, relationships). Leave empty if not stated.
+- **`firstAppearance`** — short quote or location reference ("Ch. 1, opening scene" / "Page 3, panel 2") so future continuity passes can find them.
+
+### Places (settings)
+For each distinct location with sensory detail or repeated scenes:
+- **`name`** — short evocative noun phrase ("The Rooftop", "Anna's Kitchen").
+- **`slugline`** — `INT./EXT. LOCATION — TIME` if the source uses sluglines, else synthesize one ("INT. KITCHEN — NIGHT").
+- **`description`** — 1–3 sentences naming what's visible (architecture, props, atmosphere).
+- **`palette`** — color shorthand if implied by the prose ("warm tungsten, brass, deep brown").
+- **`era`** — temporal cue if relevant ("1970s suburban", "near-future cyberpunk").
+- **`intExt`** — `"INT"` or `"EXT"`. Omit the key entirely if mixed/unclear (do NOT emit the literal string `"null"` — the sanitizer drops unknown enum values).
+- **`timeOfDay`** — one of `"dawn"`, `"day"`, `"dusk"`, `"night"`. Omit the key entirely if unknown.
+
+### Objects
+For each object with narrative weight (MacGuffins, recurring symbols, plot-critical items):
+- **`name`** — canonical name ("The Lockbox", "Dad's Watch").
+- **`description`** — 1–2 sentences. Visual + functional.
+- **`significance`** — 1 sentence on why it matters to the story.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
+
+```json
+{
+ "characters": [
+ {
+ "name": "string",
+ "aliases": ["string"],
+ "role": "string",
+ "physicalDescription": "string",
+ "personality": "string",
+ "background": "string",
+ "firstAppearance": "string"
+ }
+ ],
+ "places": [
+ {
+ "name": "string",
+ "slugline": "string",
+ "description": "string",
+ "palette": "string",
+ "era": "string",
+ "intExt": "INT",
+ "timeOfDay": "dawn"
+ }
+ ],
+ "objects": [
+ {
+ "name": "string",
+ "description": "string",
+ "significance": "string"
+ }
+ ]
+}
+```
+
+## Source — {{contentType}}
+
+```
+{{source}}
+```
diff --git a/data.sample/prompts/stages/importer-issue-proposal.md b/data.sample/prompts/stages/importer-issue-proposal.md
new file mode 100644
index 0000000000..74dbe02748
--- /dev/null
+++ b/data.sample/prompts/stages/importer-issue-proposal.md
@@ -0,0 +1,82 @@
+# Importer — Issue Proposal
+
+You are a senior story editor segmenting an existing finished work into PortOS pipeline **issues** (one issue = one comic issue or one TV episode). The source already contains the story; your job is to propose a clean split, name each issue, and pick the verbatim prose excerpt that becomes that issue's `stages.prose.output`.
+
+## Source context
+
+- **Series name:** {{seriesName}}
+- **Content type:** {{contentType}}
+- **Arc summary (already extracted):**
+
+```
+{{arcSummary}}
+```
+
+{{#isUserRequestedCount}}
+- **User-requested issue count:** {{targetIssueCount}} — produce exactly this many issues, splitting the source proportionally.
+{{/isUserRequestedCount}}
+{{^isUserRequestedCount}}
+{{#targetIssueCount}}
+- **Target issue count (default for this content type):** {{targetIssueCount}} — use this as a starting point; the per-content-type guidance below may override it (e.g. a novel with explicit chapters).
+{{/targetIssueCount}}
+{{^targetIssueCount}}
+- **Issue count:** LLM's choice — see per-content-type guidance below.
+{{/targetIssueCount}}
+{{/isUserRequestedCount}}
+
+## Per-content-type guidance for splitting
+
+{{#isShortStory}}
+A short story is typically **one issue**. Unless `targetIssueCount` is set to something larger, return exactly one issue covering the entire piece. The `proseExcerpt` is the whole source verbatim.
+{{/isShortStory}}
+{{#isNovel}}
+Novels usually map to **one issue per chapter** if chapters are short (≤3000 words), or chapter-pair groupings if chapters are longer. Honor the author's chapter breaks — they're the strongest structural signal. Aim for 6–15 issues for a typical novel.
+{{/isNovel}}
+{{#isScreenplay}}
+A standard screenplay is **one episode** (one issue). If the screenplay explicitly contains `ACT ONE` / `ACT TWO` / `ACT THREE` breaks AND the user has set `targetIssueCount > 1`, split on act breaks; otherwise return one issue.
+{{/isScreenplay}}
+{{#isComicScript}}
+Comic scripts mark issues with `ISSUE N` or `#N` or similar headers — honor those exactly. If the script is unmarked, group every ~22 pages into one issue. Page markers (`PAGE 1`, `PAGE 2`, ...) define the boundaries.
+{{/isComicScript}}
+
+## What to write per issue
+
+For each issue:
+- **`title`** — short, evocative (3–8 words). Use the source's chapter / issue / act title verbatim if present, else distill from the issue's content. Do NOT use generic titles like "Issue 1" or "Chapter 3".
+- **`arcPosition`** — 1-indexed integer. Contiguous (1, 2, 3, …) — do not skip numbers.
+- **`arcRole`** — one of `pilot`, `complication`, `midpoint`, `b-plot`, `all-is-lost`, `finale`. Use:
+ - `pilot` — the opening issue that establishes the world + protagonist.
+ - `complication` — issues that escalate the conflict.
+ - `midpoint` — the mid-arc tonal pivot (often a false victory or false defeat).
+ - `b-plot` — issues that develop secondary characters or subplots.
+ - `all-is-lost` — the lowest point before the finale.
+ - `finale` — the closing issue.
+ Use roles sparingly — a 12-issue series might have one `pilot`, one `midpoint`, one `all-is-lost`, one `finale`, and the rest `complication` / `b-plot`. Omit `arcRole` (don't return the field) if no role fits cleanly.
+- **`logline`** — one sentence. What changes in this issue.
+- **`synopsis`** — 1 paragraph. The major beats of this issue.
+- **`proseExcerpt`** — the **verbatim** contiguous span of the source text that belongs to this issue. This becomes the issue's `stages.prose.output` and feeds the downstream comicScript / teleplay / storyboards renderers. **Copy exact characters from the source — no paraphrasing, no summarization, no insertion of headers I didn't write.** The excerpt may be long (up to 500K characters per issue); err on the side of including more rather than less, since downstream stages can re-process.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
+
+```json
+{
+ "issues": [
+ {
+ "title": "string",
+ "arcPosition": 1,
+ "arcRole": "pilot",
+ "logline": "string",
+ "synopsis": "string",
+ "proseExcerpt": "string (verbatim from source)"
+ }
+ ]
+}
+```
+
+## Source — {{contentType}}
+
+```
+{{source}}
+```
diff --git a/scripts/migrations/015-importer-stage-prompts.js b/scripts/migrations/015-importer-stage-prompts.js
new file mode 100644
index 0000000000..7c887f888d
--- /dev/null
+++ b/scripts/migrations/015-importer-stage-prompts.js
@@ -0,0 +1,113 @@
+/**
+ * Seed the three Create-Suite Importer stage prompts AND their
+ * corresponding `prompts/stage-config.json` entries into existing installs.
+ *
+ * `scripts/setup-data.js`'s `ensureSampleContent` copies missing prompt
+ * files on next run, so the .md copy is technically a no-op breadcrumb on
+ * fresh installs. The stage-config entries however are merged via
+ * `JSON_MERGE_TARGETS` in setup-data — but only on fresh setup. Existing
+ * installs that upgrade by running migrations alone (without re-running
+ * setup-data) need the merge applied here, otherwise `prompts.getStage()`
+ * won't know about the importer stages, the configured `model: "heavy"`
+ * tier won't be applied, and the importer LLM calls will silently fall
+ * back to whatever the active provider's default model is.
+ */
+
+import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
+import { dirname, join } from 'path';
+
+const FILENAMES = [
+ 'importer-canon-extract.md',
+ 'importer-arc-extract.md',
+ 'importer-issue-proposal.md',
+];
+
+const STAGE_KEYS = [
+ 'importer-canon-extract',
+ 'importer-arc-extract',
+ 'importer-issue-proposal',
+];
+
+export default {
+ async up({ rootDir }) {
+ let copied = 0;
+ let present = 0;
+ let skipped = 0;
+ // Ensure the destination directory exists — sparse installs that
+ // never ran setup-data for the prompts subtree would otherwise hit
+ // ENOENT on every copy below and end up with a wall of warnings
+ // and no prompts seeded.
+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ await mkdir(stagesDir, { recursive: true });
+ for (const filename of FILENAMES) {
+ const dataPath = join(stagesDir, filename);
+ const samplePath = join(rootDir, 'data.sample', 'prompts', 'stages', filename);
+
+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
+ if (exists) { present++; continue; }
+
+ // Validate the source exists before copy — if `data.sample/` was
+ // trimmed in a later release or this migration runs against a sparse
+ // checkout, we'd otherwise abort the whole migration batch mid-loop.
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ importer-stage-prompts: sample missing for ${filename} — skipping`);
+ skipped++;
+ continue;
+ }
+
+ try {
+ await copyFile(samplePath, dataPath);
+ copied++;
+ console.log(`✅ seeded ${filename}`);
+ } catch (err) {
+ // Don't abort the batch — log and keep going so the other prompts
+ // still land. The operator sees exactly which one failed.
+ console.warn(`⚠️ importer-stage-prompts: copy failed for ${filename}: ${err.message}`);
+ skipped++;
+ }
+ }
+ console.log(`📝 importer prompts: ${copied} copied, ${present} already present, ${skipped} skipped`);
+
+ // Stage-config: merge importer entries into the installed config, or
+ // create the file from scratch (with just the importer entries) when
+ // the install has none. Without this fallback the migration would
+ // leave a sparse install in a half-seeded state — .md files copied
+ // above but no stage-config entries, so `getStage()` can't resolve
+ // them and the importer LLM calls fail or fall back to a wrong tier.
+ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ const sampleConfigPath = join(rootDir, 'data.sample', 'prompts', 'stage-config.json');
+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);
+ if (!sampleConfigExists) {
+ console.warn('⚠️ importer-stage-prompts: data.sample stage-config.json missing — cannot resolve importer entries; 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;
+ let preserved = 0;
+ for (const key of STAGE_KEYS) {
+ if (installed.stages[key]) { preserved++; continue; }
+ if (!sample?.stages?.[key]) {
+ console.warn(`⚠️ importer-stage-prompts: sample stage-config missing ${key} — skipping`);
+ continue;
+ }
+ installed.stages[key] = sample.stages[key];
+ added++;
+ }
+ if (added > 0) {
+ await mkdir(dirname(installedConfigPath), { recursive: true });
+ await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');
+ }
+ const action = installedExists ? 'merged' : 'created';
+ console.log(`📝 importer stage-config (${action}): ${added} added, ${preserved} already present`);
+ } catch (err) {
+ console.warn(`⚠️ importer-stage-prompts: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/server/index.js b/server/index.js
index 3cc5d9e46f..fe80723838 100644
--- a/server/index.js
+++ b/server/index.js
@@ -94,6 +94,7 @@ import { initComicPagesFilenameHook } from './services/pipeline/comicPagesFilena
import { initStoryboardsFilenameHook } from './services/pipeline/storyboardsFilenameHook.js';
import { initSeasonCoverFilenameHook } from './services/pipeline/seasonCoverFilenameHook.js';
import pipelineRoutes from './routes/pipeline.js';
+import importerRoutes from './routes/importer.js';
import { initMediaJobQueue } from './services/mediaJobQueue/index.js';
import { recoverInFlightProjects } from './services/creativeDirector/recovery.js';
import imageVideoModelsRoutes from './routes/imageVideoModels.js';
@@ -374,6 +375,7 @@ app.use('/api/creative-director', creativeDirectorRoutes);
app.use('/api/writers-room', writersRoomRoutes);
app.use('/api/universe-builder', universeBuilderRoutes);
app.use('/api/pipeline', pipelineRoutes);
+app.use('/api/importer', importerRoutes);
app.use('/api/image-video/models', imageVideoModelsRoutes);
app.use('/api/loras', lorasRoutes);
// AUTOMATIC1111-compatible surface for tailnet clients — gated by
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 7aacb2aea4..386f98864b 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -19,6 +19,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.media.timeline', path: '/media/timeline', label: 'Timeline', section: 'Create', aliases: ['timeline', 'video-timeline', 'editor'], keywords: ['edit', 'trim', 'composite', 'stitch', 'cut', 'compose'] },
{ id: 'nav.media.models', path: '/media/models', label: 'Media Models', section: 'Create', aliases: ['media-models', 'image-models', 'video-models', 'huggingface'], keywords: ['hf cache', 'model storage', 'disk'] },
{ id: 'nav.create.universe-builder', path: '/universe-builder', label: 'Universe Builder', section: 'Create', aliases: ['universe-builder', 'worldbuilder', 'worldbuild', 'world', 'universe', 'lore', 'universe-canon', 'canon'], keywords: ['style template', 'sci-fi', 'fantasy', 'concept art', 'batch render', 'variations', 'characters', 'settings', 'objects', 'canon entries'] },
+ { id: 'nav.create.importer', path: '/importer', label: 'Importer', section: 'Create', aliases: ['importer', 'import'], keywords: ['paste', 'screenplay', 'novel', 'short story', 'comic script', 'analyze', 'reverse-engineer', 'extract'] },
{ 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.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'] },
diff --git a/server/lib/validation.js b/server/lib/validation.js
index a07f0ab16f..1ec7780229 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -4,6 +4,7 @@ import { ASPECT_RATIOS, QUALITIES, PROJECT_STATUSES, SCENE_STATUSES } from './cr
import { WORK_KINDS, WORK_STATUSES, ANALYSIS_KINDS } from './writersRoomPresets.js';
import { ALL_STYLE_IDS, STYLE_ID } from './writersRoomStylePresets.js';
import { BIBLE_LIMITS } from './storyBible.js';
+import { ARC_SHAPE_IDS, ARC_ROLES } from './storyArc.js';
// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total
// pixels. Mirror the ceiling for every image-gen route. Local mflux can
@@ -1055,3 +1056,113 @@ export const creativeDirectorSceneUpdateSchema = z.object({
sampledAt: z.string().optional(),
}).nullable().optional(),
}).strict();
+
+// ---------------------------------------------------------------------------
+// Create Suite — Importer.
+//
+// The importer takes a finished prose/script source and reverse-engineers
+// universe canon + series arc + issue split. Zod here enforces the wire
+// shape; the heavy validation (entry-level field caps, kind-specific
+// trimming) lives in storyBible.sanitizeBibleList + storyArc.sanitizeArc so
+// commit-side mutations always run through the same sanitizers the rest of
+// the pipeline uses. The canon/arc/issue entries below therefore use
+// `.passthrough()` — we want every field the LLM picked to reach the
+// sanitizer, not get stripped at the schema gate.
+// ---------------------------------------------------------------------------
+
+export const IMPORTER_CONTENT_TYPES = Object.freeze([
+ 'short-story', 'novel', 'screenplay', 'comic-script',
+]);
+
+// Hard ceiling at the schema layer; the orchestrator enforces a tighter
+// 200K business-rule limit and returns a friendlier error. The 5MB ceiling
+// here mirrors writersRoomDraftSaveSchema.
+const importerSourceField = z.string().min(1).max(5_000_000);
+
+export const importerAnalyzeSchema = z.object({
+ universeName: z.string().trim().min(1).max(200),
+ seriesName: z.string().trim().min(1).max(200),
+ contentType: z.enum(IMPORTER_CONTENT_TYPES),
+ source: importerSourceField,
+ // UI sends `''` for "no override picked"; coerce to undefined so the
+ // server's `await getProviderById(undefined)` short-circuit kicks in.
+ providerOverride: z.preprocess(
+ (v) => (v === '' ? undefined : v),
+ z.string().trim().max(120).optional(),
+ ),
+ targetIssueCount: z.number().int().min(1).max(50).optional(),
+}).strict();
+
+// Single canon-entry schema — every per-kind sanitizer (character / place /
+// object) only requires a `name`; `.passthrough()` keeps every LLM-emitted
+// field (firstAppearance, slugline, palette, …) for the sanitizer.
+const importerCanonEntry = z.object({
+ name: z.string().trim().min(1).max(BIBLE_LIMITS.NAME_MAX),
+}).passthrough();
+
+// Arc shape — every field optional so a partial preview (user cleared some
+// fields in the Review step) still validates; sanitizeArc fills in the
+// shape-level defaults.
+const importerArcShape = z.object({
+ logline: z.string().max(500).optional(),
+ summary: z.string().max(8000).optional(),
+ protagonistArc: z.string().max(4000).optional(),
+ themes: z.array(z.string().max(100)).max(20).optional(),
+ shape: z.enum(ARC_SHAPE_IDS).optional(),
+}).passthrough();
+
+// Season + issue entries used inside the commit payload. Seasons stay
+// permissive (sanitizer normalizes numbers + ids + status); issues need
+// `title` for createIssue but otherwise let the orchestrator decide.
+const importerSeasonEntry = z.object({
+ number: z.number().int().min(1).max(99).optional(),
+ title: z.string().trim().max(200).optional(),
+ logline: z.string().max(500).optional(),
+ synopsis: z.string().max(4000).optional(),
+ endingHook: z.string().max(1000).optional(),
+ episodeCountTarget: z.number().int().min(0).max(999).optional(),
+}).passthrough();
+
+const importerIssueEntry = z.object({
+ title: z.string().trim().min(1).max(300),
+ // Optional — the service's commitImport auto-assigns the next free
+ // arcPosition when omitted (mirrors the season.number auto-assign).
+ // The wire previously required this, which orphaned the service-side
+ // auto-assign as dead code for HTTP callers; making it optional puts
+ // wire + service on one contract and keeps the auto-assign reachable.
+ arcPosition: z.number().int().min(1).max(9999).optional(),
+ // The LLM may legitimately omit arcRole on a B-plot-light volume; gate
+ // the enum but allow the field to be missing. Wrap with z.preprocess so
+ // an empty string from the UI's "clear" affordance maps to undefined.
+ arcRole: z.preprocess(
+ (v) => (v === '' || v == null ? undefined : v),
+ z.enum(ARC_ROLES).optional(),
+ ),
+ // Season the issue belongs to. Optional — orchestrator picks the first
+ // season when omitted on a multi-season import.
+ seasonNumber: z.number().int().min(1).max(99).optional(),
+ logline: z.string().max(500).optional(),
+ synopsis: z.string().max(4000).optional(),
+ // 500K cap matches the issue's stages.prose.output limit so a long
+ // novel chapter can land verbatim. Optional — the LLM may omit the
+ // excerpt on some issues. When present, must be non-empty + non-whitespace
+ // so it doesn't seed prose.output with whitespace and mark the stage
+ // `ready` misleadingly.
+ proseExcerpt: z.string().min(1).max(500_000).refine(
+ (s) => s.trim().length > 0,
+ { message: 'proseExcerpt must contain non-whitespace content' },
+ ).optional(),
+}).passthrough();
+
+export const importerCommitSchema = z.object({
+ universeId: z.string().trim().min(1).max(120),
+ seriesId: z.string().trim().min(1).max(120),
+ canonSelections: z.object({
+ characters: z.array(importerCanonEntry).max(BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX).default([]),
+ places: z.array(importerCanonEntry).max(BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX).default([]),
+ objects: z.array(importerCanonEntry).max(BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX).default([]),
+ }).default({ characters: [], places: [], objects: [] }),
+ arc: importerArcShape.nullable().optional(),
+ seasons: z.array(importerSeasonEntry).max(50).default([]),
+ issues: z.array(importerIssueEntry).min(1).max(50),
+}).strict();
diff --git a/server/routes/importer.js b/server/routes/importer.js
new file mode 100644
index 0000000000..f4988628a6
--- /dev/null
+++ b/server/routes/importer.js
@@ -0,0 +1,69 @@
+import { Router } from 'express';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import {
+ validateRequest,
+ importerAnalyzeSchema,
+ importerCommitSchema,
+} from '../lib/validation.js';
+import {
+ analyzeImport,
+ commitImport,
+ ERR_VALIDATION,
+ ERR_LOCKED,
+ ERR_PARTIAL_COMMIT_ISSUES,
+ IMPORTER_SOURCE_CHAR_LIMIT,
+} from '../services/importer.js';
+import { ARC_ROLES } from '../lib/storyArc.js';
+import * as universeSvc from '../services/universeBuilder.js';
+import * as seriesSvc from '../services/pipeline/series.js';
+
+const router = Router();
+
+// The orchestrator throws its own validation/locked codes directly. Missing
+// universe / series codes bubble through `getUniverse` / `getSeries` with
+// their service-native codes (`NOT_FOUND` / `PIPELINE_SERIES_NOT_FOUND`),
+// not an importer-prefixed alias — map those to 404.
+// `ERR_PARTIAL_COMMIT_ISSUES` maps to 207 Multi-Status (not 500) because
+// the universe + series writes succeeded and only the issue loop was
+// rolled back — alerting / generic-retry middleware that pages on 5xx
+// would otherwise treat this user-action-recoverable state as an infra
+// failure. 207 is the canonical "completed with mixed outcomes" code
+// and the client UI can render a tailored retry affordance.
+const SERVICE_ERROR_STATUS = {
+ [ERR_VALIDATION]: 400,
+ [ERR_LOCKED]: 409,
+ [ERR_PARTIAL_COMMIT_ISSUES]: 207,
+ [universeSvc.ERR_NOT_FOUND]: 404,
+ [seriesSvc.ERR_NOT_FOUND]: 404,
+};
+
+const mapServiceError = (err) => {
+ const status = SERVICE_ERROR_STATUS[err?.code];
+ if (status) return new ServerError(err.message, { status, code: err.code });
+ return err;
+};
+
+// Surfaces server-canonical constants so the client doesn't hardcode (and
+// drift from) the source-char limit or the arc-role enum. Read by the
+// Importer intake form on mount; the analyze response also includes these
+// for clients that skip the config call.
+router.get('/config', asyncHandler(async (req, res) => {
+ res.json({
+ sourceCharLimit: IMPORTER_SOURCE_CHAR_LIMIT,
+ arcRoles: [...ARC_ROLES],
+ });
+}));
+
+router.post('/analyze', asyncHandler(async (req, res) => {
+ const input = validateRequest(importerAnalyzeSchema, req.body || {});
+ const result = await analyzeImport(input).catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
+router.post('/commit', asyncHandler(async (req, res) => {
+ const input = validateRequest(importerCommitSchema, req.body || {});
+ const result = await commitImport(input).catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
+export default router;
diff --git a/server/routes/importer.test.js b/server/routes/importer.test.js
new file mode 100644
index 0000000000..80b563986e
--- /dev/null
+++ b/server/routes/importer.test.js
@@ -0,0 +1,167 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import importerRoutes from './importer.js';
+import { ERR_VALIDATION, ERR_LOCKED, IMPORTER_SOURCE_CHAR_LIMIT } from '../services/importer.js';
+import * as universeSvc from '../services/universeBuilder.js';
+import * as seriesSvc from '../services/pipeline/series.js';
+import { ARC_ROLES } from '../lib/storyArc.js';
+
+vi.mock('../services/importer.js', async () => {
+ const actual = await vi.importActual('../services/importer.js');
+ return {
+ ...actual, // real ERR_VALIDATION, ERR_LOCKED, IMPORTER_SOURCE_CHAR_LIMIT, etc.
+ analyzeImport: vi.fn(), // mocked behavior
+ commitImport: vi.fn(), // mocked behavior
+ };
+});
+
+// No mock for ../services/universeBuilder.js, ../services/pipeline/series.js,
+// or ../lib/storyArc.js — the route only reads `ERR_NOT_FOUND` constants
+// from the service modules and `ARC_ROLES`/`ARC_SHAPE_IDS` from storyArc.
+// Using the real modules keeps `ERR_NOT_FOUND` aligned with the
+// SERVICE_ERROR_STATUS map, and keeps the Zod enums aligned with the
+// prompts — placeholder mocks would silently mask drift.
+
+import * as importerSvc from '../services/importer.js';
+
+function buildApp() {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/importer', importerRoutes);
+ return app;
+}
+
+describe('GET /api/importer/config', () => {
+ it('returns sourceCharLimit and arcRoles', async () => {
+ const app = buildApp();
+ const res = await request(app).get('/api/importer/config');
+ expect(res.status).toBe(200);
+ expect(res.body.sourceCharLimit).toBe(IMPORTER_SOURCE_CHAR_LIMIT);
+ expect(Array.isArray(res.body.arcRoles)).toBe(true);
+ });
+});
+
+describe('POST /api/importer/analyze', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('returns 200 with the service result on success', async () => {
+ importerSvc.analyzeImport.mockResolvedValue({ universe: {}, series: {}, issueProposals: [] });
+ const app = buildApp();
+ const res = await request(app).post('/api/importer/analyze').send({
+ universeName: 'U',
+ seriesName: 'S',
+ contentType: 'short-story',
+ source: 'text',
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.issueProposals).toEqual([]);
+ });
+
+ it('returns 400 when the service throws ERR_VALIDATION', async () => {
+ const err = Object.assign(new Error('source is required'), { code: ERR_VALIDATION });
+ importerSvc.analyzeImport.mockRejectedValue(err);
+ const app = buildApp();
+ const res = await request(app).post('/api/importer/analyze').send({
+ universeName: 'U',
+ seriesName: 'S',
+ contentType: 'short-story',
+ source: 'x',
+ });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe(ERR_VALIDATION);
+ });
+
+ it('returns 409 when the service throws ERR_LOCKED', async () => {
+ const err = Object.assign(
+ new Error('Series "X" has a locked arc.'),
+ { code: ERR_LOCKED },
+ );
+ importerSvc.analyzeImport.mockRejectedValue(err);
+ const app = buildApp();
+ const res = await request(app).post('/api/importer/analyze').send({
+ universeName: 'U',
+ seriesName: 'X',
+ contentType: 'short-story',
+ source: 'text',
+ });
+ expect(res.status).toBe(409);
+ expect(res.body.code).toBe(ERR_LOCKED);
+ });
+});
+
+describe('POST /api/importer/commit', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('returns 200 with the service result on success', async () => {
+ importerSvc.commitImport.mockResolvedValue({
+ universe: {}, series: {}, createdIssueIds: ['issue-1'], remappedIssues: [],
+ });
+ const app = buildApp();
+ const res = await request(app).post('/api/importer/commit').send({
+ universeId: 'uni-1',
+ seriesId: 'ser-1',
+ canonSelections: { characters: [], places: [], objects: [] },
+ arc: null,
+ seasons: [],
+ issues: [{ title: 'I1', arcPosition: 1 }],
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.createdIssueIds).toEqual(['issue-1']);
+ });
+
+ it('returns 400 when the service throws ERR_VALIDATION', async () => {
+ const err = Object.assign(new Error('universeId is required'), { code: ERR_VALIDATION });
+ importerSvc.commitImport.mockRejectedValue(err);
+ const app = buildApp();
+ const res = await request(app).post('/api/importer/commit').send({
+ universeId: 'uni-1',
+ seriesId: 'ser-1',
+ canonSelections: { characters: [], places: [], objects: [] },
+ arc: null,
+ seasons: [],
+ issues: [{ title: 'I1', arcPosition: 1 }],
+ });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe(ERR_VALIDATION);
+ });
+
+ it('returns 409 when the service throws ERR_LOCKED', async () => {
+ const err = Object.assign(
+ new Error('Series "X" has a locked arc — commit refused.'),
+ { code: ERR_LOCKED },
+ );
+ importerSvc.commitImport.mockRejectedValue(err);
+ const app = buildApp();
+ const res = await request(app).post('/api/importer/commit').send({
+ universeId: 'uni-1',
+ seriesId: 'ser-1',
+ canonSelections: { characters: [], places: [], objects: [] },
+ arc: null,
+ seasons: [],
+ issues: [{ title: 'I1', arcPosition: 1 }],
+ });
+ expect(res.status).toBe(409);
+ expect(res.body.code).toBe(ERR_LOCKED);
+ });
+
+ it('returns 404 when the service throws the universe not-found code', async () => {
+ const err = Object.assign(new Error('Universe not found'), { code: universeSvc.ERR_NOT_FOUND });
+ importerSvc.commitImport.mockRejectedValue(err);
+ const app = buildApp();
+ const res = await request(app).post('/api/importer/commit').send({
+ universeId: 'missing',
+ seriesId: 'ser-1',
+ canonSelections: { characters: [], places: [], objects: [] },
+ arc: null,
+ seasons: [],
+ issues: [{ title: 'I1', arcPosition: 1 }],
+ });
+ expect(res.status).toBe(404);
+ // Pin the code too — a rename of universeSvc.ERR_NOT_FOUND would
+ // otherwise silently land here because SERVICE_ERROR_STATUS[undefined]
+ // falls through to the generic 500 handler and the status assertion
+ // alone wouldn't catch the regression.
+ expect(res.body.code).toBe(universeSvc.ERR_NOT_FOUND);
+ });
+});
diff --git a/server/services/importer.js b/server/services/importer.js
new file mode 100644
index 0000000000..7fbfac5a21
--- /dev/null
+++ b/server/services/importer.js
@@ -0,0 +1,869 @@
+/**
+ * Pipeline — Importer Service
+ *
+ * Reverse-engineers a finished short story / novel / screenplay / comic
+ * script into universe canon + series arc + prose-seeded issues.
+ *
+ * Canon kind mapping: the prompts + wire shape use the forward-looking
+ * `places` label (matches the in-flight Phase 0b SETTING→PLACE rename),
+ * but the on-disk universe schema still stores them under `settings`.
+ * Mapping happens at the orchestrator boundary so the UI + LLM never see
+ * the legacy field name.
+ */
+
+import { runStagedLLM } from '../lib/stageRunner.js';
+import {
+ listUniverses,
+ getUniverse,
+ createUniverse,
+ updateUniverse,
+ deleteUniverse,
+} from './universeBuilder.js';
+import {
+ listSeries,
+ getSeries,
+ createSeries,
+ updateSeries,
+} from './pipeline/series.js';
+import { createIssue, deleteIssue, listIssues } from './pipeline/issues.js';
+import { sanitizeArc, sanitizeSeasonList, buildSeason, ARC_SHAPE_IDS, ARC_ROLES } from '../lib/storyArc.js';
+import { mergeExtractedBible, BIBLE_KIND } from '../lib/storyBible.js';
+
+// Surfaced to the route layer so the importer's policy errors become 400s
+// with stable codes.
+export const ERR_VALIDATION = 'IMPORTER_VALIDATION';
+export const ERR_LOCKED = 'IMPORTER_LOCKED';
+// Thrown when the issue-loop fails mid-flight after universe + series writes
+// already landed. Universe/series are preserved; the partial issue set is
+// rolled back. Retrying commit is safe (merges are idempotent).
+export const ERR_PARTIAL_COMMIT_ISSUES = 'IMPORTER_PARTIAL_COMMIT_ISSUES';
+
+const makeErr = (message, code) => Object.assign(new Error(message), { code });
+
+// v1 hard cap on the source corpus. Big novels run ~500K chars; this keeps
+// us under most providers' single-call context limit until the chunked
+// fallback follow-up lands (PLAN.md / "Create Suite — Importer page").
+export const IMPORTER_SOURCE_CHAR_LIMIT = 200_000;
+
+// Per-content-type defaults when the user doesn't pass `targetIssueCount`.
+// `null` means "let the LLM decide" — short stories collapse to one; novels
+// honor chapter boundaries; screenplays default to a single episode; comic
+// scripts use explicit ISSUE headers or ~22-page bundles.
+const DEFAULT_TARGET_ISSUE_COUNT_HINT = Object.freeze({
+ 'short-story': 1,
+ 'novel': null,
+ 'screenplay': 1,
+ 'comic-script': null,
+});
+
+const normName = (s) => String(s || '').trim().toLowerCase();
+const isStr = (v) => typeof v === 'string';
+
+// Wire schema (importerSeasonEntry) caps season.number at 99 — mirror
+// that ceiling here so the auto-assign path can't silently land a value
+// the schema wouldn't accept on direct entry.
+const SEASON_NUMBER_MAX = 99;
+// Wire schema (importerIssueEntry) caps arcPosition at 9999 — mirror so
+// the service-side auto-assign can't drift above it.
+const ARC_POSITION_MAX = 9999;
+
+/**
+ * Merge incoming seasons with the existing `series.seasons[]` array,
+ * matching by `number`. Pure function — no I/O. Extracted so the merge
+ * logic (used number set, auto-assign for omitted numbers, update vs
+ * create per number, change-aware updatedAt bump, union back with
+ * retained existing) can be reasoned about + unit-tested in isolation.
+ *
+ * Contract:
+ * - Incoming seasons with an explicit integer `number >= 1` keep it.
+ * - Incoming seasons that omit `number` are assigned the next free
+ * integer above the union of existing + already-assigned numbers;
+ * throws ERR_VALIDATION if that would exceed SEASON_NUMBER_MAX (99).
+ * - Where the assigned number matches an existing season, the existing
+ * season's id (+ timestamps) are preserved — re-import is a metadata
+ * refresh, not a new season. **String-field merge follows CLAUDE.md's
+ * "absent vs intentionally empty" rule**: `undefined`/`null` preserves
+ * the existing value; an empty string `""` is treated as an intentional
+ * clear and applied. `updatedAt` bumps when any tracked field
+ * (title / logline / synopsis / endingHook / episodeCountTarget)
+ * actually changed, including a clear.
+ * - Existing seasons not touched by this merge are retained as-is.
+ * - Caller is responsible for `sanitizeSeasonList` on the result.
+ */
+export function mergeSeasons(existingSeasons, incomingSeasons, buildSeasonImpl = buildSeason) {
+ const existingByNumber = new Map(
+ existingSeasons.filter((s) => Number.isFinite(s.number)).map((s) => [s.number, s]),
+ );
+ // Dedup-check + ceiling-check explicit incoming numbers — commitImport's
+ // route path Zod gates against both, but a direct caller (a future
+ // internal consumer of the pure helper, or a test) would otherwise
+ // silently collapse two incoming seasons sharing a number into one merge
+ // target, or land a number > SEASON_NUMBER_MAX that the wire wouldn't
+ // accept. Auto-assign path enforces the ceiling below; the explicit
+ // path enforces it here for symmetry.
+ const seenIncomingNumbers = new Set();
+ for (const s of incomingSeasons) {
+ if (Number.isInteger(s?.number) && s.number >= 1) {
+ if (s.number > SEASON_NUMBER_MAX) {
+ throw makeErr(
+ `mergeSeasons: explicit season number ${s.number} exceeds the max of ${SEASON_NUMBER_MAX}.`,
+ ERR_VALIDATION,
+ );
+ }
+ if (seenIncomingNumbers.has(s.number)) {
+ throw makeErr(
+ `mergeSeasons: duplicate explicit season number ${s.number} in incoming list — caller must pre-dedupe.`,
+ ERR_VALIDATION,
+ );
+ }
+ seenIncomingNumbers.add(s.number);
+ }
+ }
+ const usedNumbers = new Set([...existingByNumber.keys(), ...seenIncomingNumbers]);
+ // Jump-past-max rather than gap-fill: if existing seasons are [1, 5],
+ // auto-assign lands at 6 (not 2). Two reasons: (1) gap-fill could
+ // silently re-occupy a slot the user intentionally deleted (e.g.
+ // removed season 3 to retire it; new content shouldn't land at slot 3
+ // with a totally different premise); (2) "new = appended" matches the
+ // user's mental model of how multi-pass imports extend the world.
+ let nextFreeNumber = (usedNumbers.size === 0) ? 1 : Math.max(...usedNumbers) + 1;
+ const nowIso = new Date().toISOString();
+ // String-field merge: absent (`undefined`/`null`) preserves the existing
+ // value; everything else — including `""` — is the user's intent and is
+ // applied verbatim. Mirrors the CLAUDE.md "distinguish absent vs
+ // intentionally empty" rule so a Review-phase blank-out actually clears.
+ const mergeStr = (incoming, existing) => (incoming == null ? (existing ?? '') : incoming);
+ const incomingBuilt = incomingSeasons.map((s) => {
+ let num;
+ if (Number.isInteger(s?.number) && s.number >= 1) {
+ num = s.number;
+ } else {
+ if (nextFreeNumber > SEASON_NUMBER_MAX) {
+ throw makeErr(
+ `Cannot auto-assign season number — next free slot (${nextFreeNumber}) exceeds the max of ${SEASON_NUMBER_MAX}. Free up a season slot or set season.number explicitly.`,
+ ERR_VALIDATION,
+ );
+ }
+ num = nextFreeNumber++;
+ }
+ const existing = existingByNumber.get(num);
+ if (existing) {
+ // Apply the same `|| Season N` default to BOTH sides of the title
+ // comparison so a legacy season with `title: undefined` doesn't
+ // churn updatedAt on every no-op re-import: without normalizing
+ // the existing-side default, `'Season N' !== undefined` always
+ // resolves truthy and bumps updatedAt even when nothing changed.
+ const titleDefault = `Season ${num}`;
+ const nextTitle = mergeStr(s.title, existing.title) || titleDefault;
+ const nextLogline = mergeStr(s.logline, existing.logline);
+ const nextSynopsis = mergeStr(s.synopsis, existing.synopsis);
+ const nextEndingHook = mergeStr(s.endingHook, existing.endingHook);
+ const nextEpisodeCount = s.episodeCountTarget ?? existing.episodeCountTarget ?? 0;
+ const anyChanged = nextTitle !== (existing.title || titleDefault)
+ || nextLogline !== (existing.logline ?? '')
+ || nextSynopsis !== (existing.synopsis ?? '')
+ || nextEndingHook !== (existing.endingHook ?? '')
+ || nextEpisodeCount !== (existing.episodeCountTarget ?? 0);
+ return {
+ ...existing,
+ title: nextTitle,
+ logline: nextLogline,
+ synopsis: nextSynopsis,
+ endingHook: nextEndingHook,
+ episodeCountTarget: nextEpisodeCount,
+ ...(anyChanged ? { updatedAt: nowIso } : {}),
+ };
+ }
+ return buildSeasonImpl({
+ number: num,
+ title: s.title || `Season ${num}`,
+ logline: s.logline || '',
+ synopsis: s.synopsis || '',
+ endingHook: s.endingHook || '',
+ episodeCountTarget: s.episodeCountTarget ?? 0,
+ status: 'draft',
+ });
+ });
+ // Union: existing seasons NOT in the incoming set + the (updated or
+ // freshly built) incoming entries. Caller runs sanitizeSeasonList.
+ // Filter retained to the same finite-numbered subset the map above
+ // operates on — a malformed existing entry (number undefined/NaN)
+ // would otherwise always slip through (since incomingNumbers only
+ // contains valid integers), surviving the merge unreachable by id.
+ // sanitizeSeasonList downstream coerces those to 0 and may drop
+ // them, but filtering here removes the ambiguity at the source.
+ const incomingNumbers = new Set(incomingBuilt.map((s) => s.number));
+ const retained = existingSeasons.filter((s) =>
+ Number.isFinite(s.number) && !incomingNumbers.has(s.number),
+ );
+ return [...retained, ...incomingBuilt];
+}
+
+// Build the "existing canon" prompt block in JS rather than as a Mustache
+// `{{#section}}{{{var}}}{{/section}}` so the user-supplied canon JSON
+// passes through the template engine's TRIPLE_RE substitution exactly
+// once (after the section-resolution loop has settled). Substituting a
+// JSON-stringified value that contains `{{spoilers}}` *inside* a section
+// would otherwise let the outer SECTION/VAR loop re-interpret the
+// braces as template tokens.
+function buildExistingCanonBlock(existingCanon) {
+ if (!existingCanon) return '';
+ const json = JSON.stringify(existingCanon, null, 2);
+ // Wrap in a tilde fence (`~~~`) rather than triple-backticks — user
+ // canon content (stylized character names, lyric titles, pasted
+ // markdown from a prior import) can legitimately contain ``` and
+ // would otherwise close our fence early, corrupting the prompt.
+ // Tildes are exceedingly rare in fiction prose; if they ever collide,
+ // a longer tilde run (`~~~~`) is the escape hatch.
+ return [
+ '## Existing universe canon (do NOT duplicate these by name or aliases)',
+ '',
+ 'This universe already has some canonical entries. Match by `name` (case-insensitive) **and by any listed `aliases`**. If an existing entry covers the same character / place / object, **omit it entirely** from your output — return only NEW entries. (Evidence for existing entries from this source is not currently re-merged; downstream evidence backfill is a follow-up.)',
+ '',
+ '~~~json',
+ json,
+ '~~~',
+ '',
+ ].join('\n');
+}
+
+/**
+ * Find a universe by case-insensitive name match. Returns `null` when no
+ * match — the caller decides to create. Exported for the test surface.
+ */
+export async function findUniverseByName(name) {
+ const target = normName(name);
+ if (!target) return null;
+ const all = await listUniverses();
+ return all.find((u) => normName(u.name) === target) || null;
+}
+
+/**
+ * Find a series by case-insensitive name match, scoped to a specific
+ * universe. A name match in a DIFFERENT universe returns `null` — see the
+ * design doc's "Find-or-Create Logic" section.
+ */
+export async function findSeriesByName(name, universeId) {
+ const target = normName(name);
+ if (!target) return null;
+ // Guard universeId too — without this, a falsy/missing universeId
+ // would match every series with a falsy `universeId` on disk, which
+ // breaks the "scoped to a specific universe" contract. Today's only
+ // caller in analyzeImport skips this lookup entirely when the universe
+ // doesn't exist yet, but this is exported for tests + future callers.
+ if (typeof universeId !== 'string' || !universeId) return null;
+ const all = await listSeries();
+ return all.find((s) =>
+ normName(s.name) === target && s.universeId === universeId,
+ ) || null;
+}
+
+/**
+ * Render the existing universe canon as a compact JSON block so the
+ * canon-extract LLM can dedup by name before returning. Drops fields that
+ * inflate the prompt without informing the dedup decision (imageRefs,
+ * timestamps, ids).
+ */
+// Fields that must serialize as arrays in the prompt JSON — a non-array
+// truthy value (defensive against malformed on-disk data) would otherwise
+// reach the LLM as a scalar and break dedup matching.
+const COMPACT_ARRAY_FIELDS = new Set(['aliases']);
+
+function compactCanonForPrompt(universe) {
+ const slim = (entry, fields) => {
+ const out = {};
+ for (const k of fields) {
+ const v = entry[k];
+ if (v == null || v === '') continue;
+ if (COMPACT_ARRAY_FIELDS.has(k)) {
+ if (!Array.isArray(v) || v.length === 0) continue;
+ } else if (Array.isArray(v) && v.length === 0) {
+ continue;
+ }
+ out[k] = v;
+ }
+ return out;
+ };
+ // Aliases are exposed for every kind so the LLM's dedup matching aligns
+ // with the server-side merge keys (`mergeExtractedBible` dedups by name +
+ // aliases). Omitting aliases for any kind would let the LLM return an
+ // entry the merge layer treats as a duplicate, just with the new source's
+ // name variant.
+ const characters = (universe.characters || []).map((c) =>
+ slim(c, ['name', 'aliases', 'role', 'physicalDescription']));
+ const places = (universe.settings || []).map((s) =>
+ slim(s, ['name', 'aliases', 'slugline', 'description']));
+ const objects = (universe.objects || []).map((o) =>
+ slim(o, ['name', 'aliases', 'description']));
+ if (!characters.length && !places.length && !objects.length) return null;
+ return { characters, places, objects };
+}
+
+/**
+ * Build a sanitized arc preview from a raw LLM arc response. Whitelists the
+ * known fields (matching `importerArcShape` in validation.js) so hallucinated
+ * or future extra keys never silently reach the client or commit path. Also
+ * validates `shape` against `ARC_SHAPE_IDS` — an invalid/misspelled shape is
+ * dropped to `null` so the UI renders "— pick one —" immediately rather than
+ * hiding the error until Zod rejects it at commit time.
+ * Threads B + C combined.
+ */
+function buildArcPreview(raw) {
+ if (raw == null || typeof raw !== 'object') return null;
+ const shape = isStr(raw.shape) && ARC_SHAPE_IDS.includes(raw.shape) ? raw.shape : null;
+ return {
+ logline: isStr(raw.logline) ? raw.logline : null,
+ summary: isStr(raw.summary) ? raw.summary : null,
+ protagonistArc: isStr(raw.protagonistArc) ? raw.protagonistArc : null,
+ themes: Array.isArray(raw.themes) ? raw.themes : [],
+ shape,
+ };
+}
+
+/**
+ * Phase 1: analyze. Runs canon-extract + arc-extract in parallel (both read
+ * source independently); after arc resolves, runs issue-proposal with the
+ * arc summary in scope so the issue boundaries align with the arc's beats.
+ *
+ * Returns a fully-shaped preview the client can render in the Review
+ * phase. Nothing canonical (arc, seasons, issues) is persisted yet — only
+ * the find-or-created universe + series exist on disk so the commit phase
+ * has stable ids to reference.
+ *
+ * Partial-failure safety (Thread A): universe + series are NOT written to
+ * disk until after all three LLM calls succeed. Pre-existing records are
+ * looked up first; new records are persisted only at the end. A network
+ * timeout or parse failure during any LLM stage therefore leaves no
+ * orphaned half-created records behind.
+ */
+export async function analyzeImport({
+ universeName,
+ seriesName,
+ contentType,
+ source,
+ providerOverride,
+ targetIssueCount,
+} = {}) {
+ if (!isStr(universeName) || !universeName.trim()) {
+ throw makeErr('universeName is required', ERR_VALIDATION);
+ }
+ if (!isStr(seriesName) || !seriesName.trim()) {
+ throw makeErr('seriesName is required', ERR_VALIDATION);
+ }
+ if (!isStr(source) || !source.trim()) {
+ throw makeErr('source is required', ERR_VALIDATION);
+ }
+ if (source.length > IMPORTER_SOURCE_CHAR_LIMIT) {
+ throw makeErr(
+ `Source is ${source.length.toLocaleString()} chars — v1 limit is ${IMPORTER_SOURCE_CHAR_LIMIT.toLocaleString()}. Trim the source or wait for chunked-extraction support.`,
+ ERR_VALIDATION,
+ );
+ }
+
+ // Look up pre-existing records WITHOUT creating anything yet. Creation is
+ // deferred until after all LLM calls succeed so a failure above never
+ // leaves orphaned data on disk.
+ const existingUniverse = await findUniverseByName(universeName);
+ const isExistingUniverse = existingUniverse !== null;
+
+ // Series lookup requires a universe id. For new universes we skip the
+ // series lookup — there can't be an existing series in a universe that
+ // doesn't exist yet.
+ const existingSeries = isExistingUniverse
+ ? await findSeriesByName(seriesName, existingUniverse.id)
+ : null;
+ const isExistingSeries = existingSeries !== null;
+
+ // If the user re-runs the importer on a series whose arc is locked, fail
+ // FAST — no point spending heavy-tier tokens to extract an arc the commit
+ // phase will refuse to apply.
+ if (existingSeries?.locked?.arc === true) {
+ throw makeErr(
+ `Series "${existingSeries.name}" has a locked arc. Unlock it on the Arc Canvas before importing — or rename the import's series so a fresh series is created.`,
+ ERR_LOCKED,
+ );
+ }
+
+ // Build the existing-canon prompt hint from the pre-existing universe (if
+ // any). For a brand-new universe this is null — the LLM gets no prior
+ // context, which is correct.
+ const existingCanon = existingUniverse ? compactCanonForPrompt(existingUniverse) : null;
+
+ // returnsJson gates extractJson() in stageRunner — required even though
+ // the stage-config also declares `returnsJson: true` (that field is
+ // metadata for the Prompts UI; the runtime only consults the per-call
+ // option). Helper returns a FRESH object each call so a future runner
+ // that decides to add bookkeeping (`opts.attempt`, `opts.startedAt`)
+ // can't leak state across our parallel canon + arc invocations.
+ const buildLlmOpts = () => ({ providerOverride, source: 'importer-analyze', returnsJson: true });
+
+ const userRequestedCount = Number.isFinite(targetIssueCount) && targetIssueCount > 0;
+ const issueCountHint = userRequestedCount
+ ? targetIssueCount
+ : DEFAULT_TARGET_ISSUE_COUNT_HINT[contentType];
+
+ // Per-type booleans for the Mustache section guards in the prompt
+ // templates (PortOS's template engine is Mustache, not Liquid — no
+ // `{% if x == 'y' %}` support, so we expose presence flags instead).
+ const typeFlags = {
+ isShortStory: contentType === 'short-story',
+ isNovel: contentType === 'novel',
+ isScreenplay: contentType === 'screenplay',
+ isComicScript: contentType === 'comic-script',
+ };
+
+ // Use the known persisted name for prompt variables when the record
+ // already exists; fall back to the trimmed input for new records.
+ const promptUniverseName = existingUniverse?.name ?? universeName.trim();
+ const promptSeriesName = existingSeries?.name ?? seriesName.trim();
+
+ // Canon + arc are independent reads of the same source — fire in
+ // parallel. Issue-proposal depends on the arc summary, so chain after
+ // arc resolves.
+ const [canonRun, arcRun] = await Promise.all([
+ runStagedLLM('importer-canon-extract', {
+ universeName: promptUniverseName,
+ seriesName: promptSeriesName,
+ contentType,
+ source,
+ existingCanonBlock: buildExistingCanonBlock(existingCanon),
+ ...typeFlags,
+ }, buildLlmOpts()),
+ runStagedLLM('importer-arc-extract', {
+ seriesName: promptSeriesName,
+ contentType,
+ source,
+ ...typeFlags,
+ }, buildLlmOpts()),
+ ]);
+
+ // Pull the arc summary in before issue-proposal so the issue boundaries
+ // align with the arc's act structure. Falls back to logline if summary
+ // is empty (older / smaller models sometimes return just logline).
+ const arcContent = (typeof arcRun.content === 'object' && arcRun.content !== null)
+ ? arcRun.content
+ : {};
+ const arcSummary = arcContent.summary || arcContent.logline || `${promptSeriesName} — ${contentType}`;
+
+ const issuesRun = await runStagedLLM('importer-issue-proposal', {
+ seriesName: promptSeriesName,
+ contentType,
+ source,
+ ...typeFlags,
+ arcSummary,
+ // `targetIssueCount` (number) is the value the prompt interpolates;
+ // `isUserRequestedCount` (boolean) gates the "user-requested — produce
+ // exactly this many" copy vs the softer "default for this type" copy so
+ // a per-type hint isn't presented as a hard user constraint.
+ targetIssueCount: issueCountHint,
+ isUserRequestedCount: userRequestedCount,
+ }, buildLlmOpts());
+
+ // All LLM calls succeeded — now persist any new records. Pre-existing
+ // records are returned as-is; new records are created here at the end so
+ // a failure above never leaves orphaned data on disk.
+ //
+ // Thread A: wrap the two-step create in a try/catch so a `createSeries`
+ // failure doesn't leave an orphaned universe on disk. We only delete the
+ // universe if we created it in this call — a pre-existing universe must
+ // never be removed as a side-effect of a series-create failure.
+ let universe = isExistingUniverse
+ ? existingUniverse
+ : await createUniverse({ name: universeName.trim() });
+ const universeWasCreated = !isExistingUniverse;
+
+ let series;
+ try {
+ series = isExistingSeries
+ ? existingSeries
+ : await createSeries({ name: seriesName.trim(), universeId: universe.id });
+ } catch (seriesErr) {
+ if (universeWasCreated) {
+ await deleteUniverse(universe.id).catch((delErr) =>
+ console.error(`❌ analyzeImport rollback: failed to delete orphaned universe ${universe.id}: ${delErr.message}`),
+ );
+ }
+ throw seriesErr;
+ }
+
+ const arcPreview = buildArcPreview(arcRun.content);
+
+ return {
+ universe,
+ series,
+ isExistingUniverse,
+ isExistingSeries,
+ canonPreview: {
+ characters: Array.isArray(canonRun.content?.characters) ? canonRun.content.characters : [],
+ places: Array.isArray(canonRun.content?.places) ? canonRun.content.places : [],
+ objects: Array.isArray(canonRun.content?.objects) ? canonRun.content.objects : [],
+ },
+ arcPreview,
+ seasonsPreview: Array.isArray(arcRun.content?.seasons) ? arcRun.content.seasons : [],
+ issueProposals: Array.isArray(issuesRun.content?.issues) ? issuesRun.content.issues : [],
+ runIds: {
+ canon: canonRun.runId,
+ arc: arcRun.runId,
+ issues: issuesRun.runId,
+ },
+ providerId: canonRun.providerId,
+ model: canonRun.model,
+ // Server-canonical constants surfaced to the client so it doesn't have to
+ // hardcode (and silently drift from) them. The intake form's char-count
+ // warning + the review form's arc-role dropdown both read these.
+ limits: {
+ sourceCharLimit: IMPORTER_SOURCE_CHAR_LIMIT,
+ },
+ arcRoles: [...ARC_ROLES],
+ };
+}
+
+/**
+ * Phase 2: commit. Merges the user-confirmed canon into the universe,
+ * writes the arc + seasons onto the series, then creates one issue per
+ * proposal with prose pre-seeded. Validates the locked-arc guard one more
+ * time (the series could have been locked between analyze + commit).
+ */
+export async function commitImport({
+ universeId,
+ seriesId,
+ canonSelections = {},
+ arc = null,
+ seasons = [],
+ issues = [],
+} = {}) {
+ if (!isStr(universeId)) throw makeErr('universeId is required', ERR_VALIDATION);
+ if (!isStr(seriesId)) throw makeErr('seriesId is required', ERR_VALIDATION);
+ if (!Array.isArray(issues) || issues.length === 0) {
+ throw makeErr('At least one issue is required', ERR_VALIDATION);
+ }
+
+ // Re-fetch under the universe + series lock window so we apply the merge
+ // against the freshest persisted state — the user may have edited the
+ // universe canon in another tab between analyze and commit.
+ const universe = await getUniverse(universeId);
+ const series = await getSeries(seriesId);
+
+ // Defensive: refuse commit when series.universeId is set AND differs,
+ // OR when series.universeId is missing entirely. A legacy series
+ // persisted before universeId became standard would otherwise silently
+ // be re-homed to whichever universe the caller routed through. createSeries
+ // sets universeId today, so a missing value implies hand-edited / pre-link
+ // legacy data — flag it so the caller decides rather than silently linking.
+ if (series.universeId !== universe.id) {
+ if (series.universeId) {
+ throw makeErr(
+ `Series "${series.name}" is linked to a different universe — commit refused to avoid cross-linking.`,
+ ERR_VALIDATION,
+ );
+ }
+ throw makeErr(
+ `Series "${series.name}" has no universeId — commit refused. Link the series to a universe explicitly before importing.`,
+ ERR_VALIDATION,
+ );
+ }
+
+ if (series.locked?.arc === true) {
+ throw makeErr(
+ `Series "${series.name}" has a locked arc — commit refused. Unlock the arc to import.`,
+ ERR_LOCKED,
+ );
+ }
+
+ // Thread C fix — fail-fast validation BEFORE any state mutation. Run
+ // every issue through all gates that createIssue enforces so that a bad
+ // payload is rejected here, before the universe + series are written.
+ // `createIssue` also requires `seriesId` (supplied below) and generates
+ // its own `id`, so those two fields don't need pre-checking.
+ for (let i = 0; i < issues.length; i++) {
+ const proposal = issues[i];
+ if (!isStr(proposal?.title) || !proposal.title.trim()) {
+ throw makeErr(
+ `Issue at position ${i + 1} is missing a title — commit refused before any state changed.`,
+ ERR_VALIDATION,
+ );
+ }
+ // arcPosition is the issue's slot in the series — Zod enforces
+ // int 1..ARC_POSITION_MAX at the route layer, but commitImport is
+ // also called directly from tests + future internal callers; mirror
+ // both the floor and the ceiling here so the service contract holds
+ // regardless of caller. Allow undefined — an auto-assign pass below
+ // picks the next free slot. Reject anything that isn't a valid
+ // integer in [1, ARC_POSITION_MAX].
+ if (proposal.arcPosition !== undefined && proposal.arcPosition !== null
+ && (!Number.isInteger(proposal.arcPosition)
+ || proposal.arcPosition < 1
+ || proposal.arcPosition > ARC_POSITION_MAX)) {
+ throw makeErr(
+ `Issue at position ${i + 1} has invalid arcPosition (must be integer 1..${ARC_POSITION_MAX}) — commit refused before any state changed.`,
+ ERR_VALIDATION,
+ );
+ }
+ // When proseExcerpt is present it must be non-empty after trim —
+ // mirrors the route Zod `.refine` so a whitespace-only excerpt from
+ // a direct caller doesn't seed `stages.prose` with garbage.
+ if (proposal.proseExcerpt !== undefined && proposal.proseExcerpt !== null) {
+ if (!isStr(proposal.proseExcerpt) || !proposal.proseExcerpt.trim()) {
+ throw makeErr(
+ `Issue at position ${i + 1} has invalid proseExcerpt (must be non-empty when present) — commit refused before any state changed.`,
+ ERR_VALIDATION,
+ );
+ }
+ }
+ }
+ // Reject duplicate explicit arcPosition values across the incoming
+ // issues array — downstream sorting collapses ties to insertion order
+ // and the renumber pass would silently re-key, leaving the user
+ // wondering why issue #3 became #4. Auto-assign for omitted positions
+ // happens below.
+ const seenArcPositions = new Set();
+ for (let i = 0; i < issues.length; i++) {
+ const pos = issues[i]?.arcPosition;
+ if (Number.isInteger(pos) && pos >= 1) {
+ if (seenArcPositions.has(pos)) {
+ throw makeErr(
+ `Duplicate arcPosition ${pos} at issue position ${i + 1} — commit refused before any state changed.`,
+ ERR_VALIDATION,
+ );
+ }
+ seenArcPositions.add(pos);
+ }
+ }
+ // Auto-assign sequential arcPositions to incoming issues that omit one.
+ // Mirrors the seasons auto-assign in the merge path. Issues with an
+ // explicit position keep it; gaps get filled by the next free integer.
+ // Seed nextFree from the UNION of explicit incoming positions AND any
+ // pre-existing series.issues[].arcPosition — re-import on a series
+ // that already has issues at [1..3] would otherwise auto-assign
+ // starting at 1 again and create duplicate positions. createIssue
+ // doesn't enforce arcPosition uniqueness, so the collision would
+ // silently land on disk and the renumber pass would arbitrarily
+ // order the ties.
+ // Cap at ARC_POSITION_MAX (matching the wire schema's `.max(9999)`)
+ // so a value the wire wouldn't accept can't reach createIssue via the
+ // service auto-assign path.
+ const existingIssues = await listIssues({ seriesId: series.id });
+ const existingArcPositions = new Set();
+ for (const ex of existingIssues) {
+ if (Number.isInteger(ex.arcPosition) && ex.arcPosition >= 1) {
+ existingArcPositions.add(ex.arcPosition);
+ }
+ }
+ // Symmetry with the auto-assign branch: reject incoming issues whose
+ // EXPLICIT arcPosition collides with an arcPosition already used by an
+ // existing issue on the series. The auto-assign branch dodges this via
+ // the union-set seed; the explicit-position branch would otherwise let
+ // createIssue happily land a duplicate.
+ for (let i = 0; i < issues.length; i++) {
+ const pos = issues[i]?.arcPosition;
+ if (Number.isInteger(pos) && pos >= 1 && existingArcPositions.has(pos)) {
+ throw makeErr(
+ `Issue at position ${i + 1} explicit arcPosition ${pos} collides with an existing issue on the series — commit refused before any state changed. Either renumber the incoming issue or omit arcPosition to auto-assign.`,
+ ERR_VALIDATION,
+ );
+ }
+ }
+ const allUsedArcPositions = new Set([...seenArcPositions, ...existingArcPositions]);
+ let nextFreeArcPos = (allUsedArcPositions.size === 0) ? 1 : Math.max(...allUsedArcPositions) + 1;
+ const issuesWithPositions = issues.map((proposal) => {
+ if (Number.isInteger(proposal.arcPosition) && proposal.arcPosition >= 1) {
+ return proposal;
+ }
+ if (nextFreeArcPos > ARC_POSITION_MAX) {
+ throw makeErr(
+ `Cannot auto-assign arcPosition — next free slot (${nextFreeArcPos}) exceeds the max of ${ARC_POSITION_MAX}. Free up a position or set issue.arcPosition explicitly.`,
+ ERR_VALIDATION,
+ );
+ }
+ const assigned = nextFreeArcPos++;
+ return { ...proposal, arcPosition: assigned };
+ });
+
+ // Same contract for seasons: route Zod enforces `number: int 1..99`,
+ // commitImport mirrors both the floor AND the ceiling so the service is
+ // safe under direct calls. Also reject duplicate season numbers — the
+ // merge keys by `number`, so two incoming seasons sharing one would
+ // silently collapse into a single entry post sanitizeSeasonList.
+ const seenSeasonNumbers = new Set();
+ for (let i = 0; i < seasons.length; i++) {
+ const s = seasons[i];
+ if (s?.number !== undefined && s?.number !== null) {
+ if (!Number.isInteger(s.number) || s.number < 1 || s.number > SEASON_NUMBER_MAX) {
+ throw makeErr(
+ `Season at position ${i + 1} has invalid number (must be integer 1..${SEASON_NUMBER_MAX}) — commit refused before any state changed.`,
+ ERR_VALIDATION,
+ );
+ }
+ if (seenSeasonNumbers.has(s.number)) {
+ throw makeErr(
+ `Duplicate season number ${s.number} at position ${i + 1} — commit refused before any state changed.`,
+ ERR_VALIDATION,
+ );
+ }
+ seenSeasonNumbers.add(s.number);
+ }
+ }
+
+ // Wire field `places` maps to storage field `settings` until the
+ // Phase 0b rename lands; the table keeps the three near-identical
+ // merge calls + universe.update payload in one place.
+ const KIND_MAP = [
+ ['characters', BIBLE_KIND.CHARACTER, 'characters'],
+ ['places', BIBLE_KIND.SETTING, 'settings'],
+ ['objects', BIBLE_KIND.OBJECT, 'objects'],
+ ];
+ // Only merge kinds the user actually supplied entries for — calling
+ // mergeExtractedBible with an empty list still rebuilds the array and
+ // re-stamps timestamps, churning the file write for no behavior change.
+ const universePatch = Object.fromEntries(
+ KIND_MAP
+ .filter(([selectionKey]) => (canonSelections[selectionKey] || []).length > 0)
+ .map(([selectionKey, kind, storageKey]) => [
+ storageKey,
+ mergeExtractedBible(
+ universe[storageKey] || [],
+ canonSelections[selectionKey],
+ kind,
+ { source: 'imported' },
+ ),
+ ]),
+ );
+ // If the user supplied no canon at all (arc-only import), skip the
+ // updateUniverse round-trip entirely.
+ const updatedUniverse = Object.keys(universePatch).length > 0
+ ? await updateUniverse(universe.id, universePatch)
+ : universe;
+
+ // sanitizeArc returns null on an entirely-empty payload — leave
+ // series.arc untouched in that case.
+ const sanitizedArc = sanitizeArc(arc);
+ let updatedSeries = series;
+ if (sanitizedArc || seasons.length > 0) {
+ // Only build + persist a seasons array when the caller actually sent
+ // some — otherwise an arc-only re-import on a series that already has
+ // seasons rewrites the array byte-for-byte identical (just to bump
+ // sanitizeSeasonList's normalization), a wasted disk write.
+ const seasonsPatch = seasons.length > 0
+ ? { seasons: sanitizeSeasonList(mergeSeasons(
+ Array.isArray(series.seasons) ? series.seasons : [],
+ seasons,
+ )) }
+ : {};
+ updatedSeries = await updateSeries(series.id, {
+ ...(sanitizedArc ? { arc: sanitizedArc } : {}),
+ ...seasonsPatch,
+ });
+ }
+
+ // seasonNumber → season-record map; missing seasonNumber falls through
+ // to the LOWEST-NUMBERED season (not array-position [0]), or null when no
+ // seasons exist. mergeSeasons returns `[...retained, ...incomingBuilt]`
+ // — retained existing seasons come first regardless of number, so an
+ // import that adds season 1 to a series already holding [2, 3] would
+ // otherwise pick season 2 as "first" and surprise the user.
+ const seasonByNumber = new Map();
+ for (const s of (updatedSeries.seasons || [])) {
+ if (Number.isFinite(s.number)) seasonByNumber.set(s.number, s);
+ }
+ const sortedSeasons = [...(updatedSeries.seasons || [])]
+ .filter((s) => Number.isFinite(s.number))
+ .sort((a, b) => a.number - b.number);
+ const fallbackSeason = sortedSeasons[0] || null;
+ const fallbackSeasonId = fallbackSeason?.id || null;
+
+ const createdIssueIds = [];
+ // Surface season-remap events so the UI can warn "issue 3 wanted season 5
+ // but landed in S2 — Diaspora." Each entry carries the actual landed
+ // season's number + title so the client toast can be specific, not just
+ // "first season" (which can lie when seasons are sparsely numbered).
+ const remappedIssues = [];
+
+ // Thread C fix — issue-loop with rollback on failure. The universe +
+ // series are already written above. If createIssue throws mid-loop (e.g.
+ // transient FS error) we delete every issue created so far and re-throw,
+ // leaving the universe + series in their updated state but with no partial
+ // issue set. The universe + series writes are kept because they represent
+ // user-confirmed data; only the issue set is all-or-nothing from the
+ // commit's perspective.
+ try {
+ for (const proposal of issuesWithPositions) {
+ let seasonId = fallbackSeasonId;
+ if (proposal.seasonNumber != null) {
+ const matched = seasonByNumber.get(proposal.seasonNumber);
+ if (matched) {
+ seasonId = matched.id;
+ } else {
+ remappedIssues.push({
+ title: proposal.title,
+ arcPosition: proposal.arcPosition,
+ requestedSeasonNumber: proposal.seasonNumber,
+ actualSeasonId: fallbackSeasonId,
+ // Surface the landed season's number + title so the UI can
+ // render a precise toast ("Issue 'Cold Iron' landed in S2 —
+ // Diaspora") instead of an inaccurate "first season".
+ actualSeasonNumber: fallbackSeason?.number ?? null,
+ actualSeasonTitle: fallbackSeason?.title ?? null,
+ });
+ }
+ }
+ // Bundle stage seeds into the initial createIssue payload so the
+ // serialized write tail handles one write per issue instead of
+ // create + updateStage(prose) + updateStage(idea).
+ const stages = {};
+ if (proposal.proseExcerpt) {
+ stages.prose = { status: 'ready', output: proposal.proseExcerpt };
+ }
+ const ideaSeed = [
+ proposal.logline && `Logline: ${proposal.logline}`,
+ proposal.synopsis && `Synopsis: ${proposal.synopsis}`,
+ ].filter(Boolean).join('\n\n');
+ if (ideaSeed) {
+ // `idea` is seeded with input only — the user/LLM still needs to
+ // run the idea stage to produce `output`. `isStageReady` requires
+ // both `status in {'ready','edited'}` AND non-empty output, so
+ // marking 'ready' here would mislabel it to status-only consumers
+ // while failing readiness predicates downstream. 'empty' matches
+ // the actual state: input present, generation not yet performed.
+ stages.idea = { status: 'empty', input: ideaSeed };
+ }
+ const issue = await createIssue({
+ seriesId: updatedSeries.id,
+ title: proposal.title,
+ seasonId,
+ arcPosition: proposal.arcPosition,
+ arcRole: proposal.arcRole,
+ stages,
+ });
+ createdIssueIds.push(issue.id);
+ }
+ } catch (issueErr) {
+ // Roll back any issues already written so the system isn't left with a
+ // partial issue set. Rollback failures are logged but don't mask the
+ // original error — the user gets the real error and can re-commit.
+ for (const id of createdIssueIds) {
+ await deleteIssue(id).catch((delErr) =>
+ console.error(`❌ commitImport rollback: failed to delete issue ${id}: ${delErr.message}`),
+ );
+ }
+ // Surface a distinct code + message so the UI can tell the user that the
+ // universe and series were saved but the issues were rolled back. Retrying
+ // commit is safe: universe/series merges are idempotent and season ids are
+ // stable, so only the issue creation re-runs.
+ const n = issues.length;
+ const partial = Object.assign(
+ new Error(
+ `The universe and series were updated successfully, but ${createdIssueIds.length} of ${n} issue${n === 1 ? '' : 's'} failed and were rolled back — retry to create the remaining issues. (Original error: ${issueErr.message})`,
+ ),
+ { code: ERR_PARTIAL_COMMIT_ISSUES },
+ );
+ throw partial;
+ }
+
+ return {
+ universe: updatedUniverse,
+ series: updatedSeries,
+ createdIssueIds,
+ remappedIssues,
+ };
+}
+
diff --git a/server/services/importer.test.js b/server/services/importer.test.js
new file mode 100644
index 0000000000..092688e469
--- /dev/null
+++ b/server/services/importer.test.js
@@ -0,0 +1,893 @@
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { mkdtempSync, rmSync, readdirSync, unlinkSync, existsSync, statSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+// Create the tempRoot at top-level so PATHS.data resolves before any
+// service module runs its `const STATE_PATH = join(PATHS.data, ...)` at
+// import time. universeBuilder.js reads PATHS.data eagerly at module init,
+// so a per-test `let tempRoot = mkdtempSync()` would land too late.
+//
+// Vitest module-scoping caveat: this mock is sticky for the entire worker
+// — every service this file imports (universeBuilder, series, issues)
+// captures the redirected PATHS at THEIR module init. Any other test file
+// loaded by the same Vitest worker that imports those same services will
+// inherit our redirected PATHS through the shared module cache. Vitest's
+// default `pool: 'forks'` isolates by-file so this is safe today; if the
+// project ever switches to `pool: 'threads'` with shared module caches,
+// this file should be wrapped in `vi.isolate()` or moved into its own
+// project to avoid cross-test PATHS leakage.
+const tempRoot = mkdtempSync(join(tmpdir(), 'importer-test-'));
+
+// Mock fileUtils.js so every PATHS member points under tempRoot — not
+// just `data`. The importer's transitive imports (universeBuilder,
+// series, issues, runner) only touch PATHS.data today, but if a future
+// change starts writing under PATHS.logs / PATHS.runs / PATHS.cache,
+// those writes would leak into the developer's working tree under the
+// previous "override data only" pattern. Redirecting every key keeps
+// tests hermetic regardless of which PATHS member the SUT picks up.
+//
+// Spread the actual exports into a plain object — matches the pattern
+// used by bibleExtractor.test.js + sceneExtractor.test.js. A Proxy over
+// the ESM namespace exotic object that `vi.importActual` returns is
+// brittle: it intercepts only `get`, can bypass `[[Module]]` invariants
+// Vitest's transform expects, and behaves unpredictably for
+// `Symbol.toStringTag` / re-exports.
+vi.mock('../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../lib/fileUtils.js');
+ const redirectedPaths = Object.fromEntries(
+ Object.keys(actual.PATHS).map((k) => [k, join(tempRoot, k)]),
+ );
+ return {
+ ...actual,
+ PATHS: redirectedPaths,
+ };
+});
+
+// Mock runStagedLLM so tests never hit a real provider — every importer
+// LLM call resolves to a canned JSON shape we control per-test.
+const mockRunStagedLLM = vi.fn();
+vi.mock('../lib/stageRunner.js', () => ({
+ runStagedLLM: (...args) => mockRunStagedLLM(...args),
+}));
+
+// Mock `./pipeline/issues.js` so a single test can force `createIssue` to
+// throw mid-loop and exercise the ERR_PARTIAL_COMMIT_ISSUES rollback path.
+// `vi.hoisted` keeps the mock fn ref reachable from both the mock factory
+// (hoisted before imports) and the beforeEach reset (runs later). Default
+// behavior passes through to the real module so the dozen other tests that
+// expect real createIssue behavior keep working unchanged.
+const { mockCreateIssue, realIssuesRef } = vi.hoisted(() => ({
+ mockCreateIssue: vi.fn(),
+ realIssuesRef: { current: null },
+}));
+vi.mock('./pipeline/issues.js', async () => {
+ const actual = await vi.importActual('./pipeline/issues.js');
+ realIssuesRef.current = actual;
+ return {
+ ...actual,
+ createIssue: (...args) => mockCreateIssue(...args),
+ };
+});
+
+const importerSvc = await import('./importer.js');
+const universeSvc = await import('./universeBuilder.js');
+const seriesSvc = await import('./pipeline/series.js');
+const issuesSvc = await import('./pipeline/issues.js');
+
+// Per-test: wipe every file under tempRoot so each test starts with a clean
+// data dir. We can't rmSync the dir itself because the universeBuilder
+// state path is captured at module init.
+function wipeTempRoot() {
+ for (const entry of readdirSync(tempRoot)) {
+ const full = join(tempRoot, entry);
+ const stat = statSync(full);
+ if (stat.isFile()) unlinkSync(full);
+ else rmSync(full, { recursive: true, force: true });
+ }
+}
+
+beforeEach(() => {
+ wipeTempRoot();
+ mockRunStagedLLM.mockReset();
+ // Default createIssue to pass-through to the real module — only the
+ // rollback test overrides this to inject a mid-loop throw.
+ mockCreateIssue.mockReset();
+ mockCreateIssue.mockImplementation((...args) => realIssuesRef.current.createIssue(...args));
+});
+
+afterAll(() => {
+ if (existsSync(tempRoot)) rmSync(tempRoot, { recursive: true, force: true });
+});
+
+// ---------------------------------------------------------------------------
+// findOrCreate helpers
+// ---------------------------------------------------------------------------
+
+describe('findUniverseByName', () => {
+ it('returns null when no universe matches', async () => {
+ expect(await importerSvc.findUniverseByName('Unknown')).toBeNull();
+ });
+
+ it('matches case-insensitively', async () => {
+ const made = await universeSvc.createUniverse({ name: 'Cyberpunk 2099' });
+ const found = await importerSvc.findUniverseByName('CYBERPUNK 2099');
+ expect(found).not.toBeNull();
+ expect(found.id).toBe(made.id);
+ });
+});
+
+describe('findSeriesByName', () => {
+ it('scopes the match to a universe', async () => {
+ const uniA = await universeSvc.createUniverse({ name: 'Universe A' });
+ const uniB = await universeSvc.createUniverse({ name: 'Universe B' });
+ await seriesSvc.createSeries({ name: 'Same Title', universeId: uniA.id });
+
+ // Match in universe A works.
+ const foundInA = await importerSvc.findSeriesByName('SAME TITLE', uniA.id);
+ expect(foundInA).not.toBeNull();
+ expect(foundInA.universeId).toBe(uniA.id);
+
+ // Same name in a different universe is NOT a match.
+ const foundInB = await importerSvc.findSeriesByName('Same Title', uniB.id);
+ expect(foundInB).toBeNull();
+ });
+});
+
+// ---------------------------------------------------------------------------
+// analyzeImport
+// ---------------------------------------------------------------------------
+
+const canonRunResponse = {
+ characters: [
+ { name: 'Aria', role: 'protagonist', physicalDescription: 'tall, freckles' },
+ ],
+ places: [
+ { name: 'The Foundry', slugline: 'INT. FOUNDRY — NIGHT', description: 'molten light' },
+ ],
+ objects: [
+ { name: 'The Locket', description: 'silver, dented', significance: "mother's keepsake" },
+ ],
+};
+
+const arcRunResponse = {
+ logline: 'A blacksmith chases a hidden inheritance.',
+ summary: 'Aria leaves the foundry to find her mother\'s past.',
+ protagonistArc: 'Reluctant heir grows into reluctant leader.',
+ themes: ['legacy', 'craft'],
+ shape: 'man-in-hole',
+ seasons: [
+ { number: 1, title: 'Foundry', logline: 'Aria leaves home.', synopsis: 'opening', endingHook: '' },
+ ],
+};
+
+const issuesRunResponse = {
+ issues: [
+ {
+ title: 'Cold Iron',
+ arcPosition: 1,
+ arcRole: 'pilot',
+ logline: 'The forge dies.',
+ synopsis: 'Aria finds the letter.',
+ proseExcerpt: 'The vault loomed in the dark.',
+ },
+ ],
+};
+
+function wireDefaultLLMResponses() {
+ // Mock per-stage so the call order doesn't matter — important because
+ // analyze fires canon + arc in parallel.
+ mockRunStagedLLM.mockImplementation(async (stageName) => {
+ if (stageName === 'importer-canon-extract') {
+ return { content: canonRunResponse, model: 'mock', providerId: 'mock', runId: 'run-canon' };
+ }
+ if (stageName === 'importer-arc-extract') {
+ return { content: arcRunResponse, model: 'mock', providerId: 'mock', runId: 'run-arc' };
+ }
+ if (stageName === 'importer-issue-proposal') {
+ return { content: issuesRunResponse, model: 'mock', providerId: 'mock', runId: 'run-issues' };
+ }
+ throw new Error(`Unexpected stage: ${stageName}`);
+ });
+}
+
+describe('analyzeImport', () => {
+ it('creates universe + series on first run and returns preview shape', async () => {
+ wireDefaultLLMResponses();
+
+ const result = await importerSvc.analyzeImport({
+ universeName: 'Test Universe',
+ seriesName: 'Test Series',
+ contentType: 'short-story',
+ source: 'The vault loomed in the dark.',
+ });
+
+ expect(result.isExistingUniverse).toBe(false);
+ expect(result.isExistingSeries).toBe(false);
+ expect(result.universe.id).toBeDefined();
+ expect(result.series.id).toMatch(/^ser-/);
+ expect(result.series.universeId).toBe(result.universe.id);
+ expect(result.canonPreview.characters).toHaveLength(1);
+ expect(result.canonPreview.characters[0].name).toBe('Aria');
+ expect(result.canonPreview.places).toHaveLength(1);
+ expect(result.canonPreview.objects).toHaveLength(1);
+ expect(result.arcPreview.shape).toBe('man-in-hole');
+ expect(result.seasonsPreview).toHaveLength(1);
+ expect(result.issueProposals).toHaveLength(1);
+ expect(result.runIds).toEqual({ canon: 'run-canon', arc: 'run-arc', issues: 'run-issues' });
+ });
+
+ it('reuses existing universe + series on a second analyze with same names', async () => {
+ wireDefaultLLMResponses();
+ const first = await importerSvc.analyzeImport({
+ universeName: 'Test U',
+ seriesName: 'Test S',
+ contentType: 'short-story',
+ source: 'first',
+ });
+ const second = await importerSvc.analyzeImport({
+ universeName: 'TEST U', // case-insensitive
+ seriesName: 'test s',
+ contentType: 'short-story',
+ source: 'second',
+ });
+ expect(second.isExistingUniverse).toBe(true);
+ expect(second.isExistingSeries).toBe(true);
+ expect(second.universe.id).toBe(first.universe.id);
+ expect(second.series.id).toBe(first.series.id);
+ });
+
+ it('rejects oversized source with ERR_VALIDATION before calling the LLM', async () => {
+ wireDefaultLLMResponses();
+ let caught;
+ try {
+ await importerSvc.analyzeImport({
+ universeName: 'U',
+ seriesName: 'S',
+ contentType: 'novel',
+ source: 'x'.repeat(importerSvc.IMPORTER_SOURCE_CHAR_LIMIT + 1),
+ });
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeDefined();
+ expect(caught.code).toBe(importerSvc.ERR_VALIDATION);
+ expect(mockRunStagedLLM).not.toHaveBeenCalled();
+ });
+
+ it('passes returnsJson:true so the stage runner parses the LLM reply', async () => {
+ // Regression-pin: without `returnsJson: true`, runStagedLLM returns the
+ // raw text and the orchestrator's `Array.isArray(content?.field)` checks
+ // all silently fail (preview becomes empty). Lock the opt in by asserting
+ // every analyze stage call passes it.
+ wireDefaultLLMResponses();
+ await importerSvc.analyzeImport({
+ universeName: 'U', seriesName: 'S', contentType: 'short-story', source: 'x',
+ });
+ expect(mockRunStagedLLM).toHaveBeenCalled();
+ for (const call of mockRunStagedLLM.mock.calls) {
+ const opts = call[2];
+ expect(opts).toMatchObject({ returnsJson: true });
+ }
+ });
+
+ it('forwards Mustache section-guard flags so per-content-type prompt blocks render', async () => {
+ // Regression-pin: PortOS's template engine is Mustache-only — the prompts
+ // use `{{#isShortStory}}…{{/isShortStory}}` blocks, so the orchestrator
+ // must pass per-type booleans alongside the contentType string.
+ wireDefaultLLMResponses();
+ await importerSvc.analyzeImport({
+ universeName: 'U', seriesName: 'S', contentType: 'novel', source: 'x',
+ });
+ const firstVars = mockRunStagedLLM.mock.calls[0][1];
+ expect(firstVars).toMatchObject({
+ isNovel: true,
+ isShortStory: false,
+ isScreenplay: false,
+ isComicScript: false,
+ });
+ });
+
+ it('rejects a locked-arc series with ERR_LOCKED before calling the LLM', async () => {
+ // Pre-seed a series with locked.arc, then re-analyze with its name.
+ const uni = await universeSvc.createUniverse({ name: 'Locked U' });
+ const seeded = await seriesSvc.createSeries({ name: 'Locked S', universeId: uni.id });
+ await seriesSvc.updateSeries(seeded.id, { locked: { arc: true } });
+
+ wireDefaultLLMResponses();
+ let caught;
+ try {
+ await importerSvc.analyzeImport({
+ universeName: 'Locked U',
+ seriesName: 'Locked S',
+ contentType: 'short-story',
+ source: 'anything',
+ });
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeDefined();
+ expect(caught.code).toBe(importerSvc.ERR_LOCKED);
+ expect(mockRunStagedLLM).not.toHaveBeenCalled();
+ });
+});
+
+// ---------------------------------------------------------------------------
+// commitImport
+// ---------------------------------------------------------------------------
+
+async function setupForCommit() {
+ // Create the universe + series the analyze phase would have created, then
+ // exercise commitImport directly with a hand-shaped payload.
+ const uni = await universeSvc.createUniverse({ name: 'Commit U' });
+ const ser = await seriesSvc.createSeries({ name: 'Commit S', universeId: uni.id });
+ return { uni, ser };
+}
+
+describe('commitImport', () => {
+ it('happy path: merges canon, writes arc + seasons, creates issues with prose seeded', async () => {
+ const { uni, ser } = await setupForCommit();
+ const result = await importerSvc.commitImport({
+ universeId: uni.id,
+ seriesId: ser.id,
+ canonSelections: {
+ characters: [{ name: 'Aria', role: 'protagonist', physicalDescription: 'tall' }],
+ places: [{ name: 'The Foundry', slugline: 'INT. FOUNDRY — NIGHT', description: 'molten' }],
+ objects: [{ name: 'The Locket', significance: 'heirloom' }],
+ },
+ arc: {
+ logline: 'A reluctant heir.',
+ summary: 'Big story.',
+ protagonistArc: 'Growth.',
+ themes: ['legacy'],
+ shape: 'man-in-hole',
+ },
+ seasons: [
+ { number: 1, title: 'Foundry', logline: 'Open', synopsis: 'a', endingHook: '' },
+ ],
+ issues: [
+ {
+ title: 'Cold Iron',
+ arcPosition: 1,
+ arcRole: 'pilot',
+ logline: 'Forge dies.',
+ synopsis: 'Aria finds the letter.',
+ proseExcerpt: 'The vault loomed in the dark.',
+ },
+ ],
+ });
+
+ // Universe canon was merged.
+ expect(result.universe.characters.find((c) => c.name === 'Aria')).toBeDefined();
+ expect(result.universe.settings.find((s) => s.name === 'The Foundry')).toBeDefined();
+ expect(result.universe.objects.find((o) => o.name === 'The Locket')).toBeDefined();
+ // Series got arc + seasons.
+ expect(result.series.arc.shape).toBe('man-in-hole');
+ expect(result.series.seasons).toHaveLength(1);
+ expect(result.series.seasons[0].title).toBe('Foundry');
+ // One issue created with prose + idea seeded.
+ expect(result.createdIssueIds).toHaveLength(1);
+ const issue = await issuesSvc.getIssue(result.createdIssueIds[0]);
+ expect(issue.title).toBe('Cold Iron');
+ expect(issue.seriesId).toBe(ser.id);
+ expect(issue.stages.prose.output).toBe('The vault loomed in the dark.');
+ expect(issue.stages.prose.status).toBe('ready');
+ expect(issue.stages.idea.input).toContain('Logline: Forge dies.');
+ expect(issue.stages.idea.input).toContain('Synopsis: Aria finds the letter.');
+ // Issue was wired to the first season.
+ expect(issue.seasonId).toBe(result.series.seasons[0].id);
+ });
+
+ it('refuses to commit when the series arc is locked', async () => {
+ const { uni, ser } = await setupForCommit();
+ await seriesSvc.updateSeries(ser.id, { locked: { arc: true } });
+ let caught;
+ try {
+ await importerSvc.commitImport({
+ universeId: uni.id,
+ seriesId: ser.id,
+ canonSelections: { characters: [], places: [], objects: [] },
+ arc: { logline: 'x', summary: 'y' },
+ seasons: [],
+ issues: [{ title: 'I1', arcPosition: 1, proseExcerpt: 'p' }],
+ });
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeDefined();
+ expect(caught.code).toBe(importerSvc.ERR_LOCKED);
+ // No issues were created.
+ const issuesAfter = await issuesSvc.listIssues({ seriesId: ser.id });
+ expect(issuesAfter).toHaveLength(0);
+ });
+
+ it('LWW-merges canon by name — second commit does not duplicate a known character', async () => {
+ const { uni, ser } = await setupForCommit();
+ // Seed Aria once.
+ await importerSvc.commitImport({
+ universeId: uni.id,
+ seriesId: ser.id,
+ canonSelections: {
+ characters: [{ name: 'Aria', role: 'protagonist', physicalDescription: 'tall' }],
+ places: [],
+ objects: [],
+ },
+ arc: null,
+ seasons: [],
+ issues: [{ title: 'I1', arcPosition: 1, proseExcerpt: 'p1' }],
+ });
+ // Commit a second pass with Aria again (different case + no description
+ // to exercise the userEditable-blank rule).
+ const second = await importerSvc.commitImport({
+ universeId: uni.id,
+ seriesId: ser.id,
+ canonSelections: {
+ characters: [{ name: 'ARIA', role: 'protagonist' }],
+ places: [],
+ objects: [],
+ },
+ arc: null,
+ seasons: [],
+ issues: [{ title: 'I2', arcPosition: 2, proseExcerpt: 'p2' }],
+ });
+ const ariaEntries = second.universe.characters.filter((c) => c.name.toLowerCase() === 'aria');
+ expect(ariaEntries).toHaveLength(1);
+ // Original physicalDescription preserved (mergeExtractedBible doesn't
+ // overwrite non-blank userEditable fields).
+ expect(ariaEntries[0].physicalDescription).toBe('tall');
+ });
+
+ it('refuses commit when the issues array is empty', async () => {
+ const { uni, ser } = await setupForCommit();
+ let caught;
+ try {
+ await importerSvc.commitImport({
+ universeId: uni.id,
+ seriesId: ser.id,
+ canonSelections: { characters: [], places: [], objects: [] },
+ arc: null,
+ seasons: [],
+ issues: [],
+ });
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeDefined();
+ expect(caught.code).toBe(importerSvc.ERR_VALIDATION);
+ });
+
+ it('refuses commit when at least one issue in the array is missing a title', async () => {
+ // Exercises the per-entry title validation loop (importer.js lines 315-323).
+ // A non-empty issues array where one entry has no title must be rejected
+ // fail-fast, before any state is written to disk.
+ const { uni, ser } = await setupForCommit();
+ let caught;
+ try {
+ await importerSvc.commitImport({
+ universeId: uni.id,
+ seriesId: ser.id,
+ canonSelections: { characters: [], places: [], objects: [] },
+ arc: null,
+ seasons: [],
+ issues: [
+ { title: 'Valid Issue', arcPosition: 1, proseExcerpt: 'p1' },
+ { title: '', arcPosition: 2, proseExcerpt: 'p2' },
+ ],
+ });
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeDefined();
+ expect(caught.code).toBe(importerSvc.ERR_VALIDATION);
+ expect(caught.message).toMatch(/position 2/i);
+ // Confirm no issues were created — the fail-fast guard prevented any write.
+ const issuesAfter = await issuesSvc.listIssues({ seriesId: ser.id });
+ expect(issuesAfter).toHaveLength(0);
+ });
+
+ it('second-pass seasons are MERGED into existing seasons, not replaced', async () => {
+ // Regression guard for importer.js:360 destructive-replace behavior.
+ // Both passes supply non-empty seasons arrays; after the second commit the
+ // series must contain seasons from BOTH calls (merge), not just the second.
+ //
+ // NOTE: this test asserts the intended post-fix MERGE behavior. If the
+ // parallel agent's merge fix in importer.js has not landed yet, this test
+ // will fail loudly — that is the correct signal.
+ const { uni, ser } = await setupForCommit();
+
+ // First pass: season 1.
+ const first = await importerSvc.commitImport({
+ universeId: uni.id,
+ seriesId: ser.id,
+ canonSelections: { characters: [], places: [], objects: [] },
+ arc: null,
+ seasons: [{ number: 1, title: 'Season One', logline: 'Beginning', synopsis: 'a', endingHook: '' }],
+ issues: [{ title: 'I1', arcPosition: 1, proseExcerpt: 'p1' }],
+ });
+ expect(first.series.seasons).toHaveLength(1);
+ expect(first.series.seasons[0].title).toBe('Season One');
+
+ // Second pass: season 2 — the importer must MERGE this with season 1.
+ const second = await importerSvc.commitImport({
+ universeId: uni.id,
+ seriesId: ser.id,
+ canonSelections: { characters: [], places: [], objects: [] },
+ arc: null,
+ seasons: [{ number: 2, title: 'Season Two', logline: 'Escalation', synopsis: 'b', endingHook: '' }],
+ issues: [{ title: 'I2', arcPosition: 2, proseExcerpt: 'p2' }],
+ });
+
+ // After merge: series must contain both seasons.
+ expect(second.series.seasons).toHaveLength(2);
+ const titles = second.series.seasons.map((s) => s.title);
+ expect(titles).toContain('Season One');
+ expect(titles).toContain('Season Two');
+ // Season numbers must also be preserved correctly.
+ const s1 = second.series.seasons.find((s) => s.number === 1);
+ const s2 = second.series.seasons.find((s) => s.number === 2);
+ expect(s1).toBeDefined();
+ expect(s2).toBeDefined();
+ });
+
+ // Round-12 review: cross-universe guard must refuse commit when the
+ // series has NO universeId (legacy / hand-edited data), not just when
+ // it differs. Previously a falsy universeId silently bypassed the
+ // guard and let the importer re-home the series.
+ it('refuses commit when the series has no universeId', async () => {
+ const uni = await universeSvc.createUniverse({ name: 'Linkless U' });
+ const ser = await seriesSvc.createSeries({ name: 'Linkless S' });
+ // sanitizeSeries normalizes a missing universeId to null. Confirm
+ // the precondition before exercising the guard.
+ expect(ser.universeId).toBeFalsy();
+ let caught;
+ try {
+ await importerSvc.commitImport({
+ universeId: uni.id, seriesId: ser.id,
+ canonSelections: { characters: [], places: [], objects: [] },
+ arc: null,
+ seasons: [],
+ issues: [{ title: 'I1', arcPosition: 1, proseExcerpt: 'p' }],
+ });
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeDefined();
+ expect(caught.code).toBe(importerSvc.ERR_VALIDATION);
+ expect(caught.message).toMatch(/no universeId/i);
+ });
+
+ // Round-10 review: round-9's auto-assign fix only covered the omitted
+ // case. An incoming issue that EXPLICITLY sets `arcPosition: 1` while
+ // the series already holds an issue at position 1 must be rejected
+ // fail-fast, not silently land a duplicate.
+ it('refuses commit when an explicit arcPosition collides with an existing issue', async () => {
+ const { uni, ser } = await setupForCommit();
+ await importerSvc.commitImport({
+ universeId: uni.id, seriesId: ser.id,
+ canonSelections: { characters: [], places: [], objects: [] },
+ arc: null,
+ seasons: [],
+ issues: [{ title: 'I1', arcPosition: 1, proseExcerpt: 'p1' }],
+ });
+ let caught;
+ try {
+ await importerSvc.commitImport({
+ universeId: uni.id, seriesId: ser.id,
+ canonSelections: { characters: [], places: [], objects: [] },
+ arc: null,
+ seasons: [],
+ // Explicit arcPosition 1 — already used by I1 above.
+ issues: [{ title: 'Collision', arcPosition: 1, proseExcerpt: 'p2' }],
+ });
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeDefined();
+ expect(caught.code).toBe(importerSvc.ERR_VALIDATION);
+ expect(caught.message).toMatch(/collides with an existing issue/i);
+ // No issue created — the gate fires before createIssue.
+ const all = await issuesSvc.listIssues({ seriesId: ser.id });
+ expect(all).toHaveLength(1);
+ });
+
+ // Round-9 review: arcPosition auto-assign must seed `nextFreeArcPos`
+ // from the union of explicit incoming positions AND pre-existing
+ // series.issues[].arcPosition — re-import on a series that already
+ // has issues at [1..3] would otherwise auto-assign starting at 1 again
+ // and create duplicate positions silently.
+ it('arcPosition auto-assign on re-import skips arcPositions already used by existing issues', async () => {
+ const { uni, ser } = await setupForCommit();
+ // First pass: seed three issues at arcPositions 1, 2, 3.
+ await importerSvc.commitImport({
+ universeId: uni.id, seriesId: ser.id,
+ canonSelections: { characters: [], places: [], objects: [] },
+ arc: null,
+ seasons: [],
+ issues: [
+ { title: 'I1', arcPosition: 1, proseExcerpt: 'p1' },
+ { title: 'I2', arcPosition: 2, proseExcerpt: 'p2' },
+ { title: 'I3', arcPosition: 3, proseExcerpt: 'p3' },
+ ],
+ });
+ // Second pass: two new issues with NO arcPosition. Must auto-assign
+ // to 4 and 5, not collide with 1 and 2.
+ const second = await importerSvc.commitImport({
+ universeId: uni.id, seriesId: ser.id,
+ canonSelections: { characters: [], places: [], objects: [] },
+ arc: null,
+ seasons: [],
+ issues: [
+ { title: 'I4 — auto', proseExcerpt: 'p4' },
+ { title: 'I5 — auto', proseExcerpt: 'p5' },
+ ],
+ });
+ expect(second.createdIssueIds).toHaveLength(2);
+ const i4 = await issuesSvc.getIssue(second.createdIssueIds[0]);
+ const i5 = await issuesSvc.getIssue(second.createdIssueIds[1]);
+ expect(i4.arcPosition).toBe(4);
+ expect(i5.arcPosition).toBe(5);
+ // And the full series now has 5 issues, no collisions on arcPosition.
+ const allIssues = await issuesSvc.listIssues({ seriesId: ser.id });
+ const positions = allIssues.map((i) => i.arcPosition).sort((a, b) => a - b);
+ expect(positions).toEqual([1, 2, 3, 4, 5]);
+ });
+
+ // Round-8 review: fallbackSeasonId must pick the LOWEST-NUMBERED season,
+ // not array-position [0]. After mergeSeasons the array order is
+ // `[...retained, ...incomingBuilt]` — retained existing seasons come
+ // first regardless of number, so a series with [season 2, season 3] that
+ // receives a new season 1 would otherwise pick season 2 as "fallback".
+ it('fallbackSeasonId picks the lowest-numbered season, not array[0]', async () => {
+ const { uni, ser } = await setupForCommit();
+
+ // First pass: seed seasons 2 and 3 (skip 1).
+ await importerSvc.commitImport({
+ universeId: uni.id, seriesId: ser.id,
+ canonSelections: { characters: [], places: [], objects: [] },
+ arc: null,
+ seasons: [
+ { number: 2, title: 'Two', logline: 'a', synopsis: '', endingHook: '' },
+ { number: 3, title: 'Three', logline: 'b', synopsis: '', endingHook: '' },
+ ],
+ issues: [{ title: 'I1', arcPosition: 1, proseExcerpt: 'p1' }],
+ });
+
+ // Second pass: add season 1 + an issue with no seasonNumber. The
+ // fallback must land it in season 1 (the new lowest), even though
+ // mergeSeasons returns [retained_2, retained_3, new_1] in that order.
+ const second = await importerSvc.commitImport({
+ universeId: uni.id, seriesId: ser.id,
+ canonSelections: { characters: [], places: [], objects: [] },
+ arc: null,
+ seasons: [{ number: 1, title: 'One', logline: 'c', synopsis: '', endingHook: '' }],
+ issues: [{ title: 'I-no-season', arcPosition: 4, proseExcerpt: 'p4' }],
+ });
+
+ const created = await issuesSvc.getIssue(second.createdIssueIds[0]);
+ const seasonOne = second.series.seasons.find((s) => s.number === 1);
+ expect(seasonOne).toBeDefined();
+ expect(created.seasonId).toBe(seasonOne.id);
+ });
+
+ // Round-8 review: remappedIssues entries now carry actualSeasonNumber
+ // and actualSeasonTitle so the client toast can name the season
+ // precisely instead of saying a generic "first season".
+ it('remappedIssues entries carry actualSeasonNumber + actualSeasonTitle', async () => {
+ const { uni, ser } = await setupForCommit();
+ // Seed season 1 only; the next commit references a non-existent season 99
+ // — the issue must land in season 1 and the remap entry must surface it.
+ const result = await importerSvc.commitImport({
+ universeId: uni.id, seriesId: ser.id,
+ canonSelections: { characters: [], places: [], objects: [] },
+ arc: null,
+ seasons: [{ number: 1, title: 'Foundry', logline: 'open', synopsis: '', endingHook: '' }],
+ issues: [
+ { title: 'A', arcPosition: 1, seasonNumber: 99, proseExcerpt: 'pa' },
+ ],
+ });
+ expect(result.remappedIssues).toHaveLength(1);
+ const remap = result.remappedIssues[0];
+ expect(remap.requestedSeasonNumber).toBe(99);
+ expect(remap.actualSeasonNumber).toBe(1);
+ expect(remap.actualSeasonTitle).toBe('Foundry');
+ expect(remap.actualSeasonId).toBeDefined();
+ });
+
+ // Round-8 review: missing test for the ERR_PARTIAL_COMMIT_ISSUES rollback
+ // path. Inject a createIssue failure on the 2nd of 3 issues; assert that
+ // the rollback deletes the 1st (already created), surfaces the partial
+ // code, and leaves the universe + series writes intact (those are
+ // idempotent + user-confirmed, so we don't roll them back).
+ it('rolls back created issues + throws ERR_PARTIAL_COMMIT_ISSUES when createIssue fails mid-loop', async () => {
+ const { uni, ser } = await setupForCommit();
+ let call = 0;
+ mockCreateIssue.mockImplementation(async (...args) => {
+ call++;
+ if (call === 2) throw new Error('simulated mid-loop FS error');
+ return realIssuesRef.current.createIssue(...args);
+ });
+
+ let caught;
+ try {
+ await importerSvc.commitImport({
+ universeId: uni.id, seriesId: ser.id,
+ canonSelections: { characters: [{ name: 'Aria' }], places: [], objects: [] },
+ arc: { logline: 'A', summary: 'S', shape: 'man-in-hole' },
+ seasons: [{ number: 1, title: 'S1', logline: '', synopsis: '', endingHook: '' }],
+ issues: [
+ { title: 'I1', arcPosition: 1, proseExcerpt: 'p1' },
+ { title: 'I2', arcPosition: 2, proseExcerpt: 'p2' },
+ { title: 'I3', arcPosition: 3, proseExcerpt: 'p3' },
+ ],
+ });
+ } catch (err) {
+ caught = err;
+ }
+
+ expect(caught).toBeDefined();
+ expect(caught.code).toBe('IMPORTER_PARTIAL_COMMIT_ISSUES');
+ expect(caught.message).toMatch(/universe and series were updated/i);
+ expect(caught.message).toMatch(/simulated mid-loop FS error/);
+
+ // Universe + series writes survive (user-confirmed, idempotent).
+ const universeAfter = await universeSvc.getUniverse(uni.id);
+ expect(universeAfter.characters.some((c) => c.name === 'Aria')).toBe(true);
+ const seriesAfter = await seriesSvc.getSeries(ser.id);
+ expect(seriesAfter.arc?.shape).toBe('man-in-hole');
+ expect(seriesAfter.seasons).toHaveLength(1);
+
+ // No leftover issues from the partial loop.
+ const issuesAfter = await issuesSvc.listIssues({ seriesId: ser.id });
+ expect(issuesAfter).toHaveLength(0);
+ });
+});
+
+describe('mergeSeasons (pure helper)', () => {
+ const stubBuildSeason = (input) => ({
+ id: `built-${input.number}`,
+ number: input.number,
+ title: input.title,
+ logline: input.logline,
+ synopsis: input.synopsis,
+ endingHook: input.endingHook,
+ episodeCountTarget: input.episodeCountTarget,
+ status: input.status,
+ createdAt: '2025-01-01T00:00:00.000Z',
+ updatedAt: '2025-01-01T00:00:00.000Z',
+ });
+
+ it('auto-assigns sequential numbers when incoming seasons omit number', () => {
+ const incoming = [
+ { title: 'A' },
+ { title: 'B' },
+ { title: 'C' },
+ ];
+ const result = importerSvc.mergeSeasons([], incoming, stubBuildSeason);
+ const numbers = result.map((s) => s.number).sort((a, b) => a - b);
+ expect(numbers).toEqual([1, 2, 3]);
+ });
+
+ it('preserves existing ids when incoming season number matches', () => {
+ const existing = [
+ { id: 'existing-1', number: 1, title: 'Old', logline: '', synopsis: '', updatedAt: '2020-01-01T00:00:00.000Z' },
+ ];
+ const incoming = [{ number: 1, title: 'Old', logline: '', synopsis: '' }];
+ const result = importerSvc.mergeSeasons(existing, incoming, stubBuildSeason);
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('existing-1');
+ });
+
+ it('bumps updatedAt only when an importable field changes', () => {
+ const existing = [
+ { id: 'e1', number: 1, title: 'Original', logline: 'L1', synopsis: 'S1', updatedAt: '2020-01-01T00:00:00.000Z' },
+ ];
+ // No change → updatedAt preserved
+ const noChange = importerSvc.mergeSeasons(existing, [{ number: 1, title: 'Original' }], stubBuildSeason);
+ expect(noChange[0].updatedAt).toBe('2020-01-01T00:00:00.000Z');
+ // Title change → updatedAt bumped (to a value newer than the original)
+ const titleChange = importerSvc.mergeSeasons(existing, [{ number: 1, title: 'New title' }], stubBuildSeason);
+ expect(titleChange[0].updatedAt > '2020-01-01T00:00:00.000Z').toBe(true);
+ });
+
+ it('retains existing seasons that the incoming list does not touch', () => {
+ const existing = [
+ { id: 'e1', number: 1, title: 'One', logline: '', synopsis: '' },
+ { id: 'e2', number: 2, title: 'Two', logline: '', synopsis: '' },
+ ];
+ const incoming = [{ number: 1, title: 'One updated' }];
+ const result = importerSvc.mergeSeasons(existing, incoming, stubBuildSeason);
+ expect(result).toHaveLength(2);
+ expect(result.find((s) => s.number === 2)?.id).toBe('e2');
+ });
+
+ it('skips over existing numbers when auto-assigning', () => {
+ const existing = [
+ { id: 'e1', number: 1, title: 'One', logline: '', synopsis: '' },
+ { id: 'e2', number: 3, title: 'Three', logline: '', synopsis: '' },
+ ];
+ const incoming = [{ title: 'New A' }, { title: 'New B' }];
+ const result = importerSvc.mergeSeasons(existing, incoming, stubBuildSeason);
+ const newNumbers = result.filter((s) => s.id.startsWith('built-')).map((s) => s.number).sort((a, b) => a - b);
+ // nextFree = max(1,3) + 1 = 4 → [4, 5]
+ expect(newNumbers).toEqual([4, 5]);
+ });
+
+ // Round-7 review: distinguish absent-vs-empty per CLAUDE.md's "LLM
+ // response merging" convention. An empty string is the user's intent
+ // to clear the field; null/undefined is the LLM omitting it and the
+ // existing value should win.
+ it('absent string fields (null/undefined) preserve the existing value', () => {
+ const existing = [
+ { id: 'e1', number: 1, title: 'Kept', logline: 'L', synopsis: 'S', endingHook: 'H', updatedAt: '2020-01-01T00:00:00.000Z' },
+ ];
+ const incoming = [{ number: 1, title: undefined, logline: null }];
+ const result = importerSvc.mergeSeasons(existing, incoming, stubBuildSeason);
+ expect(result[0].title).toBe('Kept');
+ expect(result[0].logline).toBe('L');
+ // No change in any tracked field → updatedAt preserved
+ expect(result[0].updatedAt).toBe('2020-01-01T00:00:00.000Z');
+ });
+
+ it('empty-string fields are treated as an intentional clear and bump updatedAt', () => {
+ const existing = [
+ { id: 'e1', number: 1, title: 'Original', logline: 'L', synopsis: 'S', endingHook: 'H', updatedAt: '2020-01-01T00:00:00.000Z' },
+ ];
+ const incoming = [{ number: 1, logline: '', synopsis: '' }];
+ const result = importerSvc.mergeSeasons(existing, incoming, stubBuildSeason);
+ expect(result[0].logline).toBe('');
+ expect(result[0].synopsis).toBe('');
+ // Title not present → preserved.
+ expect(result[0].title).toBe('Original');
+ // A clear is a change → updatedAt bumps.
+ expect(result[0].updatedAt > '2020-01-01T00:00:00.000Z').toBe(true);
+ });
+
+ it('throws ERR_VALIDATION when auto-assign would exceed the season number cap (99)', () => {
+ const existing = Array.from({ length: 99 }, (_, i) => ({
+ id: `e${i + 1}`, number: i + 1, title: `S${i + 1}`, logline: '', synopsis: '',
+ }));
+ let caught;
+ try {
+ importerSvc.mergeSeasons(existing, [{ title: 'overflow' }], stubBuildSeason);
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeDefined();
+ expect(caught.code).toBe(importerSvc.ERR_VALIDATION);
+ expect(caught.message).toContain('99');
+ });
+
+ // Round-11 review: legacy seasons with `title: undefined` would
+ // previously churn updatedAt on every no-op re-import — the change
+ // check compared `'Season N'` (the default applied to the new value)
+ // against `undefined` (the existing value), always producing a
+ // truthy diff. Fix applies the same default to both sides of the
+ // comparison so a re-import with no edits is correctly a no-op.
+ it('does NOT bump updatedAt for a legacy season with undefined title and no incoming edit', () => {
+ const existing = [
+ { id: 'e1', number: 1, /* title: undefined */ logline: '', synopsis: '', updatedAt: '2020-01-01T00:00:00.000Z' },
+ ];
+ // Incoming season omits every editable field — pure no-op.
+ const result = importerSvc.mergeSeasons(existing, [{ number: 1 }], stubBuildSeason);
+ expect(result[0].updatedAt).toBe('2020-01-01T00:00:00.000Z');
+ });
+
+ // Round-8 review: the pure helper now rejects duplicate explicit incoming
+ // numbers directly — commitImport's route gate caught this for HTTP
+ // callers, but a future direct consumer would otherwise silently collapse
+ // two entries sharing a number into one merge target.
+ it('throws ERR_VALIDATION on duplicate explicit incoming season numbers', () => {
+ let caught;
+ try {
+ importerSvc.mergeSeasons([], [
+ { number: 1, title: 'A' },
+ { number: 1, title: 'B' },
+ ], stubBuildSeason);
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeDefined();
+ expect(caught.code).toBe(importerSvc.ERR_VALIDATION);
+ expect(caught.message).toMatch(/duplicate/i);
+ });
+});