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): live progress, resilient + verbatim comic-script import

Adam Eivy3f309b2f5705
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d8183b6985..967bb7339f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -15,12 +15,16 @@ TBD
## Changed
- **Pick the AI provider & model for the Importer.** The Create → Importer intake form now has an "AI Provider & Model" picker (mirroring the Universe and Series builders), so the canon / arc / issue-split extraction can run on a specific provider and model instead of always using each stage's configured default. Leave it on "Default (stage provider)" to keep the prior behavior; the same selection also drives the content-type auto-detect pass.
+- **The Importer shows live progress while it analyzes.** Analyze runs several AI passes (canon + arc in parallel, then the issue split) over a single request that can take a couple of minutes, so it used to just sit on a spinner. The intake form now shows a live checklist — each pass moves from pending → running → done (✓) in real time — so you can see exactly which extraction is in flight.
+- **Comic scripts import verbatim — split, seeded, and rendered without rewriting.** A comic script is already issue/page-structured, so the Importer now (1) splits it on its existing `ISSUE` / `PAGE` headers — instantly, no LLM, no rephrasing (header-less scripts still fall back to the LLM split); (2) seeds your verbatim script straight into the issue's **comic-script stage** (not the prose stage), so the pipeline renders pages from *your* script instead of regenerating its own; and (3) the comic-page parser now understands the common screenplay convention — bare `PAGE 1` / `PANEL 1` headers with `CAPTION` / `SFX` / speaker labels on their own lines — so those pages parse into panels for image generation with your panel descriptions, captions, dialogue, and SFX intact.
+- **A failed issue split no longer throws away the canon + arc work.** Canon and arc are the expensive extraction passes; if only the final issue-split step fails or times out, the Importer keeps the canon + arc preview and shows a "Retry issue split" button in the Review panel that re-runs **only** the split — so you don't burn the two heavy passes again.
- **Pick any AI provider for the voice assistant.** The voice Chief-of-Staff's language model was hard-wired to LM Studio. Settings → Voice now has an "LLM provider" picker listing every API provider you've configured (LM Studio, Ollama, NVIDIA, or any OpenAI-compatible endpoint) plus a model dropdown with a refresh button that re-queries the provider's available models. Local-only setups are unchanged out of the box — LM Studio stays the default and the `LM_STUDIO_URL` override still applies — but you can now point voice at a hosted model. The voice service-health badge probes whichever provider you select.
- **Pipeline Series pages are now cover-forward editorial workspaces.** The series detail view replaces the long all-volumes scroll with a compact volume selector, cover cards for issues, colorful theme tags, and an editorial roadmap panel for visually debugging plot, character, and future reader-emotion arcs. Missing or in-flight volume and issue covers now show placeholders instead of leaving dense text lists as the primary navigation.
- **Consistent inline badge styling.** The peer relationship and connection-scheme labels on the Instances page and the length-target cards in the Writers Room Guide now render through one shared badge component, so their look stays consistent as more badges are added.
## Fixed
+- **Importer analyze no longer times out on long sources.** Each analyze pass feeds the entire source to a heavy-tier model in one shot, which routinely takes longer than the AI runner's 5-minute default — so the issue-split pass would falsely time out and trigger an expensive from-scratch fallback re-run on another provider. The Importer's passes now get a 20-minute timeout, matched to the work they actually do.
- **Merging duplicate universes now shows what's being combined.** When you fold two duplicate universes (or series) together, the merge dialog only ever asked you to resolve scalar conflicts like the starter prompt — the list-shaped fields (style prompt and negative prompt chips, categories, characters/places/objects, composite sheets, seasons) were silently unioned with no indication it happened. The dialog now lists each list field the folded copy contributes to, with a running "N total · +N folded in" count, so the no-data-loss combine is visible instead of feeling like those fields were ignored.
- **[peer-sync-per-category-version-gate] Machines on different PortOS versions keep syncing everything except the one changed data type.** When one federated machine updates to a version that changes how a single kind of data is stored (universes, comics, or media collections), the others used to refuse the *entire* sync until they caught up — silently stalling all data between them. Now only transfers of the changed data type wait for the lagging machine to update; every other kind keeps flowing.
- **Voice timers survive a restart and no longer double-fire.** A timer or reminder you set by voice ("remind me in 30 minutes to call mom") is now saved to disk, so it still goes off if PortOS restarts before it's due — any that came due while it was down fire as soon as it's back. A single request can no longer arm two timers, so you won't get the same reminder twice.
diff --git a/PLAN.md b/PLAN.md
index bb8aacf383..e07495d558 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -170,6 +170,16 @@ Surfaced by the multi-reviewer release gate for v2.10.0. The CRITICAL/correctnes
Surfaced by the code-review pass on the Importer AI Provider/Model picker (`client/src/pages/Importer.jsx`). Correctness was clean; these are reuse/altitude cleanups deferred to keep the PR focused.
- [ ] [shared-optional-provider-picker] **Add an optional/"Default" mode to the shared provider/model picker and migrate the inline copies.** Three pages now hand-roll the same inline two-`<select>` "Default sentinel + provider + model" picker because the shared `client/src/components/ProviderModelSelector.jsx` + `client/src/hooks/useProviderModels.js` force a selection (no empty option; `useProviderModels` auto-selects the first provider via `hasSetInitialRef`). UniverseBuilder.jsx (~2968-2992) and now Importer.jsx (~437-470, plus its `getProviders`+enabled-filter effect ~93-106 and `llmModels` memo) duplicate the logic in `FeatureProviderPicker.jsx`/`useProviderModels`. Add an `emptyOption={{ value:'', label }}` (or `allowDefault`) prop to `ProviderModelSelector` and an `allowDefault`/`includeEmpty` flag to `useProviderModels` that skips the auto-select, then refactor both Importer and UniverseBuilder to consume them — removing ~30 lines of JSX from each and the six prop-drilled values into `IntakeForm`. Note the importer's default label must stay accurate to its *per-stage* resolution (`stage.provider` → active), so a single "active provider (name)" label like UniverseBuilder's would be misleading for the importer — keep a generic "Default" label unless the picker is taught the resolved-per-stage provider. Cleanup only; no behavior change. Surfaced 2026-05-26.
+- [ ] [importer-screenplay-teleplay-seed] **Mirror the comic-script verbatim-seed for screenplay imports → `stages.teleplay`.** The comic-script import now seeds the verbatim script into `stages.comicScript` (ready) instead of `stages.prose`, so the pipeline doesn't regenerate it (`commitImport` in `server/services/importer.js`, via the `CONTENT_TYPE_SEED_STAGE` table). Adding screenplay is now a one-row change: `'screenplay': 'teleplay'`. Also extend the auto-run script-first guard in `autoRunner.js` (currently checks `comicScript || teleplay` already, so likely covered) and check whether any downstream teleplay consumer parses a specific format (the comic path needed `parseComicScript` taught the bare `PAGE/PANEL` form — teleplay may or may not have an analogous parser). Deferred to keep the 2026-05-26 PR scoped to comics, which is what the user was importing. Surfaced 2026-05-26.
+
+### Importer backport/merge code-review follow-ups (2026-05-26)
+
+Lower-severity findings from the xhigh code-review of the importer feature; the correctness/data-loss bugs (greedy speaker-cue, dropped panels, prose-cap dead-end, header false-positives, auto-run spurious prose) were fixed inline. These were deferred:
+
+- [ ] [importer-progress-hook] **Extract a `useImporterProgress` hook.** The `importer:progress` socket subscription is hand-rolled in `client/src/pages/Importer.jsx` (~60-86) — raw `socket.on/off` + `activeRunIdRef` runId-filter in a page `useEffect`, duplicating the lifecycle already factored into `useImageGenProgress` / `useMediaJobProgress` / `usePipelineAutoRunProgress`. Extract to `client/src/hooks/useImporterProgress.js`, register in the hooks `index.js` barrel + README (module-org rule: socket clients live in hooks, not pages). Also fold the `ImporterProgress` checklist's status→icon ternary into a shared lookup (it's the 3rd inline copy; `CreateApp.jsx` has another that already drifted Loader vs Loader2). Cleanup only. Surfaced 2026-05-26.
+- [ ] [importer-progress-reconnect] **Live checklist stalls if the socket misses the `start` frame.** The `importer:progress` handler gates every `stage` frame on a runId set only by a `start` frame; a mid-analyze socket reconnect (or out-of-order delivery) means stage frames are dropped and the checklist stays on "Starting…" until analyze resolves. Degrades gracefully (falls back to the old spinner), so low priority. Fix: if a `stage` frame arrives while `analyzing` with no active runId, adopt it and lazily seed the stage list, OR have the server resend `start` on (re)subscribe. Surfaced 2026-05-26.
+- [ ] [importer-retry-arcsummary-empty] **Retry's `arcSummary` uses `||` truthiness, dropping an intentionally-cleared summary.** `runRetryIssues` in `Importer.jsx` builds `arcDraft?.summary || arcDraft?.logline || ''`, so clearing the summary in Review falls back to the logline rather than sending none — violates the absent-vs-intentionally-empty rule the rest of the feature follows. Non-fatal (arcSummary is cosmetic prompt context). Fix: treat `summary === ''` as an intentional clear (`summary == null ? logline : summary`). Surfaced 2026-05-26.
+- [ ] [importer-orphan-shell-gc] **An abandoned analyze leaves an empty universe/series shell on disk.** `analyzeImport` persists universe+series after canon+arc succeed (the chosen "keep review flow + retry" tradeoff), so if the user abandons after an issue-split failure (or just never commits) on a brand-new universe/series, empty shells linger in `data/`. By-design, but a periodic GC of zero-issue, zero-canon shells older than N days (or marking analyze-created shells `ephemeral` until commit promotes them) would keep `data/` clean. Surfaced 2026-05-26.
## Future Ideas
diff --git a/client/src/pages/Importer.jsx b/client/src/pages/Importer.jsx
index 52e628f1c5..7f7bab9303 100644
--- a/client/src/pages/Importer.jsx
+++ b/client/src/pages/Importer.jsx
@@ -1,7 +1,8 @@
import { memo, useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
-import { FileInput, Loader2, ArrowLeft, CheckCircle2, AlertTriangle, ChevronDown, ChevronRight, Wand2 } from 'lucide-react';
+import { FileInput, Loader2, ArrowLeft, CheckCircle2, AlertTriangle, ChevronDown, ChevronRight, Wand2, Circle } from 'lucide-react';
import toast from '../components/ui/Toast';
+import socket from '../services/socket';
import { useAsyncAction } from '../hooks/useAsyncAction';
import { STORY_SHAPES } from '../components/pipeline/StoryShapes';
import EntryCard from '../components/universe/EntryCard';
@@ -12,6 +13,7 @@ import {
analyzeImport,
classifyImport,
commitImport,
+ retryImporterIssues,
getImporterConfig,
IMPORTER_CONTENT_TYPES,
IMPORTER_SOURCE_CHAR_LIMIT_FALLBACK,
@@ -55,6 +57,34 @@ export default function Importer() {
const [intake, setIntake] = useState(emptyIntake);
const [preview, setPreview] = useState(null);
+ // Live analyze-phase stage progress, driven by `importer:progress` socket
+ // frames. `null` = no run started yet (or reset before a fresh Analyze).
+ // The server broadcasts to all clients (single-user trust model), so each
+ // frame carries a `runId` and we ignore stage frames that don't match the
+ // run a `start` frame opened — guards against a straggler from a prior run.
+ const [analyzeStages, setAnalyzeStages] = useState(null);
+ const activeRunIdRef = useRef(null);
+ useEffect(() => {
+ const onProgress = (ev) => {
+ if (!ev || typeof ev !== 'object') return;
+ if (ev.type === 'start') {
+ activeRunIdRef.current = ev.runId;
+ setAnalyzeStages(
+ (Array.isArray(ev.stages) ? ev.stages : []).map((s) => ({ ...s, status: 'pending' })),
+ );
+ return;
+ }
+ if (ev.type === 'stage') {
+ if (ev.runId !== activeRunIdRef.current) return;
+ setAnalyzeStages((prev) =>
+ Array.isArray(prev) ? prev.map((s) => (s.id === ev.id ? { ...s, status: ev.status } : s)) : prev,
+ );
+ }
+ };
+ socket.on('importer:progress', onProgress);
+ return () => socket.off('importer:progress', onProgress);
+ }, []);
+
// Server is the source of truth for the enums — a prior client-side copy
// (`IMPORTER_ARC_ROLES_FALLBACK`) silently drifted, so we wait on the GET
// rather than shadow it. `arcShapeIds: null` means "config not loaded
@@ -117,6 +147,10 @@ export default function Importer() {
// Destructive opt-in for existing series — wipes issues + overwrites arc.
const [replaceMode, setReplaceMode] = useState(false);
const [classifyHint, setClassifyHint] = useState(null);
+ // Set when analyze succeeded on canon+arc but the issue split failed — the
+ // Review panel shows a retry affordance instead of throwing the run away.
+ const [issueSplitFailed, setIssueSplitFailed] = useState(false);
+ const [issueSplitError, setIssueSplitError] = useState(null);
// Stale hint after the source changes would mislead the user.
useEffect(() => { setClassifyHint(null); }, [intake.source]);
@@ -144,6 +178,10 @@ export default function Importer() {
// A late-resolving config GET would clobber the server-fresh values in
// `result.limits` / `arcRoles` / `arcShapeIds` below.
abortConfigRef.current?.abort();
+ // Clear any prior run's checklist; the server's `start` frame repopulates
+ // it once the first AI pass begins (a generic spinner shows until then).
+ activeRunIdRef.current = null;
+ setAnalyzeStages(null);
const payload = {
universeName: intake.universeName.trim(),
seriesName: intake.seriesName.trim(),
@@ -152,7 +190,9 @@ export default function Importer() {
providerOverride: llmProvider,
modelOverride: llmModel,
};
- const tic = intake.targetIssueCount === '' ? null : Number(intake.targetIssueCount);
+ // Round to an integer — the server schema is z.number().int(), so a
+ // pasted/typed decimal like 2.5 would otherwise 400 with a confusing error.
+ const tic = intake.targetIssueCount === '' ? null : Math.round(Number(intake.targetIssueCount));
if (Number.isFinite(tic) && tic > 0) payload.targetIssueCount = tic;
const result = await analyzeImport(payload, { silent: true });
if (!result) return null;
@@ -171,6 +211,8 @@ export default function Importer() {
setArcDraft(pickArcFields(result.arcPreview));
setSeasonsDraft((result.seasonsPreview || []).map((s) => ({ ...s })));
setIssuesDraft((result.issueProposals || []).map((i) => ({ ...i })));
+ setIssueSplitFailed(Boolean(result.issueSplitFailed));
+ setIssueSplitError(result.issueSplitError || null);
setArcAlreadyPersisted(false);
setReplaceMode(false);
setConfig((c) => ({
@@ -191,6 +233,10 @@ export default function Importer() {
universeId: preview.universe.id,
seriesId: preview.series.id,
issues: issuesDraft,
+ // Routes the verbatim excerpt to the right stage server-side — a
+ // comic-script import seeds stages.comicScript (ready) so the pipeline
+ // renders the user's script as-is instead of regenerating it.
+ contentType: intake.contentType,
};
const payload = arcAlreadyPersisted
? { ...base, canonSelections: { characters: [], places: [], objects: [] }, arc: null, seasons: [] }
@@ -234,6 +280,38 @@ export default function Importer() {
return result;
}, { errorMessage: 'Failed to commit import' });
+ // Recovery for a failed issue split — re-runs ONLY the split against the
+ // same source + the arc the user already has in the panel. Canon + arc are
+ // untouched; on success we populate the issues and clear the failed banner.
+ const [runRetryIssues, retryingIssues] = useAsyncAction(async () => {
+ if (!preview) return null;
+ const payload = {
+ contentType: intake.contentType,
+ source: intake.source,
+ seriesName: preview.series?.name || intake.seriesName,
+ providerOverride: llmProvider,
+ modelOverride: llmModel,
+ };
+ const arcSummary = arcDraft?.summary || arcDraft?.logline || '';
+ if (arcSummary.trim()) payload.arcSummary = arcSummary;
+ // Round to an integer — the server schema is z.number().int(), so a
+ // pasted/typed decimal like 2.5 would otherwise 400 with a confusing error.
+ const tic = intake.targetIssueCount === '' ? null : Math.round(Number(intake.targetIssueCount));
+ if (Number.isFinite(tic) && tic > 0) payload.targetIssueCount = tic;
+ const result = await retryImporterIssues(payload, { silent: true });
+ if (!result) return null;
+ const issues = Array.isArray(result.issueProposals) ? result.issueProposals : [];
+ setIssuesDraft(issues.map((i) => ({ ...i })));
+ if (issues.length === 0) {
+ toast.warning('Retry produced no issues — adjust the target issue count or the source and try again.');
+ } else {
+ setIssueSplitFailed(false);
+ setIssueSplitError(null);
+ toast.success(`Issue split succeeded — ${issues.length} issue${issues.length === 1 ? '' : 's'} proposed.`);
+ }
+ return result;
+ }, { errorMessage: 'Failed to retry issue split' });
+
return (
<div className="space-y-6">
<header className="flex items-start gap-3">
@@ -254,6 +332,7 @@ export default function Importer() {
setIntake={setIntake}
sourceCharLimit={config.sourceCharLimit}
analyzing={analyzing}
+ analyzeStages={analyzeStages}
onAnalyze={runAnalyze}
classifying={classifying}
onClassify={runClassify}
@@ -286,6 +365,10 @@ export default function Importer() {
committing={committing}
onCommit={runCommit}
onBack={() => setPhase('intake')}
+ issueSplitFailed={issueSplitFailed}
+ issueSplitError={issueSplitError}
+ onRetryIssues={runRetryIssues}
+ retryingIssues={retryingIssues}
/>
)}
</div>
@@ -293,7 +376,7 @@ export default function Importer() {
}
function IntakeForm({
- intake, setIntake, sourceCharLimit, analyzing, onAnalyze, classifying, onClassify, classifyHint,
+ intake, setIntake, sourceCharLimit, analyzing, analyzeStages, onAnalyze, classifying, onClassify, classifyHint,
providers, llmProvider, llmModel, llmModels, onProviderChange, onModelChange,
}) {
const sourceLen = intake.source.length;
@@ -469,6 +552,8 @@ function IntakeForm({
</div>
</div>
+ {analyzing && <ImporterProgress stages={analyzeStages} />}
+
<div className="flex items-center justify-end gap-2 pt-2">
<button
type="button"
@@ -484,6 +569,42 @@ function IntakeForm({
);
}
+// Live checklist of the analyze phase's AI passes. `stages` is null until the
+// server's first `importer:progress` frame arrives — show a generic spinner in
+// that window so the panel never looks empty between click and first frame.
+function ImporterProgress({ stages }) {
+ return (
+ <div className="bg-port-bg border border-port-border rounded-lg p-4 space-y-2">
+ <p className="text-sm font-medium flex items-center gap-2">
+ <Loader2 className="w-4 h-4 animate-spin text-port-accent" />
+ Analyzing source — this runs several AI passes and can take a minute or two.
+ </p>
+ {Array.isArray(stages) && stages.length > 0 ? (
+ <ul className="space-y-1.5 mt-2">
+ {stages.map((s) => (
+ <li key={s.id} className="flex items-center gap-2 text-sm">
+ {s.status === 'done' ? (
+ <CheckCircle2 className="w-4 h-4 text-port-success flex-shrink-0" />
+ ) : s.status === 'error' ? (
+ <AlertTriangle className="w-4 h-4 text-port-warning flex-shrink-0" />
+ ) : s.status === 'running' ? (
+ <Loader2 className="w-4 h-4 text-port-accent animate-spin flex-shrink-0" />
+ ) : (
+ <Circle className="w-4 h-4 text-port-text-muted/40 flex-shrink-0" />
+ )}
+ <span className={s.status === 'running' ? 'text-port-text' : 'text-port-text-muted'}>
+ {s.label}
+ </span>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="text-xs text-port-text-muted">Starting…</p>
+ )}
+ </div>
+ );
+}
+
function ReviewPanel({
preview, canonSelections,
selectedCanon, setSelectedCanon,
@@ -492,6 +613,7 @@ function ReviewPanel({
arcRoles, arcShapeIds,
replaceMode, setReplaceMode,
committing, onCommit, onBack,
+ issueSplitFailed, issueSplitError, onRetryIssues, retryingIssues,
}) {
const toggleSelected = (kind, idx) => {
setSelectedCanon((sc) => {
@@ -563,6 +685,29 @@ function ReviewPanel({
<ArcReviewSection arc={arcDraft} setArc={setArcDraft} seasons={seasonsDraft} setSeasons={setSeasonsDraft} arcShapeIds={arcShapeIds} />
+ {issueSplitFailed && (
+ <div className="bg-port-warning/10 border border-port-warning/40 rounded-lg p-4 flex items-start gap-3">
+ <AlertTriangle className="w-5 h-5 text-port-warning mt-0.5 flex-shrink-0" />
+ <div className="flex-1">
+ <div className="text-sm font-medium text-port-warning">Issue split didn&apos;t finish</div>
+ <p className="text-xs text-port-text-muted mt-1">
+ Canon and arc extracted successfully and are ready to review above. Only the issue
+ split failed{issueSplitError ? <> — <span className="font-mono">{issueSplitError}</span></> : null}.
+ Retry it below — this re-runs <strong>only</strong> the split, so the canon and arc work above is kept.
+ </p>
+ <button
+ type="button"
+ onClick={onRetryIssues}
+ disabled={retryingIssues}
+ className="mt-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white px-3 py-1.5 rounded text-xs font-medium flex items-center gap-1.5"
+ >
+ {retryingIssues ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <FileInput className="w-3.5 h-3.5" />}
+ {retryingIssues ? 'Retrying…' : 'Retry issue split'}
+ </button>
+ </div>
+ </div>
+ )}
+
<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">
diff --git a/client/src/services/apiImporter.js b/client/src/services/apiImporter.js
index 85a69ddc34..eb54eff4f4 100644
--- a/client/src/services/apiImporter.js
+++ b/client/src/services/apiImporter.js
@@ -39,3 +39,12 @@ export const commitImport = (payload, options = {}) => request('/importer/commit
body: JSON.stringify(payload),
...options,
});
+
+// Recovery path when analyze returned `issueSplitFailed` — re-runs ONLY the
+// issue split (canon + arc are preserved in the Review panel). Returns
+// `{ issueProposals, method }`.
+export const retryImporterIssues = (payload, options = {}) => request('/importer/retry-issues', {
+ method: 'POST',
+ body: JSON.stringify(payload),
+ ...options,
+});
diff --git a/server/lib/comicScriptParser.js b/server/lib/comicScriptParser.js
index 5986062045..82bc1588cc 100644
--- a/server/lib/comicScriptParser.js
+++ b/server/lib/comicScriptParser.js
@@ -47,6 +47,137 @@ const FIELD_RE = /^(?:\*\*)?(Description|Caption(?:\s+\d+)?|Dialogue|SFX)\s*:(?:
const NONE_RE = /^\(\s*none\s*\)$/i;
const isNoneValue = (s) => !s || NONE_RE.test(s.trim());
+// --- Bare-format normalization ---------------------------------------------
+//
+// Imported comic scripts (Create → Importer) commonly use the bare
+// screenplay convention — uppercase `PAGE 1` / `PANEL 1` headers with the
+// label on its own line and the content on the following line(s):
+//
+// PAGE 1
+// <page-level art direction>
+// PANEL 1
+// <panel description>
+// CAPTION
+// <caption text>
+// GIANT
+// <spoken line>
+// SFX
+// Thud!
+//
+// The pipeline's own comic-script stage emits the field-labeled Markdown
+// form (`## Page N`, `**Description:**`, `**Caption:**`, `Dialogue:`). Rather
+// than rewrite the user's stored script, we detect the bare form and convert
+// it to the canonical shape IN MEMORY before the main parse, so the verbatim
+// text seeded into `stages.comicScript.output` is preserved while still
+// rendering into pages/panels. Markers are matched case-sensitively (real
+// headers are uppercase) so prose like "Page after page…" isn't mistaken
+// for a header.
+const BARE_PAGE_LINE = /^\s*PAGES?\s+\S+/; // PAGE 1 / PAGES 2-3
+const BARE_PANEL_LINE = /^\s*PANELS?\s+\S+/; // PANEL 1
+const BARE_CAPTION_LINE = /^\s*CAPTION\b/; // CAPTION / CAPTION 2:
+const BARE_SFX_LINE = /^\s*SFX\b/; // SFX
+// A standalone dialogue speaker cue: a short, NAME-like all-caps token,
+// optionally with a parenthetical (`GIANT`, `KESSA (WHISPERED)`). It must NOT
+// contain sentence punctuation (`. , ! ? :`) so a terse all-caps panel
+// description ("THE CITY BURNS.") or a slugline ("INT. VAULT - NIGHT") is not
+// misread as a speaker. Even so, the FIRST content line after a PANEL/CAPTION/
+// SFX label is never treated as a speaker (see normalizeBareComicScript), which
+// protects all-caps descriptions and all-caps SFX content ("KRAKOOM").
+const BARE_SPEAKER_LINE = /^[A-Z][A-Z0-9 '’&-]{0,28}(?:\s*\([^)]*\))?$/;
+// Canonical page header — its presence means the script is already in the
+// pipeline's Markdown form, so we leave it untouched.
+const CANONICAL_PAGE_RE = /^##\s+Page\s/im;
+
+// Detect the bare form: no canonical `## Page` header, but at least one bare
+// uppercase `PAGE N` line.
+function isBareComicScript(script) {
+ if (CANONICAL_PAGE_RE.test(script)) return false;
+ return script.split(/\r?\n/).some((l) => BARE_PAGE_LINE.test(l));
+}
+
+// Convert the bare form to the canonical Markdown the main parser consumes.
+// Pages and panels are renumbered sequentially (the numbers are cosmetic —
+// the parser keys off the headers, not the values).
+function normalizeBareComicScript(script) {
+ const out = [];
+ let pageNum = 0;
+ let panelNum = 0;
+ let inPanel = false;
+ // Which field the current content lines belong to: 'description' | 'caption'
+ // | 'sfx' | null (page-level, or right after a dialogue line).
+ let field = null;
+ // True for the line immediately after a label (PANEL→description, CAPTION,
+ // SFX). That line is always the field's content, NEVER a speaker cue — this
+ // is what keeps a terse all-caps description or an all-caps SFX ("KRAKOOM")
+ // from being misread as dialogue.
+ let awaitingFirst = false;
+ let pendingSpeaker = null;
+
+ // A speaker cue whose spoken line never arrived (next line was a marker or
+ // EOF) is emitted back as plain text rather than dropped, so no input line
+ // is lost.
+ const flushDanglingSpeaker = () => {
+ if (pendingSpeaker) {
+ out.push(pendingSpeaker);
+ pendingSpeaker = null;
+ }
+ };
+
+ for (const raw of script.split(/\r?\n/)) {
+ const t = raw.trim();
+
+ if (BARE_PAGE_LINE.test(t)) {
+ flushDanglingSpeaker();
+ pageNum += 1; panelNum = 0; inPanel = false; field = null; awaitingFirst = false;
+ out.push(`## Page ${pageNum}`);
+ continue;
+ }
+ if (BARE_PANEL_LINE.test(t)) {
+ flushDanglingSpeaker();
+ panelNum += 1; inPanel = true; field = 'description'; awaitingFirst = true;
+ out.push(`Panel ${panelNum}`);
+ continue;
+ }
+ if (inPanel && BARE_CAPTION_LINE.test(t)) {
+ flushDanglingSpeaker();
+ out.push('Caption:'); field = 'caption'; awaitingFirst = true;
+ continue;
+ }
+ if (inPanel && BARE_SFX_LINE.test(t)) {
+ flushDanglingSpeaker();
+ out.push('SFX:'); field = 'sfx'; awaitingFirst = true;
+ continue;
+ }
+ // The spoken line for a pending speaker (markers were handled above and
+ // already flushed the speaker, so reaching here means a real dialogue line).
+ if (pendingSpeaker && t) {
+ out.push('Dialogue:');
+ out.push(`${pendingSpeaker}: ${t}`);
+ pendingSpeaker = null;
+ field = null; // dialogue closes the active field
+ continue;
+ }
+ // Speaker cue — only when NOT the forced first content line after a label.
+ if (inPanel && t && !awaitingFirst && BARE_SPEAKER_LINE.test(t)) {
+ pendingSpeaker = t;
+ continue;
+ }
+ // First content line after a PANEL opens the Description field.
+ if (awaitingFirst && t && field === 'description') {
+ out.push(`Description: ${t}`);
+ awaitingFirst = false;
+ continue;
+ }
+ // First content line after CAPTION/SFX, plus every continuation line and
+ // page-level/blank line, passes through — the main parser appends it to
+ // the open field.
+ if (t) awaitingFirst = false;
+ out.push(raw);
+ }
+ flushDanglingSpeaker();
+ return out.join('\n');
+}
+
const PANEL_LIMITS = Object.freeze({
PAGES_MAX: 200,
PANELS_PER_PAGE_MAX: 24,
@@ -141,7 +272,13 @@ export function parseComicScript(script) {
return { coverConcept: '', backCoverConcept: '', pages: [] };
}
- const lines = script.split(/\r?\n/);
+ // Imported scripts often arrive in the bare `PAGE`/`PANEL`/`CAPTION` form
+ // (see normalizeBareComicScript). Convert to canonical Markdown first so
+ // the verbatim stored script still parses into pages/panels. Canonical
+ // scripts are detected and left untouched, so existing behavior is unchanged.
+ const bare = isBareComicScript(script);
+ const normalized = bare ? normalizeBareComicScript(script) : script;
+ const lines = normalized.split(/\r?\n/);
const pages = [];
let currentPage = null;
let currentRawLines = null;
@@ -158,7 +295,16 @@ export function parseComicScript(script) {
const flushPanel = () => {
if (!inAnyPanel || !currentPage || !currentPanelLines) return;
const panel = parsePanelBody(currentPanelLines);
- if (panel.description) {
+ // Canonical (LLM-authored) scripts: keep only description-bearing panels —
+ // a stray `**Caption:**` with no description is generator noise (a floating
+ // header) and is intentionally dropped. Imported bare scripts: keep a panel
+ // with ANY content, because a caption-only / dialogue-only / SFX-only panel
+ // (e.g. a narration-over-black splash) is a legitimate authored beat and
+ // dropping it would lose the user's verbatim text.
+ const hasContent = bare
+ ? (panel.description || panel.caption || panel.sfx || panel.dialogue.length > 0)
+ : Boolean(panel.description);
+ if (hasContent) {
currentPage.panels.push({ ...panel, imageJobId: null });
}
currentPanelLines = null;
diff --git a/server/lib/comicScriptParser.test.js b/server/lib/comicScriptParser.test.js
index 38ed328fe9..7ee4c46fbd 100644
--- a/server/lib/comicScriptParser.test.js
+++ b/server/lib/comicScriptParser.test.js
@@ -325,3 +325,102 @@ Description: Tight on Kessa's hands clutching the railing.
expect(pages[0].rawText.length).toBeLessThanOrEqual(40_000);
});
});
+
+// Imported comic scripts use the bare screenplay convention (uppercase
+// `PAGE`/`PANEL` headers, label-on-its-own-line CAPTION/SFX/dialogue). The
+// parser normalizes that to the canonical form in memory so the verbatim
+// imported script still renders into pages/panels.
+describe('parseComicScript — bare imported format', () => {
+ const BARE = `PAGE 1
+A small village sits against a mountain. This page is the dream of Giant.
+PANEL 1
+Giant descends from the castle on a Summer day, full of smiles.
+CAPTION
+I am sorry to say, this isn't real.
+PANEL 2
+Birds sing around Giant as he enters the town.
+CAPTION
+It's not even realistic.
+PAGE 2
+PANEL 1
+He spreads his arms wide and gold coins swarm into the streets.
+PANEL 2
+Close up on Giant with a wide grin.
+GIANT
+The curse is…
+CAPTION
+Woah. Slow down big fella...
+PANEL 3
+Giant is heaved into a black panel.
+SFX
+Thud!`;
+
+ it('splits bare PAGE/PANEL headers into pages and panels', () => {
+ const { pages } = parseComicScript(BARE);
+ expect(pages).toHaveLength(2);
+ expect(pages[0].panels).toHaveLength(2);
+ expect(pages[1].panels).toHaveLength(3);
+ });
+
+ it('reads the first block after PANEL as the description, verbatim', () => {
+ const { pages } = parseComicScript(BARE);
+ expect(pages[0].panels[0].description).toMatch(/Giant descends from the castle/);
+ expect(pages[0].panels[1].description).toMatch(/Birds sing around Giant/);
+ });
+
+ it('reads CAPTION / SFX label-lines and their following text', () => {
+ const { pages } = parseComicScript(BARE);
+ expect(pages[0].panels[0].caption).toBe("I am sorry to say, this isn't real.");
+ expect(pages[1].panels[2].sfx).toBe('Thud!');
+ });
+
+ it('reads a SPEAKER cue line + the next line as dialogue', () => {
+ const { pages } = parseComicScript(BARE);
+ expect(pages[1].panels[1].dialogue).toEqual([{ character: 'GIANT', line: 'The curse is…' }]);
+ // The CAPTION after the dialogue still attaches to the same panel.
+ expect(pages[1].panels[1].caption).toBe('Woah. Slow down big fella...');
+ });
+
+ it('leaves canonical Markdown scripts untouched (no false bare-detection)', () => {
+ const { pages } = parseComicScript(SAMPLE);
+ // Same result the canonical-format tests assert — normalization skipped.
+ expect(pages).toHaveLength(2);
+ expect(pages[0].panels[0].description).toMatch(/Wide establishing shot/);
+ expect(pages[1].panels[0].caption).toMatch(/inside of a dead god/);
+ });
+
+ it('does NOT misread a terse all-caps panel description as a speaker cue', () => {
+ const { pages } = parseComicScript('PAGE 1\nPANEL 1\nTHE CITY BURNS AT NIGHT\nGIANT\nStop right there!');
+ expect(pages[0].panels[0].description).toBe('THE CITY BURNS AT NIGHT');
+ expect(pages[0].panels[0].dialogue).toEqual([{ character: 'GIANT', line: 'Stop right there!' }]);
+ });
+
+ it('keeps all-caps SFX content (KRAKOOM) as SFX, not a speaker', () => {
+ const { pages } = parseComicScript('PAGE 1\nPANEL 1\nA wide shot of the blast.\nSFX\nKRAKOOM\nGIANT\nNo!');
+ expect(pages[0].panels[0].sfx).toBe('KRAKOOM');
+ expect(pages[0].panels[0].dialogue).toEqual([{ character: 'GIANT', line: 'No!' }]);
+ });
+
+ it('does not treat a slugline-style description (has a period) as a speaker', () => {
+ const { pages } = parseComicScript('PAGE 1\nPANEL 1\nINT. VAULT - NIGHT. Dust everywhere.\nCAPTION\nIt was quiet.');
+ expect(pages[0].panels[0].description).toMatch(/INT\. VAULT - NIGHT/);
+ expect(pages[0].panels[0].caption).toBe('It was quiet.');
+ expect(pages[0].panels[0].dialogue).toEqual([]);
+ });
+
+ it('keeps a caption-only bare panel (no description) instead of dropping it', () => {
+ const { pages } = parseComicScript('PAGE 1\nPANEL 1\nCAPTION\nIn the beginning, there was nothing.');
+ expect(pages).toHaveLength(1);
+ expect(pages[0].panels).toHaveLength(1);
+ expect(pages[0].panels[0].caption).toBe('In the beginning, there was nothing.');
+ });
+
+ it('preserves a dangling speaker cue (no spoken line before the next marker) as text, not dropped', () => {
+ const { pages } = parseComicScript('PAGE 1\nPANEL 1\nA face.\nGIANT\nPANEL 2\nAnother shot.');
+ // GIANT had no spoken line before PANEL 2 — it must survive in the panel
+ // text rather than vanish or fabricate dialogue.
+ expect(pages[0].panels[0].description).toContain('GIANT');
+ expect(pages[0].panels[0].dialogue).toEqual([]);
+ expect(pages[0].panels).toHaveLength(2);
+ });
+});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index d378a0b512..31a309d995 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1617,6 +1617,12 @@ export const IMPORTER_CONTENT_TYPES = Object.freeze([
// here mirrors writersRoomDraftSaveSchema.
const importerSourceField = z.string().min(1).max(5_000_000);
+// Per-issue verbatim-excerpt ceiling (seeds stages.prose / stages.comicScript).
+// Far below importerSourceField's 5MB so a single bundled comic issue can't
+// blow past it silently — analyze validates against this so the failure
+// surfaces at analyze, not as a commit-time 400.
+export const IMPORTER_PROSE_EXCERPT_MAX = 500_000;
+
// Classify endpoint only sees the source — no universe/series context. The
// LLM only consumes the head, so the schema is intentionally minimal.
export const importerClassifySchema = z.object({
@@ -1643,6 +1649,21 @@ export const importerAnalyzeSchema = z.object({
targetIssueCount: z.number().int().min(1).max(50).optional(),
}).strict();
+// Retry-issues endpoint — re-runs ONLY the issue split after a failed analyze
+// (canon + arc are preserved client-side). No universe/series names needed;
+// `arcSummary` (optional) lets the LLM align issue boundaries to the arc the
+// user already has in the Review panel, and `seriesName` is purely cosmetic
+// prompt context.
+export const importerRetryIssuesSchema = z.object({
+ contentType: z.enum(IMPORTER_CONTENT_TYPES),
+ source: importerSourceField,
+ seriesName: z.string().trim().max(200).optional(),
+ arcSummary: z.string().max(8000).optional(),
+ providerOverride: z.preprocess(emptyToUndefined, z.string().trim().max(120).optional()),
+ modelOverride: z.preprocess(emptyToUndefined, z.string().trim().max(200).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.
@@ -1697,8 +1718,10 @@ const importerIssueEntry = z.object({
// 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(
+ // `ready` misleadingly. Exported so the mechanical comic splitter can
+ // validate against the SAME ceiling at analyze time (a verbatim split could
+ // otherwise produce an excerpt commit would reject — a confusing dead-end).
+ proseExcerpt: z.string().min(1).max(IMPORTER_PROSE_EXCERPT_MAX).refine(
(s) => s.trim().length > 0,
{ message: 'proseExcerpt must contain non-whitespace content' },
).optional(),
@@ -1715,6 +1738,12 @@ export const importerCommitSchema = z.object({
arc: importerArcShape.nullable().optional(),
seasons: z.array(importerSeasonEntry).max(50).default([]),
issues: z.array(importerIssueEntry).min(1).max(50),
+ // Drives which stage each issue's verbatim excerpt seeds: a `comic-script`
+ // import is already script-form, so its excerpt seeds `stages.comicScript`
+ // (ready) and the pipeline never regenerates — every other type seeds
+ // `stages.prose`. Optional + defaulting to prose-seed keeps older clients
+ // (which don't send it) on the prior behavior.
+ contentType: z.enum(IMPORTER_CONTENT_TYPES).optional(),
// Replace-mode flag — when true, every existing issue on the series is
// deleted before the incoming `issues` are created, and `series.arc` +
// `series.seasons[]` are written verbatim (not merged). Canon is still
diff --git a/server/routes/importer.js b/server/routes/importer.js
index b699c4e982..8897b48f85 100644
--- a/server/routes/importer.js
+++ b/server/routes/importer.js
@@ -5,11 +5,13 @@ import {
importerAnalyzeSchema,
importerCommitSchema,
importerClassifySchema,
+ importerRetryIssuesSchema,
} from '../lib/validation.js';
import {
analyzeImport,
classifyImportContent,
commitImport,
+ retryIssueSplit,
ERR_VALIDATION,
ERR_LOCKED,
ERR_PARTIAL_COMMIT_ISSUES,
@@ -79,6 +81,15 @@ router.post('/analyze', asyncHandler(async (req, res) => {
res.json(result);
}));
+// Recovery path for a failed issue split — re-runs ONLY the split (canon +
+// arc are preserved client-side from the prior analyze). Cheap relative to a
+// full re-analyze; comic scripts resolve mechanically with no LLM call.
+router.post('/retry-issues', asyncHandler(async (req, res) => {
+ const input = validateRequest(importerRetryIssuesSchema, req.body || {});
+ const result = await retryIssueSplit(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); });
diff --git a/server/routes/importer.test.js b/server/routes/importer.test.js
index 2bdd8d37ea..81a5aa284e 100644
--- a/server/routes/importer.test.js
+++ b/server/routes/importer.test.js
@@ -14,6 +14,7 @@ vi.mock('../services/importer.js', async () => {
analyzeImport: vi.fn(), // mocked behavior
classifyImportContent: vi.fn(), // mocked behavior
commitImport: vi.fn(), // mocked behavior
+ retryIssueSplit: vi.fn(), // mocked behavior
};
});
@@ -49,7 +50,7 @@ describe('GET /api/importer/config', () => {
});
describe('POST /api/importer/classify', () => {
- beforeEach(() => vi.clearAllMocks());
+ beforeEach(() => vi.resetAllMocks());
it('returns 200 with the classifier result on success', async () => {
importerSvc.classifyImportContent.mockResolvedValue({
@@ -81,7 +82,7 @@ describe('POST /api/importer/classify', () => {
});
describe('POST /api/importer/analyze', () => {
- beforeEach(() => vi.clearAllMocks());
+ beforeEach(() => vi.resetAllMocks());
it('returns 200 with the service result on success', async () => {
importerSvc.analyzeImport.mockResolvedValue({ universe: {}, series: {}, issueProposals: [] });
@@ -128,8 +129,49 @@ describe('POST /api/importer/analyze', () => {
});
});
+describe('POST /api/importer/retry-issues', () => {
+ beforeEach(() => vi.resetAllMocks());
+
+ it('returns 200 with the re-proposed issues on success', async () => {
+ importerSvc.retryIssueSplit.mockResolvedValue({
+ issueProposals: [{ title: 'Issue 1', proseExcerpt: 'verbatim' }],
+ method: 'mechanical',
+ });
+ const app = buildApp();
+ const res = await request(app).post('/api/importer/retry-issues').send({
+ contentType: 'comic-script',
+ source: 'ISSUE #1\nstuff',
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.method).toBe('mechanical');
+ expect(res.body.issueProposals).toHaveLength(1);
+ });
+
+ it('rejects an unknown contentType at the Zod layer with 400', async () => {
+ const app = buildApp();
+ const res = await request(app).post('/api/importer/retry-issues').send({
+ contentType: 'haiku',
+ source: 'x',
+ });
+ expect(res.status).toBe(400);
+ expect(importerSvc.retryIssueSplit).not.toHaveBeenCalled();
+ });
+
+ it('maps a service ERR_VALIDATION to 400', async () => {
+ const err = Object.assign(new Error('source is required'), { code: ERR_VALIDATION });
+ importerSvc.retryIssueSplit.mockRejectedValue(err);
+ const app = buildApp();
+ const res = await request(app).post('/api/importer/retry-issues').send({
+ contentType: 'novel',
+ source: 'x',
+ });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe(ERR_VALIDATION);
+ });
+});
+
describe('POST /api/importer/commit', () => {
- beforeEach(() => vi.clearAllMocks());
+ beforeEach(() => vi.resetAllMocks());
it('returns 200 with the service result on success', async () => {
importerSvc.commitImport.mockResolvedValue({
diff --git a/server/services/importer.js b/server/services/importer.js
index 3fd206b710..6b2c2e9051 100644
--- a/server/services/importer.js
+++ b/server/services/importer.js
@@ -10,7 +10,13 @@
* future schema change only has to flip the third column.
*/
+import { randomUUID } from 'crypto';
import { runStagedLLM } from '../lib/stageRunner.js';
+import { importerEvents } from './importerEvents.js';
+// Re-export so consumers reach the analyze-phase progress bus through the
+// importer's public surface (the socket bridge imports it from the source
+// module directly; tests + future callers use this).
+export { importerEvents };
import {
listUniverses,
getUniverse,
@@ -26,7 +32,10 @@ import {
} 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 { IMPORTER_CONTENT_TYPES } from '../lib/validation.js';
+import { IMPORTER_CONTENT_TYPES, IMPORTER_PROSE_EXCERPT_MAX } from '../lib/validation.js';
+// Re-export the per-issue excerpt ceiling so callers/tests can reference the
+// same value the mechanical comic split validates against.
+export { IMPORTER_PROSE_EXCERPT_MAX };
import { mergeExtractedBible, BIBLE_KIND } from '../lib/storyBible.js';
// Surfaced to the route layer so the importer's policy errors become 400s
@@ -40,6 +49,25 @@ export const ERR_PARTIAL_COMMIT_ISSUES = 'IMPORTER_PARTIAL_COMMIT_ISSUES';
const makeErr = (message, code) => Object.assign(new Error(message), { code });
+// Ordered stages surfaced to the client's live progress checklist during the
+// analyze phase. Emitted in the `start` frame so the client renders the list
+// without hardcoding (and drifting from) it; each stage then flips to
+// `running`/`done` via `stage` frames. `canon` + `arc` run in parallel — both
+// go `running` together, then resolve independently.
+export const ANALYZE_STAGES = [
+ { id: 'canon', label: 'Extracting canon (characters, places, objects)' },
+ { id: 'arc', label: 'Extracting story arc & seasons' },
+ { id: 'issues', label: 'Proposing issue split' },
+];
+
+// Each analyze stage feeds the ENTIRE source corpus (tens of thousands of
+// chars) to a heavy-tier model in one shot, so the toolkit's 5-min default
+// (DEFAULT_TIMEOUT) is too tight — a false timeout triggers an expensive
+// from-scratch fallback re-run. 20 min gives real headroom while staying
+// under the toolkit's 30-min MAX_TIMEOUT ceiling. Passed as `timeoutOverride`
+// on every analyze stage call.
+export const ANALYZE_STAGE_TIMEOUT_MS = 1_200_000;
+
// Sanity ceiling on the source corpus — matches the schema-layer abuse guard
// (`importerSourceField`, 5MB) so the importer doesn't impose an *artificial*
// product cap below it. A 5M-char source (~3,000 pages) is far beyond any real
@@ -62,9 +90,58 @@ const DEFAULT_TARGET_ISSUE_COUNT_HINT = Object.freeze({
'comic-script': null,
});
+// Which text stage an issue's verbatim excerpt seeds at commit. A content type
+// that is ALREADY in a script form seeds that script stage (ready) so the
+// pipeline renders the user's verbatim text instead of regenerating it; prose
+// types seed `stages.prose`. One table row per new structured type — e.g.
+// screenplay → 'teleplay' is the queued follow-up (PLAN.md
+// [importer-screenplay-teleplay-seed]).
+const CONTENT_TYPE_SEED_STAGE = Object.freeze({
+ 'comic-script': 'comicScript',
+});
+const DEFAULT_SEED_STAGE = 'prose';
+const seedStageFor = (contentType) => CONTENT_TYPE_SEED_STAGE[contentType] || DEFAULT_SEED_STAGE;
+
const normName = (s) => String(s || '').trim().toLowerCase();
const isStr = (v) => typeof v === 'string';
+// Required + oversized-ceiling guard for the source corpus. Shared by
+// analyze / classify / retry-issues so the check and its (verbatim) error
+// message live in one place.
+function assertSourceWithinLimit(source) {
+ 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 — exceeds the ${IMPORTER_SOURCE_CHAR_LIMIT.toLocaleString()}-char ceiling. Trim the source or wait for chunked-extraction support.`,
+ ERR_VALIDATION,
+ );
+ }
+}
+
+// Per-content-type Mustache section-guard booleans — the prompt templates use
+// `{{#isComicScript}}…{{/isComicScript}}` blocks (Mustache, not Liquid), so we
+// expose presence flags rather than the raw contentType string.
+const buildTypeFlags = (contentType) => ({
+ isShortStory: contentType === 'short-story',
+ isNovel: contentType === 'novel',
+ isScreenplay: contentType === 'screenplay',
+ isComicScript: contentType === 'comic-script',
+});
+
+// Shared per-call options for the analyze-tier staged LLM calls. Returns a
+// FRESH object each call so the parallel canon + arc invocations can't leak
+// bookkeeping state across each other, and keeps the source tag + extended
+// timeout in lock-step across analyze and retry-issues.
+const analyzeLlmOpts = (providerOverride, modelOverride) => ({
+ providerOverride,
+ modelOverride,
+ source: 'importer-analyze',
+ returnsJson: true,
+ timeoutOverride: ANALYZE_STAGE_TIMEOUT_MS,
+});
+
// 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.
@@ -326,6 +403,183 @@ function buildArcPreview(raw) {
};
}
+// --- Mechanical comic-script splitting -------------------------------------
+//
+// A comic script is already issue/page-structured prose, so re-running it
+// through a heavy LLM to "propose" an issue split both costs tokens and
+// risks the model rephrasing verbatim panel/dialogue text. When the script
+// carries explicit ISSUE or PAGE headers we split on them deterministically
+// instead — verbatim, instant, free. Falls back (returns null) to the LLM
+// split when no headers are found so a header-less comic script still works.
+
+// Default page bundle size when a script has PAGE markers but no ISSUE
+// markers and the user didn't request a specific issue count. ~22 pages is
+// the floppy-issue convention referenced in DEFAULT_TARGET_ISSUE_COUNT_HINT.
+const COMIC_PAGES_PER_ISSUE = 22;
+
+// Header-like line gate: comic ISSUE/PAGE headers sit on their own short,
+// usually all-caps line. Capping length keeps a prose sentence that happens
+// to open with "Page " or "Issue " from being mistaken for a structural
+// marker (the LLM fallback still covers genuinely header-less scripts).
+const COMIC_HEADER_MAX_LEN = 80;
+// The number token that legitimately follows ISSUE/PAGE in a header: a digit
+// run or a spelled-out number word. Crucially this is NOT `[a-z]+` — an open
+// word class matched ordinary prose like "Issue resolved." or "Pages turned
+// slowly" and (because the mechanical path wins whenever ≥1 header is found)
+// mis-split the script with no LLM fallback. Roman numerals are deliberately
+// excluded: under the case-insensitive flag `[IVXLCDM]+` matches common prose
+// words ("mild", "did", "civic"), so a rare "PAGE IV" header simply falls back
+// to the LLM split instead.
+const COMIC_NUM = '(?:\\d{1,3}|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred)';
+// `ISSUE #3`, `ISSUE 3`, `ISSUE THREE`, `ISSUE 3: TITLE`, `ISSUE THREE - TITLE`.
+// The `\b` after the keyword also stops "ISSUES with the plan…" from matching.
+const ISSUE_HEADER_RE = new RegExp(`^issue\\b\\s*#?\\s*(${COMIC_NUM})\\b\\s*[:.\\-–—]?\\s*(.*)$`, 'i');
+// `PAGE 1`, `PAGE ONE`, `PAGES 2-3`, `PAGE ONE (FIVE PANELS)`
+const PAGE_HEADER_RE = new RegExp(`^pages?\\b\\s*#?\\s*(${COMIC_NUM})\\b`, 'i');
+
+// Locate header lines matching `re`. Returns `[{ idx, title }]` where `idx`
+// is the 0-based line index and `title` is the trailing text after the
+// number (ISSUE only; '' otherwise).
+function findComicHeaders(lines, re) {
+ const headers = [];
+ for (let i = 0; i < lines.length; i++) {
+ const t = lines[i].trim();
+ if (!t || t.length > COMIC_HEADER_MAX_LEN) continue;
+ const m = re.exec(t);
+ if (m) headers.push({ idx: i, title: (m[2] || '').trim() });
+ }
+ return headers;
+}
+
+// Slice `lines[startIdx..endIdx)` back into a verbatim string (newline-
+// joined) and trim surrounding blank lines without touching interior text.
+function joinSegment(lines, startIdx, endIdx) {
+ return lines.slice(startIdx, endIdx).join('\n').replace(/^\n+|\n+$/g, '');
+}
+
+/**
+ * Mechanically split a comic script into issue proposals on its ISSUE / PAGE
+ * headers. Returns an array of `{ title, arcPosition, proseExcerpt }` (no
+ * logline/synopsis — the split deliberately does NOT interpret), or `null`
+ * when no usable headers are found (caller falls back to the LLM split).
+ *
+ * Pure + exported for unit testing. `targetIssueCount` (when a positive
+ * integer) forces the PAGE-bundling path to produce exactly that many issues,
+ * evenly distributed; ISSUE headers always win when present.
+ */
+export function splitComicScriptIssues(source, { targetIssueCount = null } = {}) {
+ if (!isStr(source) || !source.trim()) return null;
+ const lines = source.split(/\r\n|\r|\n/);
+
+ // 1) Explicit ISSUE headers — one issue per header, verbatim. Any text
+ // before the first header (title page / credits) folds into issue 1.
+ const issueHeaders = findComicHeaders(lines, ISSUE_HEADER_RE);
+ if (issueHeaders.length > 0) {
+ const out = [];
+ for (let i = 0; i < issueHeaders.length; i++) {
+ const startIdx = i === 0 ? 0 : issueHeaders[i].idx;
+ const endIdx = i + 1 < issueHeaders.length ? issueHeaders[i + 1].idx : lines.length;
+ const proseExcerpt = joinSegment(lines, startIdx, endIdx);
+ if (!proseExcerpt.trim()) continue;
+ out.push({
+ // Preserve the script's own issue title verbatim when present;
+ // otherwise label sequentially. Title-casing would be a rewrite.
+ title: issueHeaders[i].title || `Issue ${i + 1}`,
+ arcPosition: i + 1,
+ proseExcerpt,
+ });
+ }
+ return out.length > 0 ? out : null;
+ }
+
+ // 2) No ISSUE headers — bundle PAGE markers into issues.
+ const pageHeaders = findComicHeaders(lines, PAGE_HEADER_RE);
+ if (pageHeaders.length === 0) return null; // header-less → LLM fallback
+
+ // Each page spans from its header to the next (preamble folds into page 1).
+ const pages = pageHeaders.map((h, i) => {
+ const startIdx = i === 0 ? 0 : h.idx;
+ const endIdx = i + 1 < pageHeaders.length ? pageHeaders[i + 1].idx : lines.length;
+ return joinSegment(lines, startIdx, endIdx);
+ }).filter((p) => p.trim());
+ if (pages.length === 0) return null;
+
+ // How many issues to produce: explicit user count (clamped to page count)
+ // beats the ~22-pages-per-issue default.
+ const requested = Number.isInteger(targetIssueCount) && targetIssueCount > 0
+ ? Math.min(targetIssueCount, pages.length)
+ : Math.max(1, Math.ceil(pages.length / COMIC_PAGES_PER_ISSUE));
+
+ // Distribute pages as evenly as possible across `requested` issues — the
+ // first `remainder` issues get one extra page so no pages are dropped.
+ const base = Math.floor(pages.length / requested);
+ const remainder = pages.length % requested;
+ const out = [];
+ let cursor = 0;
+ for (let i = 0; i < requested; i++) {
+ const take = base + (i < remainder ? 1 : 0);
+ const slice = pages.slice(cursor, cursor + take);
+ cursor += take;
+ const proseExcerpt = slice.join('\n\n').replace(/^\n+|\n+$/g, '');
+ if (!proseExcerpt.trim()) continue;
+ out.push({ title: `Issue ${i + 1}`, arcPosition: i + 1, proseExcerpt });
+ }
+ return out.length > 0 ? out : null;
+}
+
+/**
+ * Propose the issue split for a source. Comic scripts try the mechanical
+ * header split first (verbatim, no LLM); everything else — and header-less
+ * comics — fall through to the staged `importer-issue-proposal` LLM call.
+ * Shared by `analyzeImport` and the retry-issues route so both honor the
+ * mechanical path identically.
+ *
+ * Returns `{ issues, runId, method }` where `method` is `'mechanical'`
+ * (runId null) or `'llm'`.
+ */
+async function proposeIssues({ seriesName, contentType, source, typeFlags, arcSummary, targetIssueCount, userRequestedCount, llmOpts }) {
+ if (contentType === 'comic-script') {
+ const mechanical = splitComicScriptIssues(source, {
+ targetIssueCount: userRequestedCount ? targetIssueCount : null,
+ });
+ if (mechanical && mechanical.length > 0) {
+ // A verbatim issue can exceed the commit-time proseExcerpt ceiling.
+ // Fail HERE (analyze/retry) with an actionable message instead of
+ // letting it sail through to a confusing commit-time 400.
+ const oversized = mechanical.findIndex((iss) => iss.proseExcerpt.length > IMPORTER_PROSE_EXCERPT_MAX);
+ if (oversized !== -1) {
+ throw makeErr(
+ `Issue ${oversized + 1} of the comic split is ${mechanical[oversized].proseExcerpt.length.toLocaleString()} chars — over the ${IMPORTER_PROSE_EXCERPT_MAX.toLocaleString()}-char per-issue limit. Add ISSUE/PAGE headers so it splits into smaller issues, or split the source.`,
+ ERR_VALIDATION,
+ );
+ }
+ console.log(`📚 importer: split comic script into ${mechanical.length} issue(s) on existing headers (no LLM rewrite)`);
+ return { issues: mechanical, runId: null, method: 'mechanical' };
+ }
+ }
+ const issueCountHint = userRequestedCount
+ ? targetIssueCount
+ : DEFAULT_TARGET_ISSUE_COUNT_HINT[contentType];
+ const issuesRun = await runStagedLLM('importer-issue-proposal', {
+ seriesName,
+ 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,
+ }, llmOpts);
+ return {
+ issues: Array.isArray(issuesRun.content?.issues) ? issuesRun.content.issues : [],
+ runId: issuesRun.runId,
+ method: 'llm',
+ };
+}
+
const CLASSIFIER_CONFIDENCES = new Set(['high', 'medium', 'low']);
// 4K chars is roughly 1 200 tokens — enough to see chapter markers, scene
// headings, and panel breaks. Exported so the client can trim its payload
@@ -345,15 +599,7 @@ export const CLASSIFY_SOURCE_HEAD_CHARS = 4_000;
* UI can show it in a tooltip beside the auto-pick.
*/
export async function classifyImportContent({ source, providerOverride, modelOverride } = {}) {
- 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 — exceeds the ${IMPORTER_SOURCE_CHAR_LIMIT.toLocaleString()}-char ceiling. Trim the source or wait for chunked-extraction support.`,
- ERR_VALIDATION,
- );
- }
+ assertSourceWithinLimit(source);
const sourceHead = source.slice(0, CLASSIFY_SOURCE_HEAD_CHARS);
const run = await runStagedLLM('importer-classify', { sourceHead }, {
providerOverride,
@@ -385,11 +631,13 @@ export async function classifyImportContent({ source, providerOverride, modelOve
* 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.
+ * Partial-failure safety: universe + series are NOT written to disk until
+ * after the canon + arc passes succeed. A failure in either of those leaves
+ * no orphaned half-created records behind (the function throws before any
+ * create). The issue split, by contrast, is non-fatal — canon + arc are the
+ * expensive passes, so a split timeout/parse error sets `issueSplitFailed`
+ * and still returns the canon + arc preview (with universe + series shells
+ * persisted) so the client can retry ONLY the split via `retryIssueSplit`.
*/
export async function analyzeImport({
universeName,
@@ -406,15 +654,7 @@ export async function analyzeImport({
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 — exceeds the ${IMPORTER_SOURCE_CHAR_LIMIT.toLocaleString()}-char ceiling. Trim the source or wait for chunked-extraction support.`,
- ERR_VALIDATION,
- );
- }
+ assertSourceWithinLimit(source);
// Look up pre-existing records WITHOUT creating anything yet. Creation is
// deferred until after all LLM calls succeed so a failure above never
@@ -448,25 +688,31 @@ export async function analyzeImport({
// 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, modelOverride, source: 'importer-analyze', returnsJson: true });
+ // option). `analyzeLlmOpts` returns a FRESH object each call so a future
+ // runner that adds bookkeeping can't leak state across our parallel
+ // canon + arc invocations.
+ const buildLlmOpts = () => analyzeLlmOpts(providerOverride, modelOverride);
+ // Live stage progress (see ANALYZE_STAGES). `runId` lets the client ignore
+ // stragglers from a prior run. Emitting is best-effort UI sugar — never let
+ // a listener throw abort the extraction, so swallow + log at this boundary.
+ const runId = randomUUID();
+ const emitProgress = (frame) => {
+ try {
+ importerEvents.emit('progress', { runId, ...frame });
+ } catch (err) {
+ console.error(`❌ importer progress emit failed: ${err.message}`);
+ }
+ };
+ const emitStage = (id, status) => emitProgress({ type: 'stage', id, status });
+ emitProgress({ type: 'start', stages: ANALYZE_STAGES });
+
+ // `proposeIssues` derives the per-type issue-count hint internally; analyze
+ // only needs the boolean to forward.
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',
- };
+ // Per-type Mustache section-guard booleans (see buildTypeFlags).
+ const typeFlags = buildTypeFlags(contentType);
// Use the known persisted name for prompt variables when the record
// already exists; fall back to the trimmed input for new records.
@@ -476,6 +722,11 @@ export async function analyzeImport({
// Canon + arc are independent reads of the same source — fire in
// parallel. Issue-proposal depends on the arc summary, so chain after
// arc resolves.
+ emitStage('canon', 'running');
+ emitStage('arc', 'running');
+ // `.then` on each promise flips its stage to `done` the moment that pass
+ // resolves — Promise.all alone would only report after BOTH finish, which
+ // would make the slower of the two appear stalled in the checklist.
const [canonRun, arcRun] = await Promise.all([
runStagedLLM('importer-canon-extract', {
universeName: promptUniverseName,
@@ -484,13 +735,13 @@ export async function analyzeImport({
source,
existingCanonBlock: buildExistingCanonBlock(existingCanon),
...typeFlags,
- }, buildLlmOpts()),
+ }, buildLlmOpts()).then((r) => { emitStage('canon', 'done'); return r; }),
runStagedLLM('importer-arc-extract', {
seriesName: promptSeriesName,
contentType,
source,
...typeFlags,
- }, buildLlmOpts()),
+ }, buildLlmOpts()).then((r) => { emitStage('arc', 'done'); return r; }),
]);
// Pull the arc summary in before issue-proposal so the issue boundaries
@@ -508,23 +759,45 @@ export async function analyzeImport({
}
const arcSummary = arcContent.summary || arcContent.logline || `${promptSeriesName} — ${contentType}`;
- const issuesRun = await runStagedLLM('importer-issue-proposal', {
+ emitStage('issues', 'running');
+ // Issue split tolerates failure: canon + arc are the expensive passes and
+ // they already succeeded, so a timeout / parse error on the split must NOT
+ // throw them away. On failure we flag `issueSplitFailed` and return the
+ // canon + arc preview anyway — the client offers a "retry issue split" that
+ // re-runs ONLY this pass (see POST /api/importer/retry-issues). Comic
+ // scripts take the mechanical header split first (no LLM), which both
+ // sidesteps the timeout and preserves verbatim panel/dialogue text.
+ let issueProposals = [];
+ let issuesRunId = null;
+ let issueSplitFailed = false;
+ let issueSplitError = null;
+ const issueResult = await proposeIssues({
seriesName: promptSeriesName,
contentType,
source,
- ...typeFlags,
+ 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());
+ targetIssueCount,
+ userRequestedCount,
+ llmOpts: buildLlmOpts(),
+ }).catch((err) => {
+ issueSplitFailed = true;
+ issueSplitError = err?.message || String(err);
+ console.error(`❌ importer issue split failed (canon+arc preserved): ${issueSplitError}`);
+ return null;
+ });
+ if (issueResult) {
+ issueProposals = issueResult.issues;
+ issuesRunId = issueResult.runId;
+ emitStage('issues', 'done');
+ } else {
+ emitStage('issues', 'error');
+ }
- // 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.
+ // Canon + arc succeeded — persist any new records so the preview has stable
+ // ids the client can commit/retry against. The issue split may have failed
+ // (issueSplitFailed); that's surfaced to the client, not fatal. Pre-existing
+ // records are returned as-is.
//
// 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
@@ -563,11 +836,15 @@ export async function analyzeImport({
},
arcPreview,
seasonsPreview: Array.isArray(arcRun.content?.seasons) ? arcRun.content.seasons : [],
- issueProposals: Array.isArray(issuesRun.content?.issues) ? issuesRun.content.issues : [],
+ issueProposals,
+ // True when the issue split failed after canon+arc succeeded — the client
+ // shows a "retry issue split" affordance instead of throwing the run away.
+ issueSplitFailed,
+ issueSplitError,
runIds: {
canon: canonRun.runId,
arc: arcRun.runId,
- issues: issuesRun.runId,
+ issues: issuesRunId,
},
providerId: canonRun.providerId,
model: canonRun.model,
@@ -586,6 +863,44 @@ export async function analyzeImport({
};
}
+/**
+ * Re-run ONLY the issue split — the recovery path when `analyzeImport`
+ * returned `issueSplitFailed: true` (canon + arc succeeded, the split timed
+ * out / failed). Re-extracting canon + arc would burn the two expensive
+ * passes again, so this re-runs just the split against the same source, with
+ * the arc summary the user already has in the Review panel for alignment.
+ * Comic scripts take the mechanical header path first (see `proposeIssues`).
+ */
+export async function retryIssueSplit({
+ contentType,
+ source,
+ seriesName,
+ arcSummary,
+ targetIssueCount,
+ providerOverride,
+ modelOverride,
+} = {}) {
+ assertSourceWithinLimit(source);
+ if (!IMPORTER_CONTENT_TYPES.includes(contentType)) {
+ throw makeErr(`Unknown contentType "${contentType}"`, ERR_VALIDATION);
+ }
+ const userRequestedCount = Number.isFinite(targetIssueCount) && targetIssueCount > 0;
+ const promptSeriesName = isStr(seriesName) && seriesName.trim() ? seriesName.trim() : 'the series';
+ const result = await proposeIssues({
+ seriesName: promptSeriesName,
+ contentType,
+ typeFlags: buildTypeFlags(contentType),
+ source,
+ // Fall back to a synthetic summary so the LLM prompt always has the
+ // {{arcSummary}} var (the mechanical comic path ignores it entirely).
+ arcSummary: isStr(arcSummary) && arcSummary.trim() ? arcSummary : `${promptSeriesName} — ${contentType}`,
+ targetIssueCount,
+ userRequestedCount,
+ llmOpts: analyzeLlmOpts(providerOverride, modelOverride),
+ });
+ return { issueProposals: result.issues, method: result.method, runId: result.runId };
+}
+
/**
* Phase 2: commit. Merges the user-confirmed canon into the universe,
* writes the arc + seasons onto the series, then creates one issue per
@@ -599,6 +914,9 @@ export async function commitImport({
arc = null,
seasons = [],
issues = [],
+ // Content type drives which stage each issue's verbatim excerpt seeds (see
+ // the stage-seed block below). Absent → prose-seed (prior behavior).
+ contentType = null,
// Destructive replace: wipes existing issues, overwrites arc + seasons.
// Universe canon still merges additively (it's shared across series, so
// a per-series destructive replace would be too coarse). Default false.
@@ -942,7 +1260,11 @@ export async function commitImport({
// create + updateStage(prose) + updateStage(idea).
const stages = {};
if (proposal.proseExcerpt) {
- stages.prose = { status: 'ready', output: proposal.proseExcerpt };
+ // Route the verbatim excerpt to the stage that matches the source form
+ // (see CONTENT_TYPE_SEED_STAGE): a comic-script seeds stages.comicScript
+ // (ready) so the pipeline renders the user's verbatim script instead of
+ // regenerating it; everything else seeds stages.prose.
+ stages[seedStageFor(contentType)] = { status: 'ready', output: proposal.proseExcerpt };
}
const ideaSeed = [
proposal.logline && `Logline: ${proposal.logline}`,
diff --git a/server/services/importer.test.js b/server/services/importer.test.js
index 5a564d18e5..22223f0fbe 100644
--- a/server/services/importer.test.js
+++ b/server/services/importer.test.js
@@ -209,6 +209,81 @@ function wireDefaultLLMResponses() {
});
}
+describe('splitComicScriptIssues (mechanical comic split)', () => {
+ it('splits on ISSUE headers — one verbatim issue each, sequential positions', () => {
+ const src = [
+ 'ISSUE #1: THE FOUNDRY',
+ 'PAGE 1',
+ 'Panel 1. Aria forges a blade.',
+ 'ISSUE #2: THE LOCKET',
+ 'PAGE 1',
+ 'Panel 1. The vault loomed.',
+ ].join('\n');
+ const out = importerSvc.splitComicScriptIssues(src);
+ expect(out).toHaveLength(2);
+ expect(out[0].arcPosition).toBe(1);
+ expect(out[1].arcPosition).toBe(2);
+ // Title preserved verbatim from the header; prose is verbatim + bounded.
+ expect(out[0].title).toBe('THE FOUNDRY');
+ expect(out[0].proseExcerpt).toContain('Aria forges a blade');
+ expect(out[0].proseExcerpt).toContain('ISSUE #1');
+ expect(out[0].proseExcerpt).not.toContain('The vault'); // boundary holds
+ expect(out[1].title).toBe('THE LOCKET');
+ expect(out[1].proseExcerpt).toContain('The vault loomed');
+ // No interpretation — mechanical split sets no logline/synopsis.
+ expect(out[0].logline).toBeUndefined();
+ expect(out[0].synopsis).toBeUndefined();
+ });
+
+ it('labels sequentially when an ISSUE header carries no title', () => {
+ const out = importerSvc.splitComicScriptIssues('ISSUE ONE\nstuff\nISSUE TWO\nmore');
+ expect(out.map((i) => i.title)).toEqual(['Issue 1', 'Issue 2']);
+ });
+
+ it('bundles PAGE markers into ~22-page issues when there are no ISSUE headers', () => {
+ const lines = [];
+ for (let p = 1; p <= 25; p++) { lines.push(`PAGE ${p}`); lines.push(`content ${p}`); }
+ const out = importerSvc.splitComicScriptIssues(lines.join('\n'));
+ expect(out).toHaveLength(2); // ceil(25 / 22)
+ expect(out[0].proseExcerpt).toContain('content 1');
+ expect(out[1].proseExcerpt).toContain('content 25');
+ // every page lands somewhere (no drops)
+ const joined = out.map((i) => i.proseExcerpt).join('\n');
+ for (let p = 1; p <= 25; p++) expect(joined).toContain(`content ${p}`);
+ });
+
+ it('honors an explicit targetIssueCount in the PAGE-bundle path', () => {
+ const lines = [];
+ for (let p = 1; p <= 6; p++) { lines.push(`PAGE ${p}`); lines.push(`c${p}`); }
+ const out = importerSvc.splitComicScriptIssues(lines.join('\n'), { targetIssueCount: 3 });
+ expect(out).toHaveLength(3);
+ });
+
+ it('returns null for a header-less script so the caller falls back to the LLM', () => {
+ expect(importerSvc.splitComicScriptIssues('Just prose, no markers anywhere here.')).toBeNull();
+ });
+
+ it('does not mistake a long prose sentence opening with "Page" for a header', () => {
+ const src = 'Page after page of the manuscript blurred together as she read on into the small hours.';
+ expect(importerSvc.splitComicScriptIssues(src)).toBeNull();
+ });
+
+ it('does not match a plural-keyword prose line ("ISSUES …") as an ISSUE header', () => {
+ // Word boundary after the keyword: "ISSUES" must not read as "ISSUE".
+ expect(importerSvc.splitComicScriptIssues('ISSUES with the forge piled up fast.')).toBeNull();
+ });
+
+ it('does not treat a prose line "Issue <word>" / "Pages <word>" as a header (number-token gate)', () => {
+ // The header number token is digits or spelled numbers — NOT any word —
+ // so ordinary prose that opens with the keyword no longer mis-splits.
+ expect(importerSvc.splitComicScriptIssues('Issue resolved by the council that night.')).toBeNull();
+ expect(importerSvc.splitComicScriptIssues('Pages turned slowly as the night wore on.')).toBeNull();
+ // A genuine spelled-number header still splits.
+ const out = importerSvc.splitComicScriptIssues('ISSUE ONE\nstuff\nISSUE TWO\nmore');
+ expect(out).toHaveLength(2);
+ });
+});
+
describe('analyzeImport', () => {
it('creates universe + series on first run and returns preview shape', async () => {
wireDefaultLLMResponses();
@@ -348,6 +423,138 @@ describe('analyzeImport', () => {
expect(canonCall[1].existingCanonBlock).toContain('Aria Existing');
});
+ it('emits ordered stage-progress frames with a stable runId', async () => {
+ // Regression-pin: the Importer page renders a live checklist from these
+ // `progress` frames. A `start` opens the run (carrying the stage list);
+ // each pass then flips `running`→`done`, and every frame shares one runId
+ // so the client can ignore stragglers from a prior run.
+ wireDefaultLLMResponses();
+ const frames = [];
+ const onProgress = (f) => frames.push(f);
+ importerSvc.importerEvents.on('progress', onProgress);
+ try {
+ await importerSvc.analyzeImport({
+ universeName: 'Progress U', seriesName: 'Progress S', contentType: 'short-story', source: 'x',
+ });
+ } finally {
+ importerSvc.importerEvents.off('progress', onProgress);
+ }
+
+ const start = frames.find((f) => f.type === 'start');
+ expect(start).toBeDefined();
+ expect(start.stages.map((s) => s.id)).toEqual(['canon', 'arc', 'issues']);
+
+ // Every frame shares the start frame's runId.
+ const runId = start.runId;
+ expect(runId).toBeTruthy();
+ expect(frames.every((f) => f.runId === runId)).toBe(true);
+
+ // Each stage reaches both running and done.
+ for (const id of ['canon', 'arc', 'issues']) {
+ const statuses = frames.filter((f) => f.type === 'stage' && f.id === id).map((f) => f.status);
+ expect(statuses).toContain('running');
+ expect(statuses).toContain('done');
+ }
+
+ // issues can't start until arc resolves — its `running` follows arc `done`.
+ const arcDoneIdx = frames.findIndex((f) => f.type === 'stage' && f.id === 'arc' && f.status === 'done');
+ const issuesRunningIdx = frames.findIndex((f) => f.type === 'stage' && f.id === 'issues' && f.status === 'running');
+ expect(issuesRunningIdx).toBeGreaterThan(arcDoneIdx);
+ });
+
+ it('passes the extended analyze timeout to every staged LLM call', async () => {
+ // Regression-pin: each analyze pass feeds the whole corpus to a heavy
+ // model, so the importer overrides the toolkit's 5-min default. A dropped
+ // override would reintroduce false timeouts + expensive fallback re-runs.
+ wireDefaultLLMResponses();
+ await importerSvc.analyzeImport({
+ universeName: 'Timeout U', seriesName: 'Timeout S', contentType: 'short-story', source: 'x',
+ });
+ expect(mockRunStagedLLM).toHaveBeenCalled();
+ for (const call of mockRunStagedLLM.mock.calls) {
+ expect(call[2]).toMatchObject({ timeoutOverride: importerSvc.ANALYZE_STAGE_TIMEOUT_MS });
+ }
+ });
+
+ it('mechanically splits a comic script and skips the LLM issue-proposal call', async () => {
+ wireDefaultLLMResponses();
+ const src = 'ISSUE #1: ONE\nPage stuff here.\nISSUE #2: TWO\nMore page stuff.';
+ const result = await importerSvc.analyzeImport({
+ universeName: 'Comic U', seriesName: 'Comic S', contentType: 'comic-script', source: src,
+ });
+ expect(result.issueSplitFailed).toBe(false);
+ expect(result.issueProposals).toHaveLength(2);
+ expect(result.issueProposals[0].proseExcerpt).toContain('Page stuff here');
+ // The LLM split was NOT invoked — canon + arc still were.
+ const issueCall = mockRunStagedLLM.mock.calls.find((c) => c[0] === 'importer-issue-proposal');
+ expect(issueCall).toBeUndefined();
+ expect(mockRunStagedLLM.mock.calls.some((c) => c[0] === 'importer-canon-extract')).toBe(true);
+ // Mechanical path carries no run id.
+ expect(result.runIds.issues).toBeNull();
+ });
+
+ it('preserves canon+arc and flags issueSplitFailed when the issue split throws', async () => {
+ // canon + arc succeed; the issue-proposal pass throws (e.g. a timeout).
+ // The expensive passes must NOT be discarded — analyze returns the
+ // preview with issueSplitFailed=true and persisted universe/series shells.
+ 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') throw new Error('codex timed out after 1200000ms');
+ throw new Error(`Unexpected stage: ${stageName}`);
+ });
+ // Capture progress frames to assert the issues stage reaches 'error'.
+ const frames = [];
+ const onProgress = (f) => frames.push(f);
+ importerSvc.importerEvents.on('progress', onProgress);
+ let result;
+ try {
+ result = await importerSvc.analyzeImport({
+ universeName: 'Resilient U', seriesName: 'Resilient S', contentType: 'novel', source: 'x',
+ });
+ } finally {
+ importerSvc.importerEvents.off('progress', onProgress);
+ }
+ expect(result.issueSplitFailed).toBe(true);
+ expect(result.issueSplitError).toContain('codex timed out');
+ expect(result.issueProposals).toEqual([]);
+ // The checklist's issues stage must reach a terminal 'error' frame (drives
+ // the client's error icon + retry banner).
+ const issuesStatuses = frames.filter((f) => f.type === 'stage' && f.id === 'issues').map((f) => f.status);
+ expect(issuesStatuses).toContain('running');
+ expect(issuesStatuses).toContain('error');
+ // Canon + arc preserved.
+ expect(result.canonPreview.characters).toHaveLength(1);
+ expect(result.arcPreview.shape).toBe('man-in-hole');
+ // Universe + series are actually PERSISTED (not just in-memory shells) so
+ // the client has stable ids to retry/commit against — re-read from disk.
+ expect(result.universe.id).toBeDefined();
+ expect(result.series.id).toMatch(/^ser-/);
+ expect(await universeSvc.getUniverse(result.universe.id)).toBeTruthy();
+ expect(await seriesSvc.getSeries(result.series.id)).toBeTruthy();
+ expect(result.runIds.issues).toBeNull();
+ });
+
+ it('fails analyze with ERR_VALIDATION when a comic split would exceed the per-issue prose cap', async () => {
+ // One ISSUE header with a body over IMPORTER_PROSE_EXCERPT_MAX → the
+ // verbatim excerpt would be rejected at commit; surface it at analyze
+ // instead of letting it dead-end on a commit-time 400. The failure rides
+ // the non-fatal issue-split path, so canon+arc are still preserved.
+ 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' };
+ throw new Error(`Unexpected stage: ${stageName}`);
+ });
+ const huge = `ISSUE 1\n${'x'.repeat(importerSvc.IMPORTER_PROSE_EXCERPT_MAX + 10)}`;
+ const result = await importerSvc.analyzeImport({
+ universeName: 'Big Comic U', seriesName: 'Big Comic S', contentType: 'comic-script', source: huge,
+ });
+ expect(result.issueSplitFailed).toBe(true);
+ expect(result.issueSplitError).toMatch(/per-issue limit/);
+ // No LLM issue-proposal call happened (the cap check fired on the mechanical path).
+ expect(mockRunStagedLLM.mock.calls.some((c) => c[0] === 'importer-issue-proposal')).toBe(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' });
@@ -383,6 +590,41 @@ describe('analyzeImport', () => {
// guard branch directly against the service.
// ---------------------------------------------------------------------------
+describe('retryIssueSplit', () => {
+ it('mechanically splits a comic script with no LLM call', async () => {
+ wireDefaultLLMResponses();
+ const out = await importerSvc.retryIssueSplit({
+ contentType: 'comic-script',
+ source: 'ISSUE #1: A\nstuff\nISSUE #2: B\nmore',
+ });
+ expect(out.method).toBe('mechanical');
+ expect(out.issueProposals).toHaveLength(2);
+ expect(out.runId).toBeNull();
+ expect(mockRunStagedLLM).not.toHaveBeenCalled();
+ });
+
+ it('falls through to the LLM split for prose content types, with the extended timeout', async () => {
+ wireDefaultLLMResponses();
+ const out = await importerSvc.retryIssueSplit({
+ contentType: 'novel', source: 'a novel body', arcSummary: 'the arc summary',
+ });
+ expect(out.method).toBe('llm');
+ expect(out.issueProposals).toHaveLength(1);
+ const call = mockRunStagedLLM.mock.calls.find((c) => c[0] === 'importer-issue-proposal');
+ expect(call).toBeDefined();
+ expect(call[2]).toMatchObject({ timeoutOverride: importerSvc.ANALYZE_STAGE_TIMEOUT_MS });
+ });
+
+ it('rejects an oversized source before calling the LLM', async () => {
+ wireDefaultLLMResponses();
+ await expect(importerSvc.retryIssueSplit({
+ contentType: 'novel',
+ source: 'x'.repeat(importerSvc.IMPORTER_SOURCE_CHAR_LIMIT + 1),
+ })).rejects.toMatchObject({ code: importerSvc.ERR_VALIDATION });
+ expect(mockRunStagedLLM).not.toHaveBeenCalled();
+ });
+});
+
describe('classifyImportContent', () => {
it('passes valid contentType + confidence + reasoning through verbatim', async () => {
mockRunStagedLLM.mockResolvedValueOnce({
@@ -608,6 +850,39 @@ describe('commitImport', () => {
expect(issue.seasonId).toBe(result.series.seasons[0].id);
});
+ it('seeds stages.comicScript (not prose) for a comic-script import', async () => {
+ // A comic-script source is already script-form, so its verbatim excerpt
+ // must land in comicScript (ready) — seeding prose would make the
+ // pipeline regenerate (re-interpret) the script.
+ const { uni, ser } = await setupForCommit();
+ const script = 'PAGE 1\nPANEL 1\nGiant descends.\nCAPTION\nNot real.';
+ const result = await importerSvc.commitImport({
+ universeId: uni.id,
+ seriesId: ser.id,
+ contentType: 'comic-script',
+ canonSelections: { characters: [], places: [], objects: [] },
+ issues: [{ title: 'Issue 1', arcPosition: 1, proseExcerpt: script }],
+ });
+ const issue = await issuesSvc.getIssue(result.createdIssueIds[0]);
+ expect(issue.stages.comicScript.output).toBe(script);
+ expect(issue.stages.comicScript.status).toBe('ready');
+ // prose is NOT seeded — the script never round-trips through it.
+ expect(issue.stages.prose?.output).toBeFalsy();
+ });
+
+ it('still seeds stages.prose when contentType is absent (older clients)', async () => {
+ const { uni, ser } = await setupForCommit();
+ const result = await importerSvc.commitImport({
+ universeId: uni.id,
+ seriesId: ser.id,
+ canonSelections: { characters: [], places: [], objects: [] },
+ issues: [{ title: 'Issue 1', arcPosition: 1, proseExcerpt: 'Plain prose.' }],
+ });
+ const issue = await issuesSvc.getIssue(result.createdIssueIds[0]);
+ expect(issue.stages.prose.output).toBe('Plain prose.');
+ expect(issue.stages.comicScript?.output).toBeFalsy();
+ });
+
it('refuses to commit when the series arc is locked', async () => {
const { uni, ser } = await setupForCommit();
await seriesSvc.updateSeries(ser.id, { locked: { arc: true } });
diff --git a/server/services/importerEvents.js b/server/services/importerEvents.js
new file mode 100644
index 0000000000..5bf2af90c7
--- /dev/null
+++ b/server/services/importerEvents.js
@@ -0,0 +1,12 @@
+import { EventEmitter } from 'events';
+
+// Stage-progress bus for the importer's analyze phase. `analyzeImport` runs
+// several heavy-tier AI passes (canon + arc in parallel, then issue split)
+// over a single blocking HTTP request, so the client has no way to see which
+// pass is in flight without a side channel. The orchestrator emits `progress`
+// frames here; `socket.js` bridges them to `importer:progress` on Socket.IO,
+// and the Importer page renders a live stage checklist while it waits.
+//
+// Single-user trust model: at most one analyze runs at a time, but each frame
+// carries a `runId` so the client can ignore stragglers from a prior run.
+export const importerEvents = new EventEmitter();
diff --git a/server/services/pipeline/autoRunner.js b/server/services/pipeline/autoRunner.js
index bf9b203ee4..d042696482 100644
--- a/server/services/pipeline/autoRunner.js
+++ b/server/services/pipeline/autoRunner.js
@@ -75,9 +75,24 @@ export async function startAutoRunTextStages(issueId, options = {}) {
if (!record.cancelRequested) {
await runStageIfNeeded(issueId, 'idea', options);
}
- // Stage 2: prose — depends on idea
+ // Stage 2: prose — depends on idea. SKIP when the issue arrived
+ // script-first (an imported comic seeds stages.comicScript ready with
+ // prose empty): forward-generating prose here would synthesize content
+ // the authored script was never derived from, burn tokens, and — because
+ // editorialAnalysis prefers prose — make the Reader Map analyze the
+ // generated prose instead of the user's verbatim script. A backport
+ // (Create → Importer) is the deliberate way to fill prose from the
+ // script. `force` still regenerates.
if (!record.cancelRequested) {
- await runStageIfNeeded(issueId, 'prose', options);
+ const proseIssue = await getIssue(issueId);
+ const proseEmpty = !isStageReady(proseIssue.stages?.prose);
+ const scriptAuthored = isStageReady(proseIssue.stages?.comicScript)
+ || isStageReady(proseIssue.stages?.teleplay);
+ if (proseEmpty && scriptAuthored && !options.force) {
+ broadcast(issueId, { type: 'skip', stage: 'prose', reason: 'script already authored (imported script-first) — not back-filling prose' });
+ } else {
+ await runStageIfNeeded(issueId, 'prose', options);
+ }
}
// Stage 3: comicScript + teleplay in parallel — both depend only on prose
if (!record.cancelRequested) {
diff --git a/server/services/pipeline/autoRunner.test.js b/server/services/pipeline/autoRunner.test.js
index a0193b4104..64e6193b29 100644
--- a/server/services/pipeline/autoRunner.test.js
+++ b/server/services/pipeline/autoRunner.test.js
@@ -120,6 +120,32 @@ describe('pipeline auto-runner', () => {
expect(generated).toContain('idea');
});
+ it('does NOT back-fill prose when a script stage is already authored (imported script-first)', async () => {
+ // An imported comic seeds stages.comicScript ready with prose empty.
+ // Forward-generating prose would synthesize content the script wasn't
+ // derived from and (via editorialAnalysis's prose-preference) shadow the
+ // verbatim script — so the auto-runner must skip prose here.
+ const { issue } = await seed();
+ await issuesSvc.updateStage(issue.id, 'comicScript', { status: 'ready', output: 'PAGE 1\nPANEL 1\nA scene.' });
+ await autoRunner.startAutoRunTextStages(issue.id);
+ await waitFor(() => {
+ const run = autoRunner.__testing.runs.get(issue.id);
+ return run?.lastPayload?.type === 'complete';
+ });
+ expect(generated).not.toContain('prose'); // skipped — script-first
+ expect(generated).not.toContain('comicScript'); // already ready
+ const final = await issuesSvc.getIssue(issue.id);
+ expect(final.stages?.prose?.output || '').toBe('');
+ });
+
+ it('DOES generate prose for a script-first issue when force=true', async () => {
+ const { issue } = await seed();
+ await issuesSvc.updateStage(issue.id, 'comicScript', { status: 'ready', output: 'PAGE 1\nPANEL 1\nA scene.' });
+ await autoRunner.startAutoRunTextStages(issue.id, { force: true });
+ await waitFor(() => generated.includes('prose'));
+ expect(generated).toContain('prose');
+ });
+
it('returns alreadyRunning=true on concurrent start', async () => {
const { issue } = await seed();
const first = await autoRunner.startAutoRunTextStages(issue.id);
diff --git a/server/services/socket.js b/server/services/socket.js
index 01ad343642..6522fbfca3 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -19,6 +19,7 @@ import { instanceEvents } from './instanceEvents.js';
import { reviewEvents } from './review.js';
import { loopEvents } from './loops.js';
import { imageGenEvents } from './imageGenEvents.js';
+import { importerEvents } from './importerEvents.js';
import { videoGenEvents } from './videoGen/events.js';
import { aiStatusEvents } from './aiStatusEvents.js';
import { wireProactiveTriggers } from './voice/proactiveTriggers.js';
@@ -561,11 +562,27 @@ export function initSocket(io) {
// Set up AI status event forwarding (broadcast to all clients)
setupAIStatusEventForwarding();
+ // Set up importer stage-progress forwarding (broadcast to all clients)
+ setupImporterEventForwarding();
+
// Wire proactive voice (CoS speaks first on high-severity errors, new tasks,
// and high-priority notifications — rate-limited per source).
setupProactiveSpeechForwarding();
}
+// Bridge importer analyze-phase stage progress onto Socket.IO so the Importer
+// page can render a live checklist while a (multi-minute, multi-pass) analyze
+// runs. Single-user trust model: broadcast to all clients; each frame carries
+// a `runId` so the client ignores stragglers from a prior run.
+let importerForwardingSetup = false;
+function setupImporterEventForwarding() {
+ if (importerForwardingSetup) return;
+ importerForwardingSetup = true;
+ importerEvents.on('progress', (data) => {
+ if (ioInstance) ioInstance.emit('importer:progress', data);
+ });
+}
+
let aiStatusForwardingSetup = false;
function setupAIStatusEventForwarding() {
if (aiStatusForwardingSetup) return;