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([issue-1335]): reuse manuscript AI-reformat to clean seeded excerpts at import time

[._.]/ Adam Eivy2e4b6f45d4ca
diff --git a/client/src/pages/Importer.jsx b/client/src/pages/Importer.jsx
index 861ebf0043..bd4672ce27 100644
--- a/client/src/pages/Importer.jsx
+++ b/client/src/pages/Importer.jsx
@@ -1,6 +1,6 @@
import { memo, useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate, useSearchParams } 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, Sparkles } from 'lucide-react';
import toast from '../components/ui/Toast';
import { useAsyncAction } from '../hooks/useAsyncAction';
import { useImporterProgress, stageStatusIcon } from '../hooks/useImporterProgress';
@@ -254,6 +254,9 @@ export default function Importer() {
const [arcAlreadyPersisted, setArcAlreadyPersisted] = useState(false);
// Destructive opt-in for existing series — wipes issues + overwrites arc.
const [replaceMode, setReplaceMode] = useState(false);
+ // Opt-in AI cleanup of seeded excerpts at commit time (issue #1335). Default
+ // off — it's one LLM call per issue, so a large import opts in explicitly.
+ const [cleanupFormatting, setCleanupFormatting] = 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.
@@ -372,6 +375,9 @@ export default function Importer() {
const [runCommit, committing] = useAsyncAction(async () => {
if (!preview) return null;
+ // Clear any prior (analyze) checklist so the commit-time reformat run
+ // repopulates it cleanly via the same `importer:progress` stream.
+ if (cleanupFormatting) resetAnalyzeStages();
// arcAlreadyPersisted retry: server kept arc/seasons/canon from the
// failed commit, so resending them would clobber any subsequent edits.
const base = {
@@ -383,6 +389,9 @@ export default function Importer() {
// seeds that script stage (ready) so the pipeline renders the user's
// script as-is instead of regenerating it.
contentType: intake.contentType,
+ // Opt-in: clean up each seeded excerpt with the AI reformat pass at
+ // commit time (best-effort server-side; falls back to verbatim).
+ cleanupFormatting,
};
const payload = arcAlreadyPersisted
? { ...base, canonSelections: { characters: [], places: [], objects: [] }, arc: null, seasons: [] }
@@ -517,6 +526,9 @@ export default function Importer() {
onStructureModeChange={handleStructureMode}
replaceMode={replaceMode}
setReplaceMode={setReplaceMode}
+ cleanupFormatting={cleanupFormatting}
+ setCleanupFormatting={setCleanupFormatting}
+ commitProgress={analyzeStages}
committing={committing}
onCommit={runCommit}
onBack={() => setPhase('intake')}
@@ -814,6 +826,8 @@ function ReviewPanel({
arcRoles, arcShapeIds,
structureMode, onStructureModeChange,
replaceMode, setReplaceMode,
+ cleanupFormatting, setCleanupFormatting,
+ commitProgress,
committing, onCommit, onBack,
issueSplitFailed, issueSplitError, onRetryIssues, retryingIssues,
}) {
@@ -861,6 +875,18 @@ function ReviewPanel({
</span>
</label>
)}
+ <label className="text-xs mt-2 flex items-center gap-2 cursor-pointer text-port-text-muted">
+ <input
+ type="checkbox"
+ checked={cleanupFormatting}
+ onChange={(e) => setCleanupFormatting(e.target.checked)}
+ className="accent-port-accent"
+ />
+ <Sparkles className="w-3 h-3" />
+ <span>
+ <strong>Clean up formatting with AI</strong> — repair paste/PDF artifacts (line wraps, split drop-caps, hyphen splits) in each excerpt before seeding. One AI pass per issue, so a large import adds time; wording is never changed and a failed pass keeps the original text.
+ </span>
+ </label>
</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
@@ -925,6 +951,28 @@ function ReviewPanel({
<IssuesReviewSection issues={issuesDraft} setIssues={setIssuesDraft} seasons={seasonsDraft} arcRoles={arcRoles} excerptLabel={excerptLabel} />
+ {committing && cleanupFormatting && Array.isArray(commitProgress) && commitProgress.length > 0 && (
+ <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" />
+ Cleaning up formatting — one AI pass per issue.
+ </p>
+ <ul className="space-y-1.5 mt-2">
+ {commitProgress.map((s) => {
+ const { Icon, className } = stageStatusIcon(s.status);
+ return (
+ <li key={s.id} className="flex items-center gap-2 text-sm">
+ <Icon className={className} />
+ <span className={s.status === 'running' ? 'text-port-text' : 'text-port-text-muted'}>
+ {s.label}
+ </span>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ )}
+
<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}
diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.js
index e84f7d01bc..f80487e8eb 100644
--- a/server/lib/creativeDirectorValidation.js
+++ b/server/lib/creativeDirectorValidation.js
@@ -288,6 +288,11 @@ export const importerCommitSchema = z.object({
// defaulting to prose-seed keeps older clients (which don't send it) on the
// prior behavior.
contentType: z.enum(IMPORTER_CONTENT_TYPES).optional(),
+ // Opt-in AI formatting cleanup: when true, each seeded excerpt is run through
+ // the manuscript-reformat pass at commit time so imported text arrives clean
+ // (issue #1335). One LLM call per issue + best-effort fallback, so it defaults
+ // off; older clients that don't send it keep the verbatim-seed behavior.
+ cleanupFormatting: z.boolean().optional().default(false),
// 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/services/importer.js b/server/services/importer.js
index 780cde4d19..571ef7de0e 100644
--- a/server/services/importer.js
+++ b/server/services/importer.js
@@ -31,6 +31,7 @@ import {
updateSeries,
} from './pipeline/series.js';
import { createIssue, deleteIssue, listIssues } from './pipeline/issues.js';
+import { reformatManuscriptText } from './pipeline/manuscriptFix.js';
import { sanitizeArc, sanitizeSeasonList, buildSeason, ARC_SHAPE_IDS, ARC_ROLES } from '../lib/storyArc.js';
import { COMIC_NUM, COMIC_HEADER_TAIL } from '../lib/comicScriptParser.js';
import { IMPORTER_CONTENT_TYPES, IMPORTER_PROSE_EXCERPT_MAX } from '../lib/validation.js';
@@ -106,6 +107,66 @@ const CONTENT_TYPE_SEED_STAGE = Object.freeze({
const DEFAULT_SEED_STAGE = 'prose';
const seedStageFor = (contentType) => CONTENT_TYPE_SEED_STAGE[contentType] || DEFAULT_SEED_STAGE;
+/**
+ * Best-effort AI cleanup of seeded excerpts at import time (issue #1335). The
+ * importer seeds each issue's verbatim `proseExcerpt` straight into its seed
+ * stage — which is exactly the PDF/paste-mangled text the editor's Reformat
+ * button repairs. Running it through the SAME `reformatManuscriptText` pass at
+ * import time lets manuscripts arrive already-clean instead of needing a
+ * per-section Reformat pass afterward.
+ *
+ * Opt-in (caller passes `cleanupFormatting`) because it's one LLM call per
+ * issue — a 20+ issue import would otherwise add minutes to commit. The seed
+ * stage id (prose / comicScript / teleplay — every `seedStageFor` value is a
+ * valid manuscript reformat type) selects the reformat's format label, so
+ * comic-script and screenplay imports route through too.
+ *
+ * Best-effort: a failed or integrity-guard-rejected reformat (the guard rejects
+ * any pass that altered wording) falls back to the verbatim excerpt so import
+ * never breaks. Emits importer progress frames (one checklist row per cleaned
+ * issue) so the blocking commit can show live status. Returns a NEW array;
+ * never mutates the caller's input.
+ */
+export async function reformatSeededExcerpts(issues, { contentType = null } = {}) {
+ const stageId = seedStageFor(contentType);
+ const targets = (Array.isArray(issues) ? issues : []).filter((p) => p?.proseExcerpt);
+ if (targets.length === 0) return issues;
+ const runId = randomUUID();
+ // Emitting is best-effort UI sugar — never let a listener throw abort the
+ // commit, so swallow + log at this boundary (mirrors analyze's emitProgress).
+ const emit = (frame) => {
+ try {
+ emitImporterProgress({ runId, ...frame });
+ } catch (err) {
+ console.error(`❌ importer reformat progress emit failed: ${err.message}`);
+ }
+ };
+ // Index cleaned text by the original proposal reference so the returned array
+ // can be rebuilt without mutating the input objects.
+ const cleaned = new Map();
+ emit({
+ type: 'start',
+ stages: targets.map((p, idx) => ({ id: `reformat-${idx}`, label: `Clean up formatting: ${p.title}` })),
+ });
+ for (let idx = 0; idx < targets.length; idx++) {
+ const proposal = targets[idx];
+ emit({ type: 'stage', id: `reformat-${idx}`, status: 'running' });
+ const result = await reformatManuscriptText(proposal.proseExcerpt, { stageId }).catch((err) => {
+ // Best-effort: keep the verbatim excerpt so import never breaks on an LLM
+ // error, empty output, or the integrity guard rejecting a word-altering
+ // reformat. The stage row shows 'error' (warning icon) to flag the fallback.
+ console.error(`❌ importer reformat fell back to verbatim for "${proposal.title}": ${err.message}`);
+ return null;
+ });
+ if (result?.text) cleaned.set(proposal, result.text);
+ // Map both clean outcomes to 'done' and the fallback to 'error' so the
+ // client's existing icon set renders them (no new status to teach the UI).
+ emit({ type: 'stage', id: `reformat-${idx}`, status: result ? 'done' : 'error' });
+ }
+ emit({ type: 'done' });
+ return issues.map((p) => (cleaned.has(p) ? { ...p, proseExcerpt: cleaned.get(p) } : p));
+}
+
const normName = (s) => String(s || '').trim().toLowerCase();
const isStr = (v) => typeof v === 'string';
@@ -941,6 +1002,10 @@ export async function commitImport({
// Content type drives which stage each issue's verbatim excerpt seeds (see
// the stage-seed block below). Absent → prose-seed (prior behavior).
contentType = null,
+ // Opt-in AI cleanup: run each seeded excerpt through the manuscript-reformat
+ // pass before seeding so imported prose/scripts arrive already-clean (issue
+ // #1335). Best-effort + per-issue (one LLM call each), so it defaults off.
+ cleanupFormatting = false,
// 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.
@@ -1125,6 +1190,17 @@ export async function commitImport({
}
}
+ // Optional AI cleanup of the seeded excerpts (issue #1335). Runs AFTER all
+ // the cheap fail-fast validation (so a bad payload never burns LLM calls) but
+ // BEFORE any destructive write (the wipe + universe/series writes below), so
+ // the heavy per-issue reformat happens while the on-disk state is untouched.
+ // Best-effort — `reformatSeededExcerpts` falls back to the verbatim excerpt
+ // per issue, so import never breaks. Returns a fresh array; the create loop
+ // below seeds from it.
+ const issuesToCreate = cleanupFormatting
+ ? await reformatSeededExcerpts(issuesWithPositions, { contentType })
+ : issuesWithPositions;
+
// Wipe BEFORE universe + series writes so any delete failure aborts the
// commit cleanly — universe canon + series arc are still in their
// pre-import state, and no new issues have been created yet. Without this
@@ -1290,7 +1366,7 @@ export async function commitImport({
// user-confirmed data; only the issue set is all-or-nothing from the
// commit's perspective.
try {
- for (const proposal of issuesWithPositions) {
+ for (const proposal of issuesToCreate) {
let seasonId = fallbackSeasonId;
if (proposal.seasonNumber != null) {
const matched = seasonByNumber.get(proposal.seasonNumber);
diff --git a/server/services/importer.test.js b/server/services/importer.test.js
index e9fd41e0ee..f9160cff13 100644
--- a/server/services/importer.test.js
+++ b/server/services/importer.test.js
@@ -806,6 +806,78 @@ describe('classifyImportContent', () => {
});
// ---------------------------------------------------------------------------
+// reformatSeededExcerpts (importer AI cleanup — issue #1335)
+// ---------------------------------------------------------------------------
+
+describe('reformatSeededExcerpts', () => {
+ // Collect importer progress frames the helper emits so we can assert the
+ // per-issue checklist is broadcast.
+ function captureFrames() {
+ const frames = [];
+ const onFrame = (f) => frames.push(f);
+ importerSvc.importerEvents.on('progress', onFrame);
+ return { frames, stop: () => importerSvc.importerEvents.off('progress', onFrame) };
+ }
+
+ it('returns the input unchanged (no LLM call) when no issue has a proseExcerpt', async () => {
+ const issues = [{ title: 'A', arcPosition: 1 }, { title: 'B', arcPosition: 2 }];
+ const out = await importerSvc.reformatSeededExcerpts(issues, { contentType: 'short-story' });
+ expect(out).toBe(issues); // same reference — nothing to do
+ expect(mockRunStagedLLM).not.toHaveBeenCalled();
+ });
+
+ it('replaces each excerpt with the cleaned text and emits per-issue progress frames', async () => {
+ // Cleaned output must preserve the word skeleton or the integrity guard
+ // rejects it — collapse the doubled space, nothing else.
+ mockRunStagedLLM.mockResolvedValue({ content: 'The vault loomed in the dark.', runId: 'r1' });
+ const { frames, stop } = captureFrames();
+ const issues = [{ title: 'Cold Iron', arcPosition: 1, proseExcerpt: 'The vault loomed in the\ndark.' }];
+ const out = await importerSvc.reformatSeededExcerpts(issues, { contentType: 'short-story' });
+ stop();
+
+ expect(out[0].proseExcerpt).toBe('The vault loomed in the dark.');
+ expect(out).not.toBe(issues); // fresh array, input untouched
+ expect(issues[0].proseExcerpt).toBe('The vault loomed in the\ndark.');
+ // start + (running, done) + done
+ expect(frames.find((f) => f.type === 'start')?.stages).toHaveLength(1);
+ expect(frames.some((f) => f.type === 'stage' && f.status === 'running')).toBe(true);
+ expect(frames.some((f) => f.type === 'stage' && f.status === 'done')).toBe(true);
+ expect(frames.some((f) => f.type === 'done')).toBe(true);
+ });
+
+ it('routes a comic-script import through the comicScript reformat format', async () => {
+ mockRunStagedLLM.mockResolvedValue({ content: 'PAGE 1 PANEL 1 Giant descends.', runId: 'r1' });
+ await importerSvc.reformatSeededExcerpts(
+ [{ title: 'P', arcPosition: 1, proseExcerpt: 'PAGE 1\nPANEL 1\nGiant descends.' }],
+ { contentType: 'comic-script' },
+ );
+ const call = mockRunStagedLLM.mock.calls.find((c) => c[0] === 'manuscript-reformat');
+ expect(call).toBeDefined();
+ expect(call[1].format).toBe('Comic script');
+ });
+
+ it('falls back to the verbatim excerpt when the reformat fails (best-effort, never throws)', async () => {
+ // Default reset mock resolves undefined → reformatManuscriptText throws
+ // "model returned no text" → helper swallows and keeps the original.
+ const { frames, stop } = captureFrames();
+ const issues = [{ title: 'Cold Iron', arcPosition: 1, proseExcerpt: 'The vault loomed.' }];
+ const out = await importerSvc.reformatSeededExcerpts(issues, { contentType: 'short-story' });
+ stop();
+ expect(out[0].proseExcerpt).toBe('The vault loomed.');
+ // A failed pass surfaces as 'error' in the checklist (warning icon).
+ expect(frames.some((f) => f.type === 'stage' && f.status === 'error')).toBe(true);
+ });
+
+ it('falls back when the integrity guard rejects a word-altering reformat', async () => {
+ mockRunStagedLLM.mockResolvedValue({ content: 'The castle loomed.', runId: 'r1' });
+ const out = await importerSvc.reformatSeededExcerpts(
+ [{ title: 'Cold Iron', arcPosition: 1, proseExcerpt: 'The vault loomed.' }],
+ { contentType: 'short-story' },
+ );
+ expect(out[0].proseExcerpt).toBe('The vault loomed.'); // guard tripped → verbatim kept
+ });
+});
+
// commitImport
// ---------------------------------------------------------------------------
@@ -894,6 +966,38 @@ describe('commitImport', () => {
expect(issue.seasonId).toBe(result.series.seasons[0].id);
});
+ it('cleanupFormatting:true seeds the AI-reformatted excerpt (issue #1335)', async () => {
+ mockRunStagedLLM.mockResolvedValue({ content: 'The vault loomed in the dark.', runId: 'r1' });
+ const { uni, ser } = await setupForCommit();
+ const result = await importerSvc.commitImport({
+ universeId: uni.id,
+ seriesId: ser.id,
+ contentType: 'short-story',
+ cleanupFormatting: true,
+ issues: [{ title: 'Cold Iron', arcPosition: 1, proseExcerpt: 'The vault loomed in the\ndark.' }],
+ });
+ const issue = await issuesSvc.getIssue(result.createdIssueIds[0]);
+ expect(issue.stages.prose.output).toBe('The vault loomed in the dark.');
+ expect(issue.stages.prose.status).toBe('ready');
+ expect(mockRunStagedLLM.mock.calls.some((c) => c[0] === 'manuscript-reformat')).toBe(true);
+ });
+
+ it('cleanupFormatting:true is best-effort — a failed reformat seeds the verbatim excerpt', async () => {
+ // Reset mock resolves undefined → reformat throws → fall back to verbatim;
+ // the commit still succeeds and creates the issue.
+ const { uni, ser } = await setupForCommit();
+ const result = await importerSvc.commitImport({
+ universeId: uni.id,
+ seriesId: ser.id,
+ contentType: 'short-story',
+ cleanupFormatting: true,
+ issues: [{ title: 'Cold Iron', arcPosition: 1, proseExcerpt: 'The vault loomed in the dark.' }],
+ });
+ expect(result.createdIssueIds).toHaveLength(1);
+ const issue = await issuesSvc.getIssue(result.createdIssueIds[0]);
+ expect(issue.stages.prose.output).toBe('The vault loomed in the dark.');
+ });
+
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