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

add an AI "Reformat" option for manuscript sections that can't be fixed by regex

[._.]/ Adam Eivy4064ccdc3c27
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2bbbdc6c22..7c34e7d71a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -6,6 +6,8 @@
- **"Format" button on each manuscript section cleans up pasted-PDF artifacts.** Text pasted out of a PDF export arrives hard-wrapped at the page margin (every visual line a real `\n`), with stylized drop-caps split onto their own line ("T\nhe dawn …"), words hyphenated across the wrap ("approxi-\nmating"), and closing quotes orphaned from the text they terminate (alone on a line, wrapped to the next line, or with a stray space before them) — so a paragraph reads as a column of ragged lines. A new **Format** button in each section's header (both Live and Review modes) normalizes the section: it rejoins drop-caps, repairs hyphen splits, strips trailing whitespace, and collapses runaway blank lines for every stage, and — for **prose** only — re-attaches orphaned closing quotes, drops a stray opening-quote fragment the export duplicated onto its own line (`"I\n"I need …` → `"I need …`, guarded so genuine back-to-back dialogue is untouched), and reflows the soft-wrapped lines back into paragraphs (comic/teleplay keep their structural line breaks). The reflow joins a line onto the previous one only when it begins with a lowercase letter — a real sentence/paragraph/heading never starts lowercase, so headings and attributions keep their own line and two paragraphs are never fused (a global line-width threshold is unsound on documents that mix already-joined and still-wrapped paragraphs). The prior text is snapshotted server-side, so History ▸ Revert undoes a format in one click. (`client/src/lib/manuscriptFormat.js`, `client/src/components/pipeline/manuscript/ManuscriptSectionFrame.jsx`, `client/src/pages/PipelineManuscriptEditor.jsx`)
+- **"Reformat (AI)" button on each manuscript section — fixes paste artifacts the deterministic Format can't.** PDF-pasted prose is sometimes genuinely scrambled (duplicated/misplaced quotes, ambiguous wraps before a capitalized word) in ways regex heuristics can't resolve. The new **Reformat (AI)** button sends the section to the AI provider selected in the sidebar with a strict "fix only whitespace, line breaks, drop-caps, and quotation-mark placement — do not change any words" prompt (stage `manuscript-reformat`), then persists the result (snapshotted, so History ▸ Revert undoes it). It is trustworthy by construction: a server-side **integrity guard** compares the letter/digit "skeleton" of the text before and after and rejects (400, nothing saved) any result that rewrote, added, or dropped words — the model is only ever allowed to move whitespace and re-attach quotes (plus delete a tiny budget of artifact characters, e.g. a duplicated drop-cap). The core `reformatManuscriptText()` is shared so the importer can reuse it. (`data.reference/prompts/stages/manuscript-reformat.md`, `server/services/pipeline/manuscriptFix.js`, `server/routes/pipeline/manuscript.js`, `client/src/services/apiPipeline.js`, `client/src/components/pipeline/manuscript/ManuscriptSectionFrame.jsx`, `client/src/pages/PipelineManuscriptEditor.jsx`)
+
## Changed
- **Deploying a LoRA checkpoint with no preview now auto-renders one.** A training run only writes preview thumbnails at the `sampleEvery` cadence, so a checkpoint whose step doesn't land on it — most often the final step (e.g. step 1188 with sampleEvery 300) — showed "no preview" in the picker, including on the deployed card. Promoting such a checkpoint now renders a thumbnail in the background from the just-deployed LoRA (the run's neutral trigger prompt + seed, on the LoRA's own 9B/4B base) and joins it to the checkpoint by step, so the deployed option gets a real image instead of a blank. The render is fire-and-forget — promote stays responsive and a render failure (OOM, restart) never fails the deploy, since the LoRA is already registered. The picker backstop-polls after promoting a preview-less checkpoint to surface the thumbnail once it's ready (~minutes on 9B), unmount-guarded. (`server/services/loraTraining/index.js` `ensureCheckpointPreview`, `client/src/components/loraTraining/CheckpointPicker.jsx`)
diff --git a/PLAN.md b/PLAN.md
index 5ee31de2e5..cd8dbc85d2 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -59,3 +59,5 @@ independently.
### Trigger-gated (waiting for a precondition)
- [ ] [ref-watch-phosphene-spaced-lora-id-decode-validate] **Harden trained-character/LoRA id handling for spaced filenames + percent-encoded path segments.** From `reference-watch` review of Phosphene (commit `ce031395`, 2026-06-12). Upstream's character-id validation regex was a hard gate that ran *before* the sidecar was read, so a LoRA whose trigger/filename contained a space (e.g. `Annie Phosphene_v2.safetensors`) was misclassified as style-only and vanished from the Characters tab; the fix widened the id class to allow spaces and made the route `unquote()`-then-validate (staying traversal-safe because an encoded `../` or `/` decodes to chars the class still rejects). PortOS's equivalent is `server/services/loras.js#assertSafeLoraFilename()` plus the trained-LoRA `character` classification it surfaces. Fix (if applicable): audit whether any PortOS LoRA/character id route 404s or misclassifies spaced filenames and whether percent-encoded id segments are decoded before validation; if so, widen the allowed id class to permit spaces and decode-then-validate in the route. **Decision needed:** confirm PortOS actually exposes id-addressed character/LoRA routes (not just filename-addressed ones) and reproduces the spaced-name misclassification before investing — it may already be covered by `assertSafeLoraFilename`'s filename-only model. Estimated scope: small.
+
+- [ ] [importer-ai-reformat-prose-excerpts] **Reuse the manuscript AI-reformat at import time to clean seeded prose excerpts.** The importer (`server/services/importer.js`, commit path ~line 1320) seeds `proposal.proseExcerpt` **verbatim** into `stages[seedStageFor(contentType)].output` — which is exactly the PDF-mangled text that needs the new `reformatManuscriptText()` (`server/services/pipeline/manuscriptFix.js`, already exported for this purpose). Wire it in so imported manuscripts arrive already-clean instead of needing a per-section Reformat pass afterward. **Design to settle first:** (a) opt-in — a "Clean up formatting with AI" checkbox in the import Review UI, default off — because reformatting is one LLM call per issue and a large import (20+ issues) would add minutes to commit; (b) best-effort — on reformat failure OR the integrity-guard 400, fall back to the verbatim excerpt so import never breaks; (c) emit importer progress events per reformatted issue; (d) gate to prose-like content types (route comic-script/screenplay through too, since `reformatManuscriptText` already takes a stageId). Estimated scope: medium.
diff --git a/client/src/components/pipeline/manuscript/AnnotatedManuscriptSection.jsx b/client/src/components/pipeline/manuscript/AnnotatedManuscriptSection.jsx
index 8e84523cfa..d7b18dd8d3 100644
--- a/client/src/components/pipeline/manuscript/AnnotatedManuscriptSection.jsx
+++ b/client/src/components/pipeline/manuscript/AnnotatedManuscriptSection.jsx
@@ -20,7 +20,7 @@ import { rowsFor } from './constants';
export default function AnnotatedManuscriptSection({
section, comments, spans, saveState, editing, onToggleEdit,
openCommentId, onOpenComment, onCloseComment,
- onContentChange, onBlurSave, onFormat, onRevert, registerRef, commentCardProps,
+ onContentChange, onBlurSave, onFormat, onReformat, onRevert, registerRef, commentCardProps,
}) {
const content = section.content || '';
const byId = useMemo(() => new Map(comments.map((c) => [c.id, c])), [comments]);
@@ -65,7 +65,7 @@ export default function AnnotatedManuscriptSection({
);
return (
- <ManuscriptSectionFrame section={section} saveState={saveState} onRevert={onRevert} onFormat={onFormat} headerExtra={editToggle} registerRef={registerRef}>
+ <ManuscriptSectionFrame section={section} saveState={saveState} onRevert={onRevert} onFormat={onFormat} onReformat={onReformat} headerExtra={editToggle} registerRef={registerRef}>
{editing ? (
<textarea
value={content}
diff --git a/client/src/components/pipeline/manuscript/ManuscriptLiveSection.jsx b/client/src/components/pipeline/manuscript/ManuscriptLiveSection.jsx
index 4ddb7eeb37..c0e36cb458 100644
--- a/client/src/components/pipeline/manuscript/ManuscriptLiveSection.jsx
+++ b/client/src/components/pipeline/manuscript/ManuscriptLiveSection.jsx
@@ -26,7 +26,7 @@ const EDITOR_TYPO = 'px-3 py-2 text-sm font-mono leading-relaxed whitespace-pre-
export default function ManuscriptLiveSection({
section, comments, spans, saveState, openCommentId, onOpenComment, onCloseComment,
- onContentChange, onBlurSave, onFormat, onRevert, registerRef, commentCardProps,
+ onContentChange, onBlurSave, onFormat, onReformat, onRevert, registerRef, commentCardProps,
}) {
const content = section.content || '';
const taRef = useRef(null);
@@ -72,7 +72,7 @@ export default function ManuscriptLiveSection({
useEscapeKey(openComment, onCloseComment);
return (
- <ManuscriptSectionFrame section={section} saveState={saveState} onRevert={onRevert} onFormat={onFormat} registerRef={registerRef}>
+ <ManuscriptSectionFrame section={section} saveState={saveState} onRevert={onRevert} onFormat={onFormat} onReformat={onReformat} registerRef={registerRef}>
{/* Pin chips: a touch-friendly, count-bearing way into each anchored note. */}
{anchoredComments.length > 0 || unlocatedCount > 0 ? (
<div className="flex flex-wrap items-center gap-1">
diff --git a/client/src/components/pipeline/manuscript/ManuscriptSectionFrame.jsx b/client/src/components/pipeline/manuscript/ManuscriptSectionFrame.jsx
index a744ada547..d816fa1833 100644
--- a/client/src/components/pipeline/manuscript/ManuscriptSectionFrame.jsx
+++ b/client/src/components/pipeline/manuscript/ManuscriptSectionFrame.jsx
@@ -7,7 +7,9 @@
*/
import { useState } from 'react';
-import { Loader2, History, RotateCcw, WandSparkles } from 'lucide-react';
+import {
+ Loader2, History, RotateCcw, WandSparkles, Sparkles,
+} from 'lucide-react';
import { timeAgo } from '../../../utils/formatters';
import { REFLOW_STAGES } from '../../../lib/manuscriptFormat';
import { STAGE_LABEL } from './constants';
@@ -18,10 +20,11 @@ function SaveBadge({ state }) {
return null;
}
-export default function ManuscriptSectionFrame({ section, saveState, onRevert, onFormat, headerExtra, registerRef, children }) {
+export default function ManuscriptSectionFrame({ section, saveState, onRevert, onFormat, onReformat, headerExtra, registerRef, children }) {
const [showVersions, setShowVersions] = useState(false);
const [revertingId, setRevertingId] = useState(null);
const [formatting, setFormatting] = useState(false);
+ const [reformatting, setReformatting] = useState(false);
const versions = section.versions || [];
const revert = async (runId) => {
@@ -39,6 +42,15 @@ export default function ManuscriptSectionFrame({ section, saveState, onRevert, o
}
};
+ const reformat = async () => {
+ setReformatting(true);
+ try {
+ await onReformat();
+ } finally {
+ setReformatting(false);
+ }
+ };
+
// Prose reflows into paragraphs; scripts only get safe artifact cleanup.
const formatTitle = REFLOW_STAGES.has(section.stageId)
? 'Clean up formatting — fix pasted-PDF artifacts (drop-caps, hyphen splits) and reflow hard-wrapped lines into paragraphs'
@@ -71,6 +83,19 @@ export default function ManuscriptSectionFrame({ section, saveState, onRevert, o
Format
</button>
) : null}
+ {onReformat ? (
+ <button
+ type="button"
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={reformat}
+ disabled={reformatting}
+ className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[11px] border border-port-border text-port-accent hover:text-white hover:border-port-accent/40 disabled:opacity-40"
+ title="Reformat with AI — fixes paste artifacts the plain Format can't (scrambled/duplicated quotes, ambiguous wraps) using the AI provider selected in the sidebar. Never changes your words; revertible via history."
+ >
+ {reformatting ? <Loader2 size={11} className="animate-spin" /> : <Sparkles size={11} />}
+ Reformat (AI)
+ </button>
+ ) : null}
{headerExtra}
<SaveBadge state={saveState} />
{versions.length > 0 ? (
diff --git a/client/src/pages/PipelineManuscriptEditor.jsx b/client/src/pages/PipelineManuscriptEditor.jsx
index 1003d84441..47fb1c555e 100644
--- a/client/src/pages/PipelineManuscriptEditor.jsx
+++ b/client/src/pages/PipelineManuscriptEditor.jsx
@@ -47,7 +47,7 @@ import ManuscriptImpactPreview from '../components/pipeline/manuscript/Manuscrip
import { MANUSCRIPT_TYPES, STAGE_LABEL } from '../components/pipeline/manuscript/constants';
import {
getPipelineSeries, updatePipelineSeries, getPipelineManuscript, getPipelineManuscriptReview,
- savePipelineManuscriptSection, restorePipelineStageVersion,
+ savePipelineManuscriptSection, reformatPipelineManuscriptSection, restorePipelineStageVersion,
analyzePipelineManuscriptCompleteness, startPipelineManuscriptCompleteness,
cancelPipelineManuscriptCompleteness, getPipelineManuscriptCompletenessStatus, getProviders,
pipelineManuscriptCompletenessSseUrl,
@@ -398,6 +398,28 @@ export default function PipelineManuscriptEditor() {
if (saved) toast.success('Formatting cleaned up');
};
+ // AI reformat: send the section to the LLM (selected provider override) to
+ // repair paste artifacts that the deterministic Format can't — handled
+ // server-side, snapshotted (revertible), and guarded so it can never change
+ // the wording (a 400 surfaces "changed the wording" and saves nothing).
+ const reformatSection = async (section) => {
+ const result = await reformatPipelineManuscriptSection(
+ seriesId,
+ section.issueId,
+ { stageId: section.stageId, providerOverride, modelOverride },
+ { silent: true },
+ ).catch((err) => {
+ toast.error(err.message || 'AI reformat failed');
+ return null;
+ });
+ if (!result?.section) return;
+ const content = result.section.content;
+ baselineRef.current.set(`${section.issueId}:${section.stageId}`, content);
+ patchSection(section.issueId, { content, versions: result.section.versions });
+ setSaveState((prev) => ({ ...prev, [section.issueId]: 'saved' }));
+ toast.success(result.changed === false ? 'Already well-formatted — nothing to clean up' : 'Reformatted with AI');
+ };
+
const revertSection = async (section, runId) => {
const result = await restorePipelineStageVersion(section.issueId, section.stageId, runId, { silent: true })
.catch((err) => { toast.error(err.message || 'Failed to revert'); return null; });
@@ -671,6 +693,7 @@ export default function PipelineManuscriptEditor() {
onContentChange: (content) => setSectionContent(section.issueId, content),
onBlurSave: () => saveSection(section),
onFormat: () => formatSection(section),
+ onReformat: () => reformatSection(section),
onRevert: (runId) => revertSection(section, runId),
registerRef: registerSectionRef(section.number),
commentCardProps,
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 749e32047c..16c94b4940 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -489,6 +489,17 @@ export const savePipelineManuscriptSection = (seriesId, issueId, { stageId, outp
...options,
});
+// AI reformat of one manuscript section — repairs paste artifacts (wrapping,
+// drop-caps, orphaned quotes) WITHOUT changing words, snapshotting the prior
+// text so it's revertible. Returns { section, changed }; a 400 means the model
+// altered the wording and nothing was saved (integrity guard).
+export const reformatPipelineManuscriptSection = (seriesId, issueId, { stageId, providerOverride, modelOverride } = {}, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/manuscript/sections/${encodeURIComponent(issueId)}/reformat`, {
+ method: 'POST',
+ body: JSON.stringify({ stageId, providerOverride, modelOverride }),
+ ...options,
+ });
+
// ---- Volume beat-sheet bulk generator ----
// Sequential idea-stage run across every issue in a volume. `mode` is
// 'skip-existing' (default) or 'regenerate-all'. Returns
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 61d16ea808..acd703ae94 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -14,6 +14,13 @@
"returnsJson": false,
"variables": []
},
+ "manuscript-reformat": {
+ "name": "Manuscript — Reformat (fix paste artifacts)",
+ "description": "Repair PDF/paste formatting artifacts in a manuscript section — hard-wrapped paragraphs, split drop-caps, hyphen-broken words, and orphaned/duplicated quotation marks — WITHOUT changing any words. Returns the reformatted text only; an integrity guard rejects the result if any letters/digits changed.",
+ "model": "default",
+ "returnsJson": false,
+ "variables": []
+ },
"writers-room-script": {
"name": "Writers Room — Adapt to Scene Script",
"description": "Adapt a Writers Room prose draft into a scene-by-scene screenplay-style breakdown with sluglines, action, dialogue, and per-scene visual prompts the image-gen pipeline can render.",
diff --git a/data.reference/prompts/stages/manuscript-reformat.md b/data.reference/prompts/stages/manuscript-reformat.md
new file mode 100644
index 0000000000..592ac295ea
--- /dev/null
+++ b/data.reference/prompts/stages/manuscript-reformat.md
@@ -0,0 +1,55 @@
+# Manuscript — Reformat (fix paste artifacts)
+
+You are repairing the FORMATTING of a manuscript that was pasted out of a PDF or
+similar export. The words are correct, but the line breaks and whitespace are
+mangled. Common damage:
+
+- Paragraphs hard-wrapped at the page margin — every visual line became a real
+ line break, so one paragraph is a column of short lines.
+- A stylized drop-cap split onto its own line (`T` then `he dawn …`), or the
+ word `I`/`A` left alone on a line by a wrap.
+- A word hyphenated across the wrap (`approxi-` then `mating`).
+- Quotation marks orphaned from the text they belong to: a `"` alone on a line,
+ wrapped to the start of the next line, duplicated, or with a stray space.
+
+## Format being reformatted
+
+{{format}}
+
+## Text
+
+Everything between the two `===MANUSCRIPT===` markers is the text to reformat.
+The markers are not part of the text.
+
+===MANUSCRIPT===
+{{body}}
+===MANUSCRIPT===
+
+## Task
+
+Return the SAME text with ONLY its formatting repaired:
+
+- Re-flow hard-wrapped lines back into whole paragraphs — one paragraph per
+ block, separated by a single blank line.
+- Rejoin a split drop-cap and de-hyphenate a word broken across a wrap.
+- Re-attach orphaned, wrapped, or duplicated quotation marks to the words they
+ belong to, and remove a stray space sitting before a closing quote.
+- Keep intentional structure on its own line: chapter and scene headings,
+ epigraphs, attributions ("— Author, …"), and — for a comic script or teleplay
+ — panel descriptions, scene headings, and character cue lines.
+- Collapse runs of blank lines to a single blank line.
+
+## Absolute constraints
+
+- DO NOT change, add, or remove any words. Preserve every letter and digit, all
+ spelling, names, and the author's punctuation and voice EXACTLY. You are only
+ moving whitespace around and re-attaching quotation marks.
+- DO NOT rewrite, rephrase, summarize, correct, translate, or "improve" anything.
+- If a passage looks garbled or a word seems missing, leave it exactly as it is —
+ do not guess or fill it in.
+- DO NOT add headings, labels, commentary, or code fences of your own.
+
+## Output contract
+
+Return ONLY the reformatted text as plain text — no preamble, no closing remark,
+no `===MANUSCRIPT===` markers, no code fence.
diff --git a/scripts/migrations/087-manuscript-reformat-stage.js b/scripts/migrations/087-manuscript-reformat-stage.js
new file mode 100644
index 0000000000..426831dc6b
--- /dev/null
+++ b/scripts/migrations/087-manuscript-reformat-stage.js
@@ -0,0 +1,75 @@
+/**
+ * Seed the `manuscript-reformat` stage into existing installs.
+ *
+ * Mirrors `041-editorial-analysis-stage.js`: copies the `.md` template from
+ * `data.reference/prompts/stages/` and merges the stage-config entry into
+ * `data/prompts/stage-config.json`. Boot runs migrations (server/index.js) but
+ * NOT `setup-data.js`, so an upgrade that pulls + `pm2 restart`s (rather than
+ * running `update.sh`) would otherwise leave the new manuscript "Reformat (AI)"
+ * stage unseeded and `buildPrompt('manuscript-reformat')` would throw "Stage
+ * not found" the first time a user clicks Reformat (AI).
+ */
+
+import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
+import { dirname, join } from 'path';
+
+const FILENAME = 'manuscript-reformat.md';
+const STAGE_KEY = 'manuscript-reformat';
+
+export default {
+ async up({ rootDir }) {
+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ await mkdir(stagesDir, { recursive: true });
+
+ const dataPath = join(stagesDir, FILENAME);
+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', FILENAME);
+
+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
+ if (exists) {
+ console.log(`📝 manuscript-reformat prompt: already present`);
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ manuscript-reformat: sample missing for ${FILENAME} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${FILENAME}`);
+ } catch (err) {
+ console.warn(`⚠️ manuscript-reformat: copy failed for ${FILENAME}: ${err.message}`);
+ }
+ }
+ }
+
+ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);
+ if (!sampleConfigExists) {
+ console.warn('⚠️ manuscript-reformat: data.reference stage-config.json missing — cannot resolve entry; skipping config write');
+ return;
+ }
+ try {
+ const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));
+ const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);
+ const installed = installedExists
+ ? JSON.parse(await readFile(installedConfigPath, 'utf8'))
+ : { stages: {} };
+ installed.stages = installed.stages || {};
+ if (installed.stages[STAGE_KEY]) {
+ console.log(`📝 manuscript-reformat stage-config: already present`);
+ return;
+ }
+ if (!sample?.stages?.[STAGE_KEY]) {
+ console.warn(`⚠️ manuscript-reformat: sample stage-config missing ${STAGE_KEY} — skipping`);
+ return;
+ }
+ installed.stages[STAGE_KEY] = sample.stages[STAGE_KEY];
+ await mkdir(dirname(installedConfigPath), { recursive: true });
+ await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');
+ const action = installedExists ? 'merged' : 'created';
+ console.log(`📝 manuscript-reformat stage-config (${action}): 1 added`);
+ } catch (err) {
+ console.warn(`⚠️ manuscript-reformat: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/server/routes/pipeline/manuscript.js b/server/routes/pipeline/manuscript.js
index 8846059c45..19e05aa4d8 100644
--- a/server/routes/pipeline/manuscript.js
+++ b/server/routes/pipeline/manuscript.js
@@ -72,6 +72,11 @@ const manuscriptSectionSaveSchema = z.object({
output: z.string().max(issuesSvc.STAGE_OUTPUT_MAX),
});
+const manuscriptReformatSchema = z.object({
+ stageId: z.enum(seriesSvc.MANUSCRIPT_TYPES),
+ ...providerOverrideShape,
+});
+
// Manuscript-completeness editor pass — categorized "finish the draft"
// suggestions read from the actual drafted script (not synopses). Advisory.
router.post('/series/:id/manuscript/completeness', asyncHandler(async (req, res) => {
@@ -187,4 +192,16 @@ router.put('/series/:id/manuscript/sections/:issueId', asyncHandler(async (req,
res.json(result);
}));
+// AI reformat of one manuscript section — repair PDF/paste artifacts (wrapping,
+// split drop-caps, orphaned quotes) WITHOUT changing words. Snapshots the prior
+// text so it's revertible via the stage-restore route; an integrity guard in
+// the service discards (400s) any result that altered the wording.
+router.post('/series/:id/manuscript/sections/:issueId/reformat', asyncHandler(async (req, res) => {
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const body = validateRequest(manuscriptReformatSchema, req.body ?? {});
+ const result = await manuscriptFix.reformatManuscriptSection(req.params.id, { issueId: req.params.issueId, ...body })
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
export default router;
diff --git a/server/services/pipeline/manuscriptFix.js b/server/services/pipeline/manuscriptFix.js
index 72e4a92eab..afc15af732 100644
--- a/server/services/pipeline/manuscriptFix.js
+++ b/server/services/pipeline/manuscriptFix.js
@@ -344,6 +344,94 @@ export async function saveManuscriptSection(seriesId, { issueId, stageId, output
return { section: sectionFrom(issue, stageId, stage) };
}
+// === AI Reformat (repair paste artifacts via the LLM) ===
+
+const MANUSCRIPT_FORMAT_LABEL = { prose: 'Prose', comicScript: 'Comic script', teleplay: 'Teleplay' };
+
+// Letters + digits only, lowercased — the "skeleton" a pure reformat preserves.
+// Reformatting only moves whitespace and re-attaches quotation marks, so the
+// letter/digit sequence is (near) identical before and after; comparing
+// skeletons is how we prove the model didn't rewrite the prose.
+const wordSkeleton = (s) => (typeof s === 'string' ? s.replace(/[^\p{L}\p{N}]+/gu, '').toLowerCase() : '');
+
+// Is `small` a subsequence of `big` (same order, gaps allowed)?
+const isSubsequence = (small, big) => {
+ let i = 0;
+ for (let j = 0; j < big.length && i < small.length; j += 1) {
+ if (small[i] === big[j]) i += 1;
+ }
+ return i === small.length;
+};
+
+// Reject any reformat that altered the actual wording. The output is allowed to
+// be the input with at most a tiny budget of characters DELETED (artifact
+// removal — e.g. a duplicated drop-cap), and those deletions must form a
+// subsequence (no substitutions, no additions). Anything else — a rewritten
+// word, an inserted sentence, a dropped paragraph — fails and is discarded.
+function assertWordsPreserved(before, after) {
+ const a = wordSkeleton(before);
+ const b = wordSkeleton(after);
+ if (a === b) return;
+ const budget = Math.max(8, Math.round(a.length * 0.004));
+ const shrink = a.length - b.length;
+ if (shrink >= 0 && shrink <= budget && isSubsequence(b, a)) return;
+ throw makeErr(
+ 'AI reformat changed the wording, so it was discarded and the text is unchanged. Try again or use the plain Format button.',
+ ERR_VALIDATION,
+ );
+}
+
+// Strip a stray ``` code fence or echoed ===MANUSCRIPT=== marker the model may
+// wrap the output in despite the prompt's contract.
+const stripReformatWrapper = (text) => String(text ?? '')
+ .replace(/^?\s*```[\w-]*\s*\n?/, '').replace(/\n?```\s*$/, '')
+ .replace(/^\s*===MANUSCRIPT===\s*\n?/, '').replace(/\n?\s*===MANUSCRIPT===\s*$/, '')
+ .trim();
+
+/**
+ * Reformat a block of manuscript text with the LLM — repair paste artifacts
+ * (wrapping, split drop-caps, hyphen splits, orphaned/duplicated quotes)
+ * WITHOUT changing words. Returns `{ text, runId, changed }`. Throws
+ * ERR_VALIDATION when the model altered the wording (integrity guard), so a
+ * caller never persists silently-rewritten prose. Shared by the section
+ * endpoint and the importer.
+ */
+export async function reformatManuscriptText(text, { stageId = 'prose', providerOverride, modelOverride } = {}) {
+ const body = typeof text === 'string' ? text : '';
+ if (!body.trim()) return { text: body, runId: null, changed: false };
+ const format = MANUSCRIPT_FORMAT_LABEL[stageId] || MANUSCRIPT_FORMAT_LABEL.prose;
+ const r = await runStagedLLM('manuscript-reformat', { format, body }, {
+ providerOverride,
+ modelOverride,
+ returnsJson: false,
+ source: 'pipeline-manuscript-reformat',
+ });
+ const cleaned = stripReformatWrapper(r?.content);
+ if (!cleaned) throw makeErr('The model returned no text — try again', ERR_VALIDATION);
+ assertWordsPreserved(body, cleaned);
+ return { text: cleaned, runId: r?.runId || null, changed: cleaned !== body };
+}
+
+/**
+ * Reformat one manuscript section in place and persist it (snapshotting the
+ * prior text into history so the change is revertible). No-op-safe: when the
+ * model returns the text unchanged, the section is returned without a write.
+ */
+export async function reformatManuscriptSection(seriesId, { issueId, stageId, providerOverride, modelOverride } = {}) {
+ if (!MANUSCRIPT_TYPES.includes(stageId)) {
+ throw makeErr(`Not an editable manuscript stage: ${stageId}`, ERR_VALIDATION);
+ }
+ const current = await loadStageText(issueId, stageId);
+ if (!current.trim()) throw makeErr('There is no drafted text to reformat', ERR_VALIDATION);
+ const { text, changed } = await reformatManuscriptText(current, { stageId, providerOverride, modelOverride });
+ if (!changed) {
+ const issue = await getIssue(issueId);
+ return { section: sectionFrom(issue, stageId, issue.stages?.[stageId]), changed: false };
+ }
+ const saved = await saveManuscriptSection(seriesId, { issueId, stageId, output: text });
+ return { ...saved, changed: true };
+}
+
/**
* Generate anchored fix edits for a comment and persist them on the comment
* (status stays `open` — the user still has to accept). When an edit's `find`
diff --git a/server/services/pipeline/manuscriptReformat.test.js b/server/services/pipeline/manuscriptReformat.test.js
new file mode 100644
index 0000000000..ec8bdb5ae7
--- /dev/null
+++ b/server/services/pipeline/manuscriptReformat.test.js
@@ -0,0 +1,83 @@
+import {
+ describe, it, expect, vi, beforeEach,
+} from 'vitest';
+
+// Mock the staged-LLM runner so the reformat core is tested without a real call.
+vi.mock('../../lib/stageRunner.js', () => ({
+ runStagedLLM: vi.fn(),
+ resolveStageContext: vi.fn(async () => ({ contextWindow: 100000 })),
+}));
+
+import { reformatManuscriptText } from './manuscriptFix.js';
+import { runStagedLLM } from '../../lib/stageRunner.js';
+
+describe('reformatManuscriptText — integrity guard', () => {
+ beforeEach(() => runStagedLLM.mockReset());
+
+ it('returns the cleaned text when only whitespace/line-breaks changed', async () => {
+ runStagedLLM.mockResolvedValue({ content: 'The dawn cycle hums to life.', runId: 'r1' });
+ const r = await reformatManuscriptText('The dawn cycle\nhums to life.', { stageId: 'prose' });
+ expect(r.text).toBe('The dawn cycle hums to life.');
+ expect(r.changed).toBe(true);
+ expect(r.runId).toBe('r1');
+ });
+
+ it('preserves a de-hyphenated word (skeleton ignores the hyphen)', async () => {
+ runStagedLLM.mockResolvedValue({ content: 'something approximating daylight.', runId: 'r1' });
+ const r = await reformatManuscriptText('something approxi-\nmating daylight.', { stageId: 'prose' });
+ expect(r.text).toBe('something approximating daylight.');
+ });
+
+ it('rejects a result that rewrote a word', async () => {
+ runStagedLLM.mockResolvedValue({ content: 'The dusk cycle hums to life.', runId: 'r1' });
+ await expect(reformatManuscriptText('The dawn cycle\nhums to life.', { stageId: 'prose' }))
+ .rejects.toThrow(/changed the wording/i);
+ });
+
+ it('rejects an inserted sentence', async () => {
+ runStagedLLM.mockResolvedValue({ content: 'The dawn cycle hums to life. Also it rained.', runId: 'r1' });
+ await expect(reformatManuscriptText('The dawn cycle\nhums to life.', { stageId: 'prose' }))
+ .rejects.toThrow(/changed the wording/i);
+ });
+
+ it('allows a tiny artifact deletion (a duplicated drop-cap fragment)', async () => {
+ runStagedLLM.mockResolvedValue({ content: '"I need a partner."', runId: 'r1' });
+ const r = await reformatManuscriptText('"I\n"I need a partner."', { stageId: 'prose' });
+ expect(r.text).toBe('"I need a partner."');
+ });
+
+ it('rejects a large deletion beyond the artifact budget', async () => {
+ const input = 'The pool hums softly. The nebula churns in slow motion outside the wide viewport.';
+ runStagedLLM.mockResolvedValue({ content: 'The pool hums softly.', runId: 'r1' });
+ await expect(reformatManuscriptText(input, { stageId: 'prose' }))
+ .rejects.toThrow(/changed the wording/i);
+ });
+
+ it('strips a stray code fence the model wrapped the output in', async () => {
+ runStagedLLM.mockResolvedValue({ content: '```\nThe dawn cycle hums.\n```', runId: 'r1' });
+ const r = await reformatManuscriptText('The dawn cycle\nhums.', { stageId: 'prose' });
+ expect(r.text).toBe('The dawn cycle hums.');
+ });
+
+ it('strips echoed ===MANUSCRIPT=== markers', async () => {
+ runStagedLLM.mockResolvedValue({ content: '===MANUSCRIPT===\nThe dawn cycle hums.\n===MANUSCRIPT===', runId: 'r1' });
+ const r = await reformatManuscriptText('The dawn cycle\nhums.', { stageId: 'prose' });
+ expect(r.text).toBe('The dawn cycle hums.');
+ });
+
+ it('no-ops on empty/whitespace input without calling the model', async () => {
+ const r = await reformatManuscriptText(' ', { stageId: 'prose' });
+ expect(r.changed).toBe(false);
+ expect(runStagedLLM).not.toHaveBeenCalled();
+ });
+
+ it('passes the stage format label and source through to the runner', async () => {
+ runStagedLLM.mockResolvedValue({ content: 'Panel 1. A wide shot.', runId: 'r1' });
+ await reformatManuscriptText('Panel 1. A wide shot.', { stageId: 'comicScript', providerOverride: 'p1', modelOverride: 'm1' });
+ expect(runStagedLLM).toHaveBeenCalledWith(
+ 'manuscript-reformat',
+ expect.objectContaining({ format: 'Comic script', body: 'Panel 1. A wide shot.' }),
+ expect.objectContaining({ providerOverride: 'p1', modelOverride: 'm1', returnsJson: false }),
+ );
+ });
+});