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

address review (codex): make AI reformat compute-only, exact-skeleton, edit-safe

[._.]/ Adam Eivy357563361d6c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7c34e7d71a..175b1efa8d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -6,7 +6,7 @@
- **"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`)
+- **"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** requires the letter/digit "skeleton" of the text to be **identical** before and after, rejecting (400, nothing saved) any result that changed, added, or dropped even a single letter or word — the model may only move whitespace and re-attach quotation-mark/punctuation glyphs. The endpoint is compute-only (returns the cleaned text without persisting); the client sends its live content and owns the save, so unsaved edits aren't reformatted-away and a mid-call edit discards the stale result instead of clobbering it. 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
diff --git a/client/src/pages/PipelineManuscriptEditor.jsx b/client/src/pages/PipelineManuscriptEditor.jsx
index 70b0cbba20..5b7ab853d3 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, reformatPipelineManuscriptSection, restorePipelineStageVersion,
+ savePipelineManuscriptSection, reformatPipelineManuscriptText, restorePipelineStageVersion,
analyzePipelineManuscriptCompleteness, startPipelineManuscriptCompleteness,
cancelPipelineManuscriptCompleteness, getPipelineManuscriptCompletenessStatus, getProviders,
pipelineManuscriptCompletenessSseUrl,
@@ -119,6 +119,13 @@ export default function PipelineManuscriptEditor() {
const patchSection = (issueId, fields) =>
setSections((prev) => prev.map((s) => (s.issueId === issueId ? { ...s, ...fields } : s)));
+ // Live mirror of `sections` so async handlers (e.g. the slow AI reformat) can
+ // read the CURRENT content at resolution time and detect a mid-call edit
+ // instead of clobbering it via a stale closure.
+ const liveSectionsRef = useRef([]);
+ liveSectionsRef.current = sections;
+ const liveContentFor = (issueId) => liveSectionsRef.current.find((s) => s.issueId === issueId)?.content ?? '';
+
useEffect(() => {
if (typeof window !== 'undefined') window.localStorage.setItem(VIEW_MODE_KEY, viewMode);
}, [viewMode]);
@@ -398,31 +405,39 @@ 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).
+ // AI reformat: send the section's CURRENT (possibly unsaved) text to the LLM
+ // (selected provider override) to repair paste artifacts the deterministic
+ // Format can't. The endpoint only computes — it returns the cleaned text and
+ // never persists, so we own the save: if the user edited the section during
+ // the (slow) call we discard the result rather than clobber the edit;
+ // otherwise we apply it and save through the normal path (snapshotted →
+ // revertible). The server guard rejects (400) any result that changed wording.
const reformatSection = async (section) => {
- const result = await reformatPipelineManuscriptSection(
+ const sent = section.content || '';
+ if (!sent.trim()) {
+ toast('There is no drafted text to reformat');
+ return;
+ }
+ const result = await reformatPipelineManuscriptText(
seriesId,
- section.issueId,
- { stageId: section.stageId, providerOverride, modelOverride },
+ { stageId: section.stageId, content: sent, providerOverride, modelOverride },
{ silent: true },
).catch((err) => {
toast.error(err.message || 'AI reformat failed');
return null;
});
- if (!result?.section) return;
- if (result.changed === false) {
- // Nothing was written server-side — don't flash a "saved" badge.
+ if (!result || typeof result.text !== 'string') return;
+ if (liveContentFor(section.issueId) !== sent) {
+ toast('Section changed while reformatting — discarded the AI result');
+ return;
+ }
+ if (!result.changed) {
toast('Already well-formatted — nothing to clean up');
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('Reformatted with AI');
+ setSectionContent(section.issueId, result.text);
+ const saved = await saveSectionContent(section, result.text);
+ if (saved) toast.success('Reformatted with AI');
};
const revertSection = async (section, runId) => {
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 16c94b4940..995c513df9 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -489,14 +489,15 @@ 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 }),
+// AI reformat of manuscript text — repairs paste artifacts (wrapping, drop-caps,
+// orphaned quotes) WITHOUT changing words. Compute-only: returns the cleaned
+// `{ text, changed, runId }` and does NOT persist — the caller sends its live
+// content and owns the save (so unsaved edits aren't clobbered). A 400 means the
+// model altered the wording (integrity guard) and the text is unchanged.
+export const reformatPipelineManuscriptText = (seriesId, { stageId, content, providerOverride, modelOverride } = {}, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/manuscript/reformat`, {
+ method: 'POST',
+ body: JSON.stringify({ stageId, content, providerOverride, modelOverride }),
...options,
});
diff --git a/data.reference/prompts/stages/manuscript-reformat.md b/data.reference/prompts/stages/manuscript-reformat.md
index 592ac295ea..878cdbd16b 100644
--- a/data.reference/prompts/stages/manuscript-reformat.md
+++ b/data.reference/prompts/stages/manuscript-reformat.md
@@ -43,7 +43,12 @@ Return the SAME text with ONLY its formatting repaired:
- 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.
+ moving whitespace around and re-attaching quotation marks. (The output is
+ rejected automatically if its sequence of letters and digits differs at all
+ from the input.)
+- Even if a WORD looks duplicated, leave it exactly as it is — do not delete it.
+ You may drop a redundant quotation mark or a stray space (those are
+ punctuation, not words), but never a letter or a word.
- 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.
diff --git a/server/routes/pipeline/manuscript.js b/server/routes/pipeline/manuscript.js
index 19e05aa4d8..061e5744ae 100644
--- a/server/routes/pipeline/manuscript.js
+++ b/server/routes/pipeline/manuscript.js
@@ -74,6 +74,7 @@ const manuscriptSectionSaveSchema = z.object({
const manuscriptReformatSchema = z.object({
stageId: z.enum(seriesSvc.MANUSCRIPT_TYPES),
+ content: z.string().max(issuesSvc.STAGE_OUTPUT_MAX),
...providerOverrideShape,
});
@@ -192,14 +193,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) => {
+// AI reformat of manuscript text — repair PDF/paste artifacts (wrapping, split
+// drop-caps, orphaned quotes) WITHOUT changing words. Compute-only: it returns
+// the cleaned `{ text, changed }` and does NOT persist — the client sends its
+// live (possibly unsaved) content and owns the save, so unsaved edits aren't
+// clobbered and a mid-call edit can skip the write. An integrity guard in the
+// service discards (400s) any result that altered the wording.
+router.post('/series/:id/manuscript/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 })
+ const { content, ...opts } = validateRequest(manuscriptReformatSchema, req.body ?? {});
+ const result = await manuscriptFix.reformatManuscriptStageText(content, opts)
.catch((err) => { throw mapServiceError(err); });
res.json(result);
}));
diff --git a/server/services/pipeline/manuscriptFix.js b/server/services/pipeline/manuscriptFix.js
index 3b376e0652..183361a6ca 100644
--- a/server/services/pipeline/manuscriptFix.js
+++ b/server/services/pipeline/manuscriptFix.js
@@ -354,34 +354,17 @@ const MANUSCRIPT_FORMAT_LABEL = { prose: 'Prose', comicScript: 'Comic script', t
// 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;
-};
-
-// The most letter/digit chars a pure reformat may delete IN TOTAL. Reflow and
-// quote-reattachment delete none (skeleton is identical); the only legitimate
-// deletion is a handful of artifact glyphs — a duplicated drop-cap, a stray
-// mark. Kept a small ABSOLUTE bound (not proportional): for a subsequence the
-// net length drop IS the exact total deleted, so this alone rejects a dropped
-// clause/sentence (≥ this many chars) without any unreliable run analysis.
-const MAX_TOTAL_DELETION = 8;
-
-// Reject any reformat that altered the actual wording. The output must be the
-// input skeleton with at most MAX_TOTAL_DELETION characters DELETED, those
-// deletions forming a subsequence (no substitutions, no additions). Anything
-// else — a rewritten word, an inserted sentence, a dropped clause — fails and is
-// discarded so a caller never persists silently-rewritten prose.
+// Reject any reformat that altered the actual wording. A pure reformat only
+// moves whitespace and quotation-mark/punctuation glyphs (all non-alphanumeric)
+// and de-hyphenates across a wrap (the hyphen is non-alphanumeric too) — so the
+// letter/digit skeleton is IDENTICAL before and after. We require an exact
+// skeleton match: no substitution, no insertion, and no deletion of even a
+// short word (e.g. dropping "not" from "do not go" would slip past any
+// deletion budget yet invert the meaning). A duplicated word the export left in
+// place stays in place — the deterministic Format button handles that dedup;
+// the AI pass is held to "change not one letter".
function assertWordsPreserved(before, after) {
- const a = wordSkeleton(before);
- const b = wordSkeleton(after);
- if (a === b) return;
- const shrink = a.length - b.length;
- if (shrink >= 0 && shrink <= MAX_TOTAL_DELETION && isSubsequence(b, a)) return;
+ if (wordSkeleton(before) === wordSkeleton(after)) 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,
@@ -420,23 +403,20 @@ export async function reformatManuscriptText(text, { stageId = 'prose', provider
}
/**
- * 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.
+ * Compute-only reformat of a stage's worth of text for the editor endpoint —
+ * validates the stage and runs `reformatManuscriptText`, returning the cleaned
+ * text WITHOUT persisting. The client owns the save (so it can fold in unsaved
+ * edits and skip the write if the section changed during the call); the
+ * importer calls `reformatManuscriptText` directly.
*/
-export async function reformatManuscriptSection(seriesId, { issueId, stageId, providerOverride, modelOverride } = {}) {
+export async function reformatManuscriptStageText(text, { 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 };
+ if (!(typeof text === 'string' && text.trim())) {
+ throw makeErr('There is no drafted text to reformat', ERR_VALIDATION);
}
- const saved = await saveManuscriptSection(seriesId, { issueId, stageId, output: text });
- return { ...saved, changed: true };
+ return reformatManuscriptText(text, { stageId, providerOverride, modelOverride });
}
/**
diff --git a/server/services/pipeline/manuscriptReformat.test.js b/server/services/pipeline/manuscriptReformat.test.js
index 2472e09260..625386bcf4 100644
--- a/server/services/pipeline/manuscriptReformat.test.js
+++ b/server/services/pipeline/manuscriptReformat.test.js
@@ -8,7 +8,7 @@ vi.mock('../../lib/stageRunner.js', () => ({
resolveStageContext: vi.fn(async () => ({ contextWindow: 100000 })),
}));
-import { reformatManuscriptText } from './manuscriptFix.js';
+import { reformatManuscriptText, reformatManuscriptStageText } from './manuscriptFix.js';
import { runStagedLLM } from '../../lib/stageRunner.js';
describe('reformatManuscriptText — integrity guard', () => {
@@ -40,36 +40,31 @@ describe('reformatManuscriptText — integrity guard', () => {
.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('removes a duplicated quotation MARK (punctuation) — skeleton unchanged', async () => {
+ runStagedLLM.mockResolvedValue({ content: 'He said "hello" to her.', runId: 'r1' });
+ const r = await reformatManuscriptText('He said ""hello" to her.', { stageId: 'prose' });
+ expect(r.text).toBe('He said "hello" to her.');
});
- 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' }))
+ it('rejects deleting a duplicated WORD fragment (exact skeleton required)', async () => {
+ // The export duplicated "I"; the guard forbids dropping the letter — the
+ // deterministic Format button owns that dedup, the AI pass changes no letter.
+ runStagedLLM.mockResolvedValue({ content: '"I need a partner."', runId: 'r1' });
+ await expect(reformatManuscriptText('"I\n"I need a partner."', { stageId: 'prose' }))
.rejects.toThrow(/changed the wording/i);
});
- it('rejects a dropped clause even on a long section (budget is a small absolute)', async () => {
- // A long doc must not buy a bigger deletion budget — dropping "the passage"
- // (10 skeleton chars > the 8-char total budget) is rejected regardless of size.
- const filler = `${'word '.repeat(2000)}`;
- const input = `Start of it. ${filler}and the passage ends here.`;
- const output = `Start of it. ${filler}and ends here.`;
- runStagedLLM.mockResolvedValue({ content: output, runId: 'r1' });
- await expect(reformatManuscriptText(input, { stageId: 'prose' }))
+ it('rejects dropping a short word that inverts meaning (do not go → do go)', async () => {
+ runStagedLLM.mockResolvedValue({ content: 'Please do go now.', runId: 'r1' });
+ await expect(reformatManuscriptText('Please do not\ngo now.', { stageId: 'prose' }))
.rejects.toThrow(/changed the wording/i);
});
- it('accepts a few scattered single-char artifact deletions', async () => {
- const input = 'A line.\n"I\n"I am here.\nAnother "A\n"A line follows.';
- const output = 'A line.\n"I am here.\nAnother "A line follows.';
- runStagedLLM.mockResolvedValue({ content: output, runId: 'r1' });
- const r = await reformatManuscriptText(input, { stageId: 'prose' });
- expect(r.text).toBe(output);
+ it('rejects a dropped clause', 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 () => {
@@ -100,3 +95,25 @@ describe('reformatManuscriptText — integrity guard', () => {
);
});
});
+
+describe('reformatManuscriptStageText — endpoint wrapper', () => {
+ beforeEach(() => runStagedLLM.mockReset());
+
+ it('rejects a non-manuscript stage', async () => {
+ await expect(reformatManuscriptStageText('hi', { stageId: 'idea' }))
+ .rejects.toThrow(/not an editable manuscript stage/i);
+ expect(runStagedLLM).not.toHaveBeenCalled();
+ });
+
+ it('rejects empty content without calling the model', async () => {
+ await expect(reformatManuscriptStageText(' ', { stageId: 'prose' }))
+ .rejects.toThrow(/no drafted text/i);
+ expect(runStagedLLM).not.toHaveBeenCalled();
+ });
+
+ it('returns the computed result for a valid stage (no persistence)', async () => {
+ runStagedLLM.mockResolvedValue({ content: 'The dawn cycle hums.', runId: 'r1' });
+ const r = await reformatManuscriptStageText('The dawn cycle\nhums.', { stageId: 'prose' });
+ expect(r).toEqual({ text: 'The dawn cycle hums.', runId: 'r1', changed: true });
+ });
+});