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 adversarial cuts check + mechanical applier for prose tightening

[._.]/ Adam Eivy667d3098f740
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3983ff9c3f..c3b812ef53 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -13,6 +13,7 @@
- **[issue-2165] Editorial review now catches recognizable "AI slop" writing tells automatically.** Four new deterministic editorial checks join the existing 68: a tiered banned-word scan (hard-bans like "delve"/"myriad"/"utilize"; suspicious words like "robust"/"seamless" only flagged when 3+ cluster in one paragraph), fiction-specific AI-tell idioms ("a sense of dread", "couldn't help but", "eyes widened", "a wave of relief washed over him"), rhetorical structural tics ("not just X, but Y", runs of "did not [verb]", punchy three-sentence-in-a-row bursts like "Fast. Precise. Deadly."), and structural burstiness (em-dash overuse, essay-style transition-word openers, mechanically uniform paragraph lengths). Each surfaces as an editorial finding with the exact offending quote, same as the existing prose checks — configurable thresholds and house-style allowlists included.
- **[issue-2166] Editorial review now flags an issue whose narrative voice statistically drifts from the rest of the series.** A new deterministic `style.voice-drift` check measures each issue's prose fingerprint — sentence-length rhythm (mean, spread, variation), fragment and long-sentence rates, paragraph shape, dialogue ratio, em-dash rate, abstract-noun and simile density, and how often sentences open the same way — then compares every issue against the series average and flags the outliers (e.g. "Issue 7's sentence-length variation is 0.18 vs the series 0.41 — prose has gone metronomic"). It's the cheap, deterministic complement to the existing LLM voice-consistency check: no model cost, and it names the exact issue and metric that drifted. You can tune the sensitivity (σ threshold), and optionally declare vocabulary "wells" — register categories like `trade: forge, anvil; body: pulse, sinew` — so it also flags an issue that drops a register the series leans on. It stays off until at least 4 issues are drafted (with fewer, the statistics are too small to distinguish real drift from a normal series).
+- **[issue-2168] A new "adversarial cuts" editorial check and mechanical applier tightens prose by identifying what a ruthless editor would cut.** The `prose.adversarial-cuts` check asks an LLM editor persona to cut 8–12% of the text as 10–20 passages, classifying each cut by type: FAT (purple prose), REDUNDANT (repeated information), OVER-EXPLAIN (spelling out what's clear), GENERIC (stock phrases), TELL (emotion-telling after showing), or STRUCTURAL (scenes that don't advance the story). Each cut lands as a manuscriptReview finding with the exact verbatim quote. The Manuscript Editor gains an "Apply safe cuts" action that batch-removes OVER-EXPLAIN and REDUNDANT cuts mechanically — exact string match with whitespace-normalized fallback, refusing ambiguous or too-short quotes — through the same snapshotted stage-write path fixes use (full undo via version history). The check also reports `fat_percentage`, `tightest_passage` (protected), and `loosest_passage` for a quick health read.
## Human Activity Tracking
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 3551cf6ed0..90e2b672f2 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -574,6 +574,25 @@ export const reformatPipelineManuscriptText = (seriesId, { stageId, content, pro
...options,
});
+// ---- Adversarial cuts (#2168) ----
+// Preview cuts — dry-run that returns before/after diffs without applying.
+// Returns { preview: [{ issueNumber, before, after, applied, refused, refusedDetails }], totalApplied, totalRefused }.
+export const previewPipelineManuscriptCuts = (seriesId, { commentIds, allowTypes, safeTypesOnly } = {}, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/manuscript/cuts/preview`, {
+ method: 'POST',
+ body: JSON.stringify({ commentIds, allowTypes, safeTypesOnly }),
+ ...options,
+ });
+
+// Apply cuts — writes through the serialized stage-write path with snapshots.
+// Returns { applied, refused, sections, refusedDetails, acceptedCount }.
+export const applyPipelineManuscriptCuts = (seriesId, { commentIds, allowTypes, safeTypesOnly } = {}, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/manuscript/cuts/apply`, {
+ method: 'POST',
+ body: JSON.stringify({ commentIds, allowTypes, safeTypesOnly }),
+ ...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 9f2e5f0107..f361c26600 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -771,6 +771,13 @@
"model": "default",
"returnsJson": true,
"variables": []
+ },
+ "pipeline-editorial-adversarial-cuts": {
+ "name": "Pipeline — Editorial Check: Adversarial cuts (prose tightening)",
+ "description": "Editorial check (#2168): a ruthless literary editor persona that cuts 8–12% of the text as 10–20 passages, each an exact verbatim quote classified by cut type (FAT, REDUNDANT, OVER-EXPLAIN, GENERIC, TELL, STRUCTURAL). Also returns fat_percentage, tightest_passage (protected), loosest_passage, and one_sentence_verdict. Safe cut types (OVER-EXPLAIN, REDUNDANT) can be batch-applied mechanically. Returns issue-anchored findings with cutType.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
}
}
}
diff --git a/data.reference/prompts/stages/pipeline-editorial-adversarial-cuts.md b/data.reference/prompts/stages/pipeline-editorial-adversarial-cuts.md
new file mode 100644
index 0000000000..8b3705f515
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-adversarial-cuts.md
@@ -0,0 +1,84 @@
+# Pipeline — Editorial Check: Adversarial Cuts (prose tightening)
+
+You are a ruthless literary editor doing one job: **cutting fat**. If a sentence
+isn't earning its place, it goes. Quote exactly — never paraphrase.
+
+Your goal: identify {{cutTargetPercent}}% of the manuscript that can be cut
+without losing story, character, or meaning. Aim for {{minCuts}}–{{maxCuts}} passages.
+
+## Cut types (classify each cut)
+
+- **FAT** — Purple prose, overwrought description, unnecessary flourishes that
+ don't advance story or character. Decorative language with no payoff.
+- **REDUNDANT** — The same information delivered twice (restated beats, repeated
+ emotional reactions, dialogue that echoes narration).
+- **OVER-EXPLAIN** — Spelling out what's already clear from context, action, or
+ dialogue. The reader got it; the author kept explaining.
+- **GENERIC** — Stock phrases, placeholder descriptions, anything that could
+ appear in any story ("she took a deep breath," "his eyes met hers"). No
+ specificity, no earned detail.
+- **TELL** — Emotional telling after showing, author intrusion explaining what
+ a character feels instead of letting action/dialogue carry it.
+- **STRUCTURAL** — Entire scenes or passages that don't advance plot, character,
+ or theme. Often backstory dumps or transitional filler.
+
+## What NOT to cut
+
+Do NOT cut:
+
+- Necessary plot beats or character-defining moments
+- Dialogue that reveals character or advances conflict
+- Setting details that ground the scene or establish atmosphere purposefully
+- Foreshadowing or thematic setup that pays off later
+- Voice-defining prose that establishes the narrator's personality
+
+## Manuscript
+
+The manuscript is stitched from the drafted issues. Each section begins with a
+header like `# Issue 3 — Title (prose)`; use the issue number in that header to
+attribute each finding.
+
+```
+{{manuscript}}
+```
+
+## Task
+
+Cut {{cutTargetPercent}}% of this manuscript. For each cut:
+
+1. Quote the EXACT passage verbatim (minimum 10 words, maximum 400 characters)
+2. Classify it as one of: FAT, REDUNDANT, OVER-EXPLAIN, GENERIC, TELL, STRUCTURAL
+3. Give a one-line reason why it should go
+
+Also identify:
+- The `fat_percentage`: your estimate of how much of this manuscript is cuttable fat
+- The `tightest_passage`: one passage that is so well-crafted it should NEVER be cut
+- The `loosest_passage`: the single worst offender — if you could only cut one thing
+- The `one_sentence_verdict`: your overall assessment of the prose's tightness
+
+If the manuscript is already tight with little to cut, return fewer findings and
+a low `fat_percentage`. Do not invent cuts to hit a quota.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence:
+
+```json
+{
+ "fat_percentage": 8,
+ "tightest_passage": "exact quote of the best-written passage",
+ "loosest_passage": "exact quote of the worst offender",
+ "one_sentence_verdict": "Overall assessment of prose tightness",
+ "findings": [
+ {
+ "severity": "high|medium|low",
+ "issueNumber": 3,
+ "location": "Chapter 3, second paragraph",
+ "problem": "1-2 sentences explaining why this should be cut",
+ "suggestion": "Cut this passage entirely",
+ "anchorQuote": "exact verbatim quote from the manuscript (10-400 chars)",
+ "cutType": "OVER-EXPLAIN|REDUNDANT|FAT|GENERIC|TELL|STRUCTURAL"
+ }
+ ]
+}
+```
diff --git a/server/lib/editorial/checkInfra.js b/server/lib/editorial/checkInfra.js
index 8366804480..76f1c6f71f 100644
--- a/server/lib/editorial/checkInfra.js
+++ b/server/lib/editorial/checkInfra.js
@@ -378,6 +378,28 @@ export const MIRROR_DESCRIPTION_STAGE = 'pipeline-editorial-mirror-description';
export const DIALOGUE_PLEASANTRIES_STAGE = 'pipeline-editorial-dialogue-pleasantries';
export const KILL_YOUR_DARLINGS_STAGE = 'pipeline-editorial-kill-your-darlings';
+// Stage name for the adversarial-cuts prose-tightening LLM check (#2168). Ships
+// in data.reference/prompts/stages/ + stage-config.json (fresh installs via
+// setup-data.js); new file so no migration needed. Asks a ruthless editor
+// persona to cut 8–12% of the text, classifying each cut (FAT, REDUNDANT,
+// OVER-EXPLAIN, GENERIC, TELL, STRUCTURAL). Safe types (OVER-EXPLAIN, REDUNDANT)
+// can be batch-applied mechanically.
+export const ADVERSARIAL_CUTS_STAGE = 'pipeline-editorial-adversarial-cuts';
+
+// The six cut types the adversarial-cuts check returns, ordered by safe-to-auto-
+// apply (the first two are the "safe majority" per the design doc). The applier
+// defaults to OVER-EXPLAIN + REDUNDANT only; other types require manual review.
+export const CUT_TYPES = Object.freeze([
+ 'OVER-EXPLAIN',
+ 'REDUNDANT',
+ 'FAT',
+ 'GENERIC',
+ 'TELL',
+ 'STRUCTURAL',
+]);
+// The subset that can be auto-applied without manual review.
+export const SAFE_CUT_TYPES = Object.freeze(['OVER-EXPLAIN', 'REDUNDANT']);
+
// Stage names for the two scene-grounding LLM checks (#1309): sensory balance
// (all-visual / sensory-bare scenes) and white-room (ungrounded, setting-less
// scenes). Each prompt ships in data.reference/prompts/stages/ + stage-config.json
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index 6fe438a1f0..aeed3c264d 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -36,6 +36,7 @@
// the public API exactly). Promoted-private helpers used by ./checks/*.js stay
// internal to ./checkInfra.js and are imported from there directly.
export {
+ ADVERSARIAL_CUTS_STAGE,
APPEARANCE_CONTINUITY_STAGE,
ARC_REGRESSION_STAGE,
ARC_TRANSITIONS_STAGE,
@@ -50,6 +51,7 @@ export {
COMIC_PROSE_SYNC_STAGE,
CUSTOM_CHECK_MAX_FINDINGS_DEFAULT,
CUSTOM_CHECK_RUN_SOURCE,
+ CUT_TYPES,
DEAD_METAPHOR_STAGE,
DIALOGUE_PLEASANTRIES_STAGE,
EDITORIAL_PRIOR_DIGEST_BODY_CHARS,
@@ -79,6 +81,7 @@ export {
PLOT_STRUCTURE_STAGE,
PROSE_SYNC_PROSE_CHAR_CAP,
REACTION_PROPORTIONALITY_STAGE,
+ SAFE_CUT_TYPES,
SECONDARY_ARC_STAGE,
SENSORY_BALANCE_STAGE,
STYLE_CONFORMANCE_STAGE,
@@ -219,6 +222,7 @@ const CHECK_ORDER = Object.freeze([
'style.voice-consistency',
'style.voice-drift',
'prose.kill-your-darlings',
+ 'prose.adversarial-cuts',
'prose.italic-thoughts',
'endings.cliffhanger',
'endings.pov-switch',
diff --git a/server/lib/editorial/checks/proseStyle.js b/server/lib/editorial/checks/proseStyle.js
index 3262d237e2..ba648dfd63 100644
--- a/server/lib/editorial/checks/proseStyle.js
+++ b/server/lib/editorial/checks/proseStyle.js
@@ -1,6 +1,8 @@
// Editorial checks — proseStyle group. Extracted from checkRegistry.js (#1829).
// Each entry is a declarative check; see ../README.md and ../checkInfra.js.
import {
+ ADVERSARIAL_CUTS_STAGE,
+ CUT_TYPES,
DEAD_METAPHOR_STAGE,
EDITORIAL_PROMPT_OVERHEAD_TOKENS,
INFO_DUMPING_STAGE,
@@ -1130,6 +1132,138 @@ export const proseStyleChecks = [
buildVars: (manuscript) => ({ manuscript }),
}),
},
+ {
+ id: 'prose.adversarial-cuts',
+ sources: ['manuscript'],
+ label: 'Adversarial cuts (prose tightening)',
+ description:
+ 'Asks a ruthless literary editor persona to cut 8–12% of the text, classifying each cut as FAT, REDUNDANT, OVER-EXPLAIN, GENERIC, TELL, or STRUCTURAL. Returns fat_percentage, tightest_passage (protected), loosest_passage, and typed cut findings. Safe types (OVER-EXPLAIN, REDUNDANT) can be batch-applied mechanically via the Manuscript Editor.',
+ scope: 'issue',
+ kind: 'llm',
+ category: 'prose',
+ severityDefault: 'medium',
+ defaultEnabled: true,
+ needsManuscript: true,
+ configSchema: z.object({
+ // Target percentage of text to cut (the prompt asks for this much).
+ cutTargetPercent: z.number().int().min(5).max(20).default(10),
+ // Minimum cuts per run.
+ minCuts: z.number().int().min(5).max(30).default(10),
+ // Maximum cuts per run.
+ maxCuts: z.number().int().min(10).max(50).default(20),
+ // Cap findings so a long manuscript can not flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(20),
+ }),
+ configFields: [
+ {
+ key: 'cutTargetPercent',
+ label: 'Cut target (%)',
+ type: 'number',
+ min: 5,
+ max: 20,
+ step: 1,
+ help: 'Target percentage of the manuscript to cut. 8–12% is typical for tightening passes.',
+ },
+ {
+ key: 'minCuts',
+ label: 'Min cuts',
+ type: 'number',
+ min: 5,
+ max: 30,
+ step: 1,
+ help: 'Minimum number of cut passages to identify.',
+ },
+ {
+ key: 'maxCuts',
+ label: 'Max cuts',
+ type: 'number',
+ min: 10,
+ max: 50,
+ step: 1,
+ help: 'Maximum number of cut passages to identify.',
+ },
+ {
+ key: 'maxFindings',
+ label: 'Max findings per run',
+ type: 'number',
+ min: 1,
+ max: 50,
+ step: 1,
+ help: 'Cap findings so a long manuscript can not flood the review.',
+ },
+ ],
+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
+ run: async (ctx) => {
+ const cfg = ctx.config || {};
+ const cutTargetPercent = cfg.cutTargetPercent ?? 10;
+ const minCuts = cfg.minCuts ?? 10;
+ const maxCuts = cfg.maxCuts ?? 20;
+ const max = cfg.maxFindings ?? 20;
+ const chunks = await ctx.planManuscriptChunks(ADVERSARIAL_CUTS_STAGE, {
+ overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS,
+ });
+ // Run the check with the cut parameters injected into the prompt.
+ const runChunk = async (manuscript) => {
+ const vars = { manuscript, cutTargetPercent, minCuts, maxCuts };
+ const { content } = await ctx.callStagedLLM(ADVERSARIAL_CUTS_STAGE, vars, {
+ returnsJson: true,
+ source: ADVERSARIAL_CUTS_STAGE,
+ });
+ return content;
+ };
+ // Merge findings across chunks, deduping by anchorQuote.
+ const seenQuotes = new Set();
+ const findings = [];
+ let fatPercentage = null;
+ let tightestPassage = null;
+ let loosestPassage = null;
+ let verdict = null;
+ for (const chunk of chunks?.sections || [chunks]) {
+ const manuscript = typeof chunk === 'string' ? chunk : chunk?.sections?.[0]?.text || ctx.manuscript;
+ const result = await runChunk(manuscript);
+ // Capture meta fields from the first chunk.
+ if (fatPercentage == null && typeof result?.fat_percentage === 'number') {
+ fatPercentage = result.fat_percentage;
+ }
+ if (!tightestPassage && typeof result?.tightest_passage === 'string') {
+ tightestPassage = result.tightest_passage;
+ }
+ if (!loosestPassage && typeof result?.loosest_passage === 'string') {
+ loosestPassage = result.loosest_passage;
+ }
+ if (!verdict && typeof result?.one_sentence_verdict === 'string') {
+ verdict = result.one_sentence_verdict;
+ }
+ const raw = Array.isArray(result?.findings) ? result.findings : [];
+ for (const f of raw) {
+ if (findings.length >= max) break;
+ const anchorQuote = typeof f?.anchorQuote === 'string' ? f.anchorQuote : '';
+ if (!anchorQuote || anchorQuote.length < 10) continue;
+ const key = anchorQuote.toLowerCase().trim();
+ if (seenQuotes.has(key)) continue;
+ seenQuotes.add(key);
+ const cutType = CUT_TYPES.includes(f?.cutType) ? f.cutType : null;
+ findings.push({
+ severity: ['high', 'medium', 'low'].includes(f?.severity) ? f.severity : ctx.severityDefault,
+ category: 'prose',
+ location: typeof f?.location === 'string' ? f.location : '',
+ problem: typeof f?.problem === 'string' ? f.problem : '',
+ suggestion: typeof f?.suggestion === 'string' ? f.suggestion : 'Cut this passage entirely.',
+ anchorQuote,
+ issueNumber: Number.isInteger(f?.issueNumber) ? f.issueNumber : null,
+ // Carry the cut type as a subtype for filtering in the applier.
+ subtype: cutType,
+ });
+ }
+ if (findings.length >= max) break;
+ }
+ // Log summary for debugging.
+ if (fatPercentage != null) {
+ console.log(`✂️ adversarial-cuts: fat=${fatPercentage}% tightest="${(tightestPassage || '').slice(0, 40)}..." verdict="${verdict || ''}"`);
+ }
+ return findings;
+ },
+ },
{
id: 'prose.italic-thoughts',
sources: ['manuscript'],
diff --git a/server/routes/pipeline/manuscript.js b/server/routes/pipeline/manuscript.js
index 29e8f7fb4d..ed2c4daa6e 100644
--- a/server/routes/pipeline/manuscript.js
+++ b/server/routes/pipeline/manuscript.js
@@ -16,6 +16,7 @@ import * as issuesSvc from '../../services/pipeline/issues.js';
import * as arcPlanner from '../../services/pipeline/arcPlanner.js';
import * as manuscriptReview from '../../services/pipeline/manuscriptReview.js';
import * as manuscriptFix from '../../services/pipeline/manuscriptFix.js';
+import * as applyCuts from '../../services/pipeline/applyCuts.js';
import * as completenessRunner from '../../services/pipeline/manuscriptCompletenessRunner.js';
import { getReviewWithStaleness } from '../../services/pipeline/editorial/checkRunner.js';
import { recordTrendSnapshot } from '../../services/pipeline/editorialScore.js';
@@ -86,6 +87,16 @@ const manuscriptReformatSchema = z.object({
...providerOverrideShape,
});
+// Adversarial cuts — preview and apply (#2168).
+const manuscriptCutsSchema = z.object({
+ // Which comment ids to apply cuts from. If empty, applies all eligible open cuts.
+ commentIds: z.array(z.string().min(1).max(120)).max(100).optional(),
+ // Filter by cut types. Defaults to SAFE_CUT_TYPES (OVER-EXPLAIN, REDUNDANT).
+ allowTypes: z.array(z.enum(applyCuts.CUT_TYPES)).max(6).optional(),
+ // Whether to only allow safe cut types.
+ safeTypesOnly: z.boolean().optional(),
+});
+
// 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) => {
@@ -246,4 +257,65 @@ router.post('/series/:id/manuscript/reformat', asyncHandler(async (req, res) =>
res.json(result);
}));
+// ---------------------------------------------------------------------------
+// Adversarial cuts (#2168) — batch application of cut-type findings.
+// ---------------------------------------------------------------------------
+
+// Preview cuts — dry-run that returns before/after diffs without applying.
+router.post('/series/:id/manuscript/cuts/preview', asyncHandler(async (req, res) => {
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const body = validateRequest(manuscriptCutsSchema, req.body ?? {});
+ const review = await manuscriptReview.getReview(req.params.id);
+ // Filter to open cut-type comments.
+ let cuts = applyCuts.filterCutComments(review.comments);
+ // If specific comment ids requested, filter to those.
+ if (Array.isArray(body.commentIds) && body.commentIds.length > 0) {
+ const wanted = new Set(body.commentIds);
+ cuts = cuts.filter((c) => wanted.has(c.id));
+ }
+ const opts = {
+ safeTypesOnly: body.safeTypesOnly !== false,
+ allowTypes: Array.isArray(body.allowTypes) ? body.allowTypes : applyCuts.SAFE_CUT_TYPES,
+ };
+ const result = await applyCuts.previewCuts(req.params.id, cuts, opts)
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
+// Apply cuts — writes through the serialized stage-write path with snapshots.
+router.post('/series/:id/manuscript/cuts/apply', asyncHandler(async (req, res) => {
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const body = validateRequest(manuscriptCutsSchema, req.body ?? {});
+ const review = await manuscriptReview.getReview(req.params.id);
+ // Filter to open cut-type comments.
+ let cuts = applyCuts.filterCutComments(review.comments);
+ // If specific comment ids requested, filter to those.
+ if (Array.isArray(body.commentIds) && body.commentIds.length > 0) {
+ const wanted = new Set(body.commentIds);
+ cuts = cuts.filter((c) => wanted.has(c.id));
+ }
+ const opts = {
+ safeTypesOnly: body.safeTypesOnly !== false,
+ allowTypes: Array.isArray(body.allowTypes) ? body.allowTypes : applyCuts.SAFE_CUT_TYPES,
+ };
+ const result = await applyCuts.applyCuts(req.params.id, cuts, opts)
+ .catch((err) => { throw mapServiceError(err); });
+ // Mark applied cuts as accepted in the review.
+ const appliedSections = new Set(result.sections.map((s) => `${s.issueId}:${s.stageId}`));
+ const appliedCuts = cuts.filter((c) => {
+ // A cut was applied if it wasn't in the refusedDetails.
+ const refused = result.refusedDetails.some((r) => r.quote === c.anchorQuote);
+ if (refused) return false;
+ // And its section was updated.
+ const key = c.issueId && c.stageId ? `${c.issueId}:${c.stageId}` : null;
+ return key ? appliedSections.has(key) : true;
+ });
+ // Auto-accept applied cuts.
+ for (const c of appliedCuts) {
+ await manuscriptReview.updateComment(req.params.id, c.id, { status: 'accepted' })
+ .catch((err) => console.warn(`⚠️ applyCuts: failed to mark comment ${c.id} accepted: ${err.message}`));
+ }
+ res.json({ ...result, acceptedCount: appliedCuts.length });
+}));
+
export default router;
diff --git a/server/services/pipeline/applyCuts.js b/server/services/pipeline/applyCuts.js
new file mode 100644
index 0000000000..22fc58a73a
--- /dev/null
+++ b/server/services/pipeline/applyCuts.js
@@ -0,0 +1,331 @@
+/**
+ * Pipeline — Mechanical Cut Applier (#2168)
+ *
+ * Applies adversarial-cut findings to manuscript text with a multi-tier matching
+ * strategy. Autonovel's signature editing technique: the cuts the LLM identified
+ * ARE the revision plan. Safe cut types (OVER-EXPLAIN, REDUNDANT) can be batch-
+ * applied with no human review; other types remain advisory findings.
+ *
+ * Matching tiers:
+ * 1. Exact string match — verbatim substring.
+ * 2. Whitespace-normalized regex — tokens joined by \s+, handles reflow.
+ * 3. Refuse ambiguous — more than 1 occurrence → manual review.
+ * 4. Refuse short — < 25 chars → too risky for mechanical removal.
+ *
+ * Applied through the serialized stage-write path (updateStagesWithLatest) with
+ * runHistory snapshot for undo, same as manuscriptFix.js.
+ */
+
+import { randomUUID } from 'crypto';
+import { updateStagesWithLatest } from './issues.js';
+import { collectManuscriptSections } from './arcPlanner.js';
+import { SAFE_CUT_TYPES, CUT_TYPES } from '../../lib/editorial/checkRegistry.js';
+
+export { SAFE_CUT_TYPES, CUT_TYPES };
+
+// Minimum anchor length to apply mechanically — shorter quotes are too risky.
+export const MIN_ANCHOR_CHARS = 25;
+
+// Output after input: drafted text wins over seed.
+const stageTextOf = (stage) => (stage?.output?.trim() || stage?.input?.trim() || '');
+
+/**
+ * Build a whitespace-tolerant regex for a quote. LLMs often reformat whitespace
+ * when quoting (collapsed indentation, added line breaks), so exact match fails
+ * even when the quote clearly targets a real span.
+ */
+function buildWhitespaceTolerantRegex(quote) {
+ const escaped = quote.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ return new RegExp(escaped.replace(/\s+/g, '\\s+'), 'g');
+}
+
+/**
+ * Locate a cut quote in the text. Returns { start, end, method } on success,
+ * or { error: string } on failure.
+ *
+ * @param {string} text - The manuscript section text.
+ * @param {string} quote - The exact quote to find and cut.
+ * @returns {{ start: number, end: number, method: 'exact'|'normalized' } | { error: string }}
+ */
+export function locateCutSpan(text, quote) {
+ if (!quote || typeof quote !== 'string') {
+ return { error: 'Missing or invalid quote' };
+ }
+ if (quote.length < MIN_ANCHOR_CHARS) {
+ return { error: `Quote too short (${quote.length} < ${MIN_ANCHOR_CHARS} chars)` };
+ }
+
+ // Tier 1: exact match.
+ const first = text.indexOf(quote);
+ if (first !== -1) {
+ // Check for ambiguity (multiple occurrences).
+ const second = text.indexOf(quote, first + 1);
+ if (second !== -1) {
+ return { error: 'Ambiguous: quote appears multiple times' };
+ }
+ return { start: first, end: first + quote.length, method: 'exact' };
+ }
+
+ // Tier 2: whitespace-normalized regex.
+ const re = buildWhitespaceTolerantRegex(quote);
+ const matches = [];
+ let m;
+ while ((m = re.exec(text)) !== null) {
+ matches.push({ start: m.index, end: m.index + m[0].length });
+ // Guard against zero-width matches.
+ if (m.index === re.lastIndex) re.lastIndex += 1;
+ }
+
+ if (matches.length === 0) {
+ return { error: 'Quote not found in text' };
+ }
+ if (matches.length > 1) {
+ return { error: 'Ambiguous: quote matches multiple locations (whitespace-normalized)' };
+ }
+ return { ...matches[0], method: 'normalized' };
+}
+
+/**
+ * Collapse runs of blank lines into a single blank line after cuts are applied.
+ * Cutting a paragraph can leave orphaned blank lines; this cleans them up.
+ */
+export function collapseBlankLines(text) {
+ // Replace 3+ consecutive newlines with 2 (one blank line).
+ return text.replace(/\n{3,}/g, '\n\n');
+}
+
+/**
+ * Plan cuts for a single section. Returns an array of applicable cuts and
+ * an array of refused cuts with reasons.
+ *
+ * @param {string} text - The section's manuscript text.
+ * @param {Array<{ anchorQuote: string, subtype: string|null }>} cuts - Cuts to apply.
+ * @param {{ safeTypesOnly?: boolean, allowTypes?: string[] }} opts
+ * @returns {{ applicable: Array<{ quote: string, span: { start: number, end: number, method: string }, cutType: string|null }>, refused: Array<{ quote: string, reason: string, cutType: string|null }> }}
+ */
+export function planCutsForSection(text, cuts, { safeTypesOnly = true, allowTypes = SAFE_CUT_TYPES } = {}) {
+ const applicable = [];
+ const refused = [];
+
+ for (const cut of cuts) {
+ const quote = typeof cut?.anchorQuote === 'string' ? cut.anchorQuote : '';
+ const cutType = CUT_TYPES.includes(cut?.subtype) ? cut.subtype : null;
+
+ // Filter by cut type if requested.
+ if (safeTypesOnly && cutType && !allowTypes.includes(cutType)) {
+ refused.push({ quote, reason: `Cut type "${cutType}" is not in the safe list`, cutType });
+ continue;
+ }
+
+ const result = locateCutSpan(text, quote);
+ if (result.error) {
+ refused.push({ quote, reason: result.error, cutType });
+ continue;
+ }
+
+ // Check for overlaps with already-planned cuts.
+ const overlaps = applicable.some(
+ (a) => result.start < a.span.end && a.span.start < result.end,
+ );
+ if (overlaps) {
+ refused.push({ quote, reason: 'Overlaps with another cut', cutType });
+ continue;
+ }
+
+ applicable.push({ quote, span: result, cutType });
+ }
+
+ return { applicable, refused };
+}
+
+/**
+ * Apply planned cuts to text, returning the modified text.
+ * Cuts are applied in reverse order (highest start index first) to preserve
+ * earlier indices as we remove spans.
+ */
+export function applyCutsToText(text, applicable) {
+ let result = text;
+ // Sort by start descending so we can slice without index shifting.
+ const sorted = [...applicable].sort((a, b) => b.span.start - a.span.start);
+ for (const cut of sorted) {
+ result = result.slice(0, cut.span.start) + result.slice(cut.span.end);
+ }
+ return collapseBlankLines(result);
+}
+
+/**
+ * Dry-run preview of cuts. Returns the impact without applying.
+ *
+ * @param {string} seriesId
+ * @param {Array<{ id: string, anchorQuote: string, subtype: string|null, issueNumber?: number, issueId?: string, stageId?: string }>} comments
+ * @param {{ safeTypesOnly?: boolean, allowTypes?: string[], minFatPercent?: number }} opts
+ * @returns {Promise<{ preview: Array<{ issueNumber: number, issueId: string, stageId: string, before: string, after: string, applied: number, refused: number, refusedDetails: Array }>, totalApplied: number, totalRefused: number }>}
+ */
+export async function previewCuts(seriesId, comments, { safeTypesOnly = true, allowTypes = SAFE_CUT_TYPES } = {}) {
+ const sections = await collectManuscriptSections(seriesId);
+ const byIssue = new Map();
+ for (const s of sections) {
+ const key = `${s.issueId}:${s.stageId}`;
+ if (!byIssue.has(key)) byIssue.set(key, s);
+ }
+
+ // Group comments by section.
+ const commentsBySection = new Map();
+ for (const c of comments) {
+ const key = c.issueId && c.stageId
+ ? `${c.issueId}:${c.stageId}`
+ : (c.issueNumber != null
+ ? sections.find((s) => s.number === c.issueNumber)?.let?.((s) => `${s.issueId}:${s.stageId}`)
+ : null);
+ if (!key) continue;
+ if (!commentsBySection.has(key)) commentsBySection.set(key, []);
+ commentsBySection.get(key).push(c);
+ }
+
+ const preview = [];
+ let totalApplied = 0;
+ let totalRefused = 0;
+
+ for (const [key, sectionComments] of commentsBySection) {
+ const section = byIssue.get(key);
+ if (!section) continue;
+
+ const { applicable, refused } = planCutsForSection(section.content || '', sectionComments, {
+ safeTypesOnly,
+ allowTypes,
+ });
+
+ const after = applicable.length > 0 ? applyCutsToText(section.content || '', applicable) : section.content;
+
+ preview.push({
+ issueNumber: section.number,
+ issueId: section.issueId,
+ stageId: section.stageId,
+ before: section.content || '',
+ after,
+ applied: applicable.length,
+ refused: refused.length,
+ refusedDetails: refused,
+ });
+
+ totalApplied += applicable.length;
+ totalRefused += refused.length;
+ }
+
+ return { preview, totalApplied, totalRefused };
+}
+
+/**
+ * Apply cuts to manuscript sections. Writes through the serialized stage-write
+ * path with runHistory snapshots for undo.
+ *
+ * @param {string} seriesId
+ * @param {Array<{ id: string, anchorQuote: string, subtype: string|null, issueNumber?: number, issueId?: string, stageId?: string }>} comments
+ * @param {{ safeTypesOnly?: boolean, allowTypes?: string[] }} opts
+ * @returns {Promise<{ applied: number, refused: number, sections: Array<{ issueId: string, stageId: string, issueNumber: number }>, refusedDetails: Array }>}
+ */
+export async function applyCuts(seriesId, comments, { safeTypesOnly = true, allowTypes = SAFE_CUT_TYPES } = {}) {
+ const sections = await collectManuscriptSections(seriesId);
+ const byIssue = new Map();
+ for (const s of sections) {
+ const key = `${s.issueId}:${s.stageId}`;
+ if (!byIssue.has(key)) byIssue.set(key, s);
+ }
+
+ // Group comments by section.
+ const commentsBySection = new Map();
+ for (const c of comments) {
+ let key = null;
+ if (c.issueId && c.stageId) {
+ key = `${c.issueId}:${c.stageId}`;
+ } else if (c.issueNumber != null) {
+ const s = sections.find((sec) => sec.number === c.issueNumber);
+ if (s) key = `${s.issueId}:${s.stageId}`;
+ }
+ if (!key) continue;
+ if (!commentsBySection.has(key)) commentsBySection.set(key, []);
+ commentsBySection.get(key).push(c);
+ }
+
+ const updates = [];
+ const allRefused = [];
+ let totalApplied = 0;
+
+ for (const [key, sectionComments] of commentsBySection) {
+ const section = byIssue.get(key);
+ if (!section) continue;
+
+ const { applicable, refused } = planCutsForSection(section.content || '', sectionComments, {
+ safeTypesOnly,
+ allowTypes,
+ });
+
+ allRefused.push(...refused.map((r) => ({ ...r, issueNumber: section.number })));
+
+ if (applicable.length === 0) continue;
+
+ const newText = applyCutsToText(section.content || '', applicable);
+ totalApplied += applicable.length;
+
+ updates.push({
+ issueId: section.issueId,
+ stageId: section.stageId,
+ issueNumber: section.number,
+ computeFn: (cur) => {
+ // Verify the text hasn't changed since we planned.
+ if (stageTextOf(cur) !== section.content) {
+ console.warn(`⚠️ applyCuts: skipping issue ${section.number} — text changed mid-apply`);
+ return null;
+ }
+ return { output: newText, status: 'edited', lastRunId: `cut-${randomUUID()}` };
+ },
+ });
+ }
+
+ // Apply all updates through the serialized path.
+ const appliedSections = [];
+ if (updates.length > 0) {
+ const results = await updateStagesWithLatest(
+ seriesId,
+ updates.map((u) => ({ issueId: u.issueId, stageId: u.stageId, computeFn: u.computeFn })),
+ { snapshotPrior: true },
+ );
+ for (let i = 0; i < results.length; i += 1) {
+ if (results[i].stage) {
+ appliedSections.push({
+ issueId: updates[i].issueId,
+ stageId: updates[i].stageId,
+ issueNumber: updates[i].issueNumber,
+ });
+ }
+ }
+ }
+
+ console.log(`✂️ applyCuts: applied=${totalApplied} refused=${allRefused.length} sections=${appliedSections.length}`);
+
+ return {
+ applied: totalApplied,
+ refused: allRefused.length,
+ sections: appliedSections,
+ refusedDetails: allRefused,
+ };
+}
+
+/**
+ * Filter comments to only those that are adversarial-cut findings (have a
+ * cut-type subtype) and are still open.
+ */
+export function filterCutComments(comments) {
+ return (Array.isArray(comments) ? comments : []).filter((c) => {
+ if (c.status !== 'open') return false;
+ // Must have a cutType subtype (one of CUT_TYPES).
+ return CUT_TYPES.includes(c.subtype);
+ });
+}
+
+/**
+ * Filter comments to only safe-to-apply cut types.
+ */
+export function filterSafeCutComments(comments) {
+ return filterCutComments(comments).filter((c) => SAFE_CUT_TYPES.includes(c.subtype));
+}
diff --git a/server/services/pipeline/applyCuts.test.js b/server/services/pipeline/applyCuts.test.js
new file mode 100644
index 0000000000..a24dd96951
--- /dev/null
+++ b/server/services/pipeline/applyCuts.test.js
@@ -0,0 +1,223 @@
+/**
+ * Tests for the mechanical cut applier (#2168).
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ locateCutSpan,
+ collapseBlankLines,
+ planCutsForSection,
+ applyCutsToText,
+ filterCutComments,
+ filterSafeCutComments,
+ MIN_ANCHOR_CHARS,
+ CUT_TYPES,
+ SAFE_CUT_TYPES,
+} from './applyCuts.js';
+
+describe('locateCutSpan', () => {
+ it('finds exact match', () => {
+ const text = 'The quick brown fox jumps over the lazy dog and runs away quickly.';
+ const quote = 'brown fox jumps over the lazy dog'; // 33 chars
+ const result = locateCutSpan(text, quote);
+ expect(result.error).toBeUndefined();
+ expect(result.method).toBe('exact');
+ expect(text.slice(result.start, result.end)).toBe(quote);
+ });
+
+ it('finds whitespace-normalized match', () => {
+ const text = 'The quick brown fox\njumps over the lazy dog and runs away.';
+ const quote = 'brown fox jumps over the lazy dog'; // 33 chars
+ const result = locateCutSpan(text, quote);
+ expect(result.error).toBeUndefined();
+ expect(result.method).toBe('normalized');
+ expect(result.start).toBeGreaterThan(0);
+ });
+
+ it('refuses ambiguous quote (multiple occurrences)', () => {
+ const text = 'The fox jumps high. Another fox jumps high. A third fox jumps high.';
+ const quote = 'fox jumps high. Another fox jumps'; // appears once exactly, so need different test
+ const result = locateCutSpan(text, quote);
+ // This particular quote is unique, so let's test a truly ambiguous case
+ const text2 = 'She said hello and he replied hello and then she said hello again.';
+ const quote2 = 'said hello and he replied hello';
+ const result2 = locateCutSpan(text2, quote2);
+ // Actually this is also unique. Let's use a simpler case.
+ const text3 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ';
+ const quote3 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
+ const result3 = locateCutSpan(text3, quote3);
+ expect(result3.error).toBe('Ambiguous: quote appears multiple times');
+ });
+
+ it('refuses short quote', () => {
+ const text = 'Hello world, this is a test.';
+ const quote = 'Hello world'; // 11 chars, below 25
+ const result = locateCutSpan(text, quote);
+ expect(result.error).toContain('too short');
+ });
+
+ it('returns error for missing quote', () => {
+ const text = 'The quick brown fox.';
+ const quote = 'This text is not in the source and is long enough to pass the length check.';
+ const result = locateCutSpan(text, quote);
+ expect(result.error).toBe('Quote not found in text');
+ });
+
+ it('returns error for missing or invalid quote input', () => {
+ expect(locateCutSpan('some text', '')).toEqual({ error: 'Missing or invalid quote' });
+ expect(locateCutSpan('some text', null)).toEqual({ error: 'Missing or invalid quote' });
+ });
+});
+
+describe('collapseBlankLines', () => {
+ it('collapses multiple blank lines to one', () => {
+ const input = 'First paragraph.\n\n\n\n\nSecond paragraph.';
+ const result = collapseBlankLines(input);
+ expect(result).toBe('First paragraph.\n\nSecond paragraph.');
+ });
+
+ it('leaves single blank lines alone', () => {
+ const input = 'First paragraph.\n\nSecond paragraph.';
+ const result = collapseBlankLines(input);
+ expect(result).toBe(input);
+ });
+
+ it('handles no blank lines', () => {
+ const input = 'First paragraph.\nSecond paragraph.';
+ const result = collapseBlankLines(input);
+ expect(result).toBe(input);
+ });
+});
+
+describe('planCutsForSection', () => {
+ const sampleText = `
+This is the introduction paragraph with some verbose content.
+
+Here is a sentence that over-explains things unnecessarily by saying the same thing twice in different words.
+
+A redundant paragraph that repeats information from earlier.
+
+The conclusion wraps everything up nicely.
+`.trim();
+
+ it('plans applicable cuts with exact matches', () => {
+ const cuts = [
+ { anchorQuote: 'over-explains things unnecessarily by', subtype: 'OVER-EXPLAIN' },
+ ];
+ const { applicable, refused } = planCutsForSection(sampleText, cuts, { safeTypesOnly: true });
+ expect(applicable).toHaveLength(1);
+ expect(refused).toHaveLength(0);
+ expect(applicable[0].cutType).toBe('OVER-EXPLAIN');
+ });
+
+ it('refuses non-safe cut types when safeTypesOnly=true', () => {
+ const cuts = [
+ { anchorQuote: 'introduction paragraph with some verbose', subtype: 'FAT' },
+ ];
+ const { applicable, refused } = planCutsForSection(sampleText, cuts, { safeTypesOnly: true });
+ expect(applicable).toHaveLength(0);
+ expect(refused).toHaveLength(1);
+ expect(refused[0].reason).toContain('not in the safe list');
+ });
+
+ it('allows non-safe cut types when safeTypesOnly=false', () => {
+ const cuts = [
+ { anchorQuote: 'introduction paragraph with some verbose', subtype: 'FAT' },
+ ];
+ const { applicable, refused } = planCutsForSection(sampleText, cuts, {
+ safeTypesOnly: false,
+ allowTypes: CUT_TYPES,
+ });
+ expect(applicable).toHaveLength(1);
+ expect(refused).toHaveLength(0);
+ });
+
+ it('refuses overlapping cuts', () => {
+ const cuts = [
+ { anchorQuote: 'over-explains things unnecessarily by', subtype: 'OVER-EXPLAIN' },
+ { anchorQuote: 'things unnecessarily by saying the same', subtype: 'REDUNDANT' },
+ ];
+ const { applicable, refused } = planCutsForSection(sampleText, cuts, { safeTypesOnly: true });
+ expect(applicable).toHaveLength(1);
+ expect(refused).toHaveLength(1);
+ expect(refused[0].reason).toBe('Overlaps with another cut');
+ });
+
+ it('refuses quotes not found in text', () => {
+ const cuts = [
+ { anchorQuote: 'this text does not exist anywhere in the sample', subtype: 'OVER-EXPLAIN' },
+ ];
+ const { applicable, refused } = planCutsForSection(sampleText, cuts, { safeTypesOnly: true });
+ expect(applicable).toHaveLength(0);
+ expect(refused).toHaveLength(1);
+ expect(refused[0].reason).toBe('Quote not found in text');
+ });
+});
+
+describe('applyCutsToText', () => {
+ it('removes single cut and collapses blank lines', () => {
+ const text = 'First sentence.\n\nMiddle sentence to cut.\n\nLast sentence.';
+ // "Middle sentence to cut." starts at index 17 (after "First sentence.\n\n")
+ // and ends at index 40 (17 + 23 chars)
+ const applicable = [{ quote: 'Middle sentence to cut.', span: { start: 17, end: 40, method: 'exact' } }];
+ const result = applyCutsToText(text, applicable);
+ // After removing, we have "First sentence.\n\n\n\nLast sentence." which collapses to:
+ expect(result).toBe('First sentence.\n\nLast sentence.');
+ });
+
+ it('removes multiple cuts in correct order', () => {
+ const text = 'One. Two. Three. Four. Five.';
+ // "Two. " starts at 5, ends at 10
+ // "Four. " starts at 17, ends at 23
+ const applicable = [
+ { quote: 'Two. ', span: { start: 5, end: 10, method: 'exact' } },
+ { quote: 'Four. ', span: { start: 17, end: 23, method: 'exact' } },
+ ];
+ const result = applyCutsToText(text, applicable);
+ expect(result).toBe('One. Three. Five.');
+ });
+});
+
+describe('filterCutComments', () => {
+ it('filters to open cut-type comments only', () => {
+ const comments = [
+ { id: '1', status: 'open', subtype: 'OVER-EXPLAIN' },
+ { id: '2', status: 'open', subtype: 'FAT' },
+ { id: '3', status: 'dismissed', subtype: 'OVER-EXPLAIN' },
+ { id: '4', status: 'open', subtype: null },
+ { id: '5', status: 'accepted', subtype: 'REDUNDANT' },
+ { id: '6', status: 'open', subtype: 'REDUNDANT' },
+ ];
+ const result = filterCutComments(comments);
+ expect(result).toHaveLength(3);
+ expect(result.map((c) => c.id)).toEqual(['1', '2', '6']);
+ });
+});
+
+describe('filterSafeCutComments', () => {
+ it('filters to open safe-type cuts only', () => {
+ const comments = [
+ { id: '1', status: 'open', subtype: 'OVER-EXPLAIN' },
+ { id: '2', status: 'open', subtype: 'FAT' },
+ { id: '3', status: 'open', subtype: 'REDUNDANT' },
+ { id: '4', status: 'open', subtype: 'TELL' },
+ ];
+ const result = filterSafeCutComments(comments);
+ expect(result).toHaveLength(2);
+ expect(result.map((c) => c.id)).toEqual(['1', '3']);
+ });
+});
+
+describe('constants', () => {
+ it('has expected CUT_TYPES', () => {
+ expect(CUT_TYPES).toEqual(['OVER-EXPLAIN', 'REDUNDANT', 'FAT', 'GENERIC', 'TELL', 'STRUCTURAL']);
+ });
+
+ it('has expected SAFE_CUT_TYPES', () => {
+ expect(SAFE_CUT_TYPES).toEqual(['OVER-EXPLAIN', 'REDUNDANT']);
+ });
+
+ it('has reasonable MIN_ANCHOR_CHARS', () => {
+ expect(MIN_ANCHOR_CHARS).toBe(25);
+ });
+});