Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(issue-1340): chunk LLM editorial checks to the provider context window

[._.]/ Adam Eivy8df3a7c7d8e2
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.md
index 3e7772a017..33ca583df0 100644
--- a/server/lib/editorial/README.md
+++ b/server/lib/editorial/README.md
@@ -8,8 +8,13 @@ optional gate, and a `run(ctx)` that returns findings shaped for the existing
the enabled checks, and seeds findings lives at
`server/services/pipeline/editorial/checkRunner.js`.
-This directory is **pure** (no side-effecting imports). LLM-kind checks get
-their model caller through `ctx.callStagedLLM`, injected by the runner.
+This directory is **pure** (no side-effecting imports — only `zod` and the pure
+`estimateTokens` budgeter). LLM-kind checks get their model caller through
+`ctx.callStagedLLM`, and a manuscript-consuming LLM check plans the corpus into
+provider-sized chunks through `ctx.planManuscriptChunks` — both injected by the
+runner. Per-chunk findings are merged first-wins (capped at the check's
+`maxFindings`) via `mergeChunkFindings`/`editorialFindingKey`, so a long series
+is fully reviewed regardless of the provider's context window (#1340).
## Discovery rule
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index c1ec718a0c..e601cc9235 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -10,9 +10,12 @@
* existing `manuscriptReview` comment store.
*
* This module is intentionally PURE — it imports nothing with side effects
- * (only `zod`). LLM-kind checks receive their model caller through
- * `ctx.callStagedLLM`, injected by `server/services/pipeline/editorial/checkRunner.js`,
- * so the registry stays side-effect-free and unit-testable in isolation.
+ * (only `zod` and the pure `estimateTokens` budgeter). LLM-kind checks receive
+ * their model caller through `ctx.callStagedLLM`, and a manuscript-consuming LLM
+ * check plans the manuscript into provider-sized chunks through
+ * `ctx.planManuscriptChunks` — both injected by
+ * `server/services/pipeline/editorial/checkRunner.js`, so the registry stays
+ * side-effect-free and unit-testable in isolation.
*
* A finding returned by `run(ctx)` is a partial `manuscriptReview` comment:
* { severity?, category?, location?, problem (required), suggestion?,
@@ -22,6 +25,7 @@
*/
import { z } from 'zod';
+import { estimateTokens } from '../contextBudget.js';
export const CHECK_SCOPES = Object.freeze(['series', 'issue', 'scene', 'noun']);
export const CHECK_KINDS = Object.freeze(['deterministic', 'llm']);
@@ -178,20 +182,64 @@ function attachmentBackstoryRows(ctx) {
}
// ---------------------------------------------------------------------------
-// Shared LLM-check helpers. Every `kind: 'llm'` check truncates an over-long
-// manuscript before the call and normalizes the model's raw findings into the
-// manuscriptReview comment shape afterward — these collapse those two repeated
-// blocks so the cap message + field validation live once.
+// Shared LLM-check helpers. Every `kind: 'llm'` check normalizes the model's
+// raw findings into the manuscriptReview comment shape, and a manuscript-
+// consuming check additionally feeds the whole corpus to the model in
+// provider-sized chunks (so a long series isn't truncated on a small/local
+// provider) and merges the per-chunk findings. These collapse those repeated
+// blocks so the field validation + chunk-merge live once.
// ---------------------------------------------------------------------------
-// Truncate `full` to `cap` chars with a note so a long corpus can't overflow a
-// small/local provider's context window. A single-call safeguard; full
-// per-provider context chunking is tracked separately.
-function capManuscript(full, cap) {
- const text = full || '';
- return text.length > cap
- ? `${text.slice(0, cap)}\n\n[manuscript truncated to the first ${cap} characters for this check]`
- : text;
+// Fixed per-call prompt overhead (template scaffolding + JSON-shape
+// instructions) reserved on top of any check-specific static vars, so the
+// chunk budget leaves room for the prompt the manuscript rides inside.
+export const EDITORIAL_PROMPT_OVERHEAD_TOKENS = 1_500;
+
+// First-wins dedup key for an editorial finding, used to merge results across
+// manuscript chunks. Mirrors completenessPass.findingKey: a finding identical on
+// (issue, category, anchor, problem) is kept once even if two chunks surface it.
+export const editorialFindingKey = (f) => [
+ f.issueNumber ?? '',
+ f.category ?? '',
+ (f.anchorQuote || '').trim().toLowerCase().slice(0, 120),
+ (f.problem || '').trim().toLowerCase().slice(0, 120),
+].join('|');
+
+// Merge per-chunk finding lists first-wins, capped at `max`. The cap bounds the
+// WHOLE run (not each chunk) so a long, many-chunk manuscript can't flood the
+// review — preserving `maxFindings`'s original single-call meaning.
+export function mergeChunkFindings(lists, max = Infinity) {
+ const merged = new Map();
+ for (const list of (Array.isArray(lists) ? lists : [])) {
+ for (const f of (Array.isArray(list) ? list : [])) {
+ const k = editorialFindingKey(f);
+ if (!merged.has(k)) merged.set(k, f);
+ }
+ }
+ return [...merged.values()].slice(0, Math.max(0, max));
+}
+
+// Shared body for a manuscript-consuming LLM check. Plans the manuscript into
+// provider-sized chunks for `stage` (via the runner-injected
+// `ctx.planManuscriptChunks`), runs the model on each chunk, and merges the
+// findings first-wins (capped at the check's `maxFindings`). `buildVars(chunk)`
+// returns the stage vars — only the manuscript var changes per chunk. These
+// checks are all manuscript-scoped, so findings keep a model-supplied issue
+// number (`withIssueNumber: true`).
+async function runManuscriptLlmCheck(ctx, { stage, category, overheadTokens = 0, buildVars }) {
+ const max = ctx.config?.maxFindings ?? 12;
+ const chunks = await ctx.planManuscriptChunks(stage, { overheadTokens });
+ const perChunk = [];
+ for (const manuscript of chunks) {
+ const { content } = await ctx.callStagedLLM(stage, buildVars(manuscript), { returnsJson: true, source: stage });
+ perChunk.push(mapLlmFindings(content?.findings, {
+ severityDefault: ctx.severityDefault,
+ category,
+ max,
+ withIssueNumber: true,
+ }));
+ }
+ return mergeChunkFindings(perChunk, max);
}
// Normalize raw LLM findings into partial manuscriptReview comments: validate
@@ -574,9 +622,6 @@ export const EDITORIAL_CHECKS = [
configSchema: z.object({
// Cap findings per run so a long manuscript can't flood the review.
maxFindings: z.number().int().min(1).max(50).default(12),
- // Bound the prompt so a long series can't overflow a small/local provider's
- // context window. Single-call safeguard — mirrors the info-dumping check.
- maxManuscriptChars: z.number().int().min(2000).max(200_000).default(48_000),
}),
configFields: [
{
@@ -588,29 +633,16 @@ export const EDITORIAL_CHECKS = [
step: 1,
help: 'Cap findings so a long manuscript can not flood the review.',
},
- {
- key: 'maxManuscriptChars',
- label: 'Max manuscript characters analyzed',
- type: 'number',
- min: 2000,
- max: 200_000,
- step: 1000,
- help: 'Bounds the prompt so a long series can not overflow a small provider context window.',
- },
],
gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
- run: async (ctx) => {
- const manuscript = capManuscript(ctx.manuscript, ctx.config?.maxManuscriptChars ?? 48_000);
- const { content } = await ctx.callStagedLLM(
- OBJECT_MOTIVATION_STAGE,
- { manuscript, objects: describeObjectAttachments(ctx) },
- { returnsJson: true, source: OBJECT_MOTIVATION_STAGE },
- );
- return mapLlmFindings(content?.findings, {
- severityDefault: ctx.severityDefault,
+ run: (ctx) => {
+ const objects = describeObjectAttachments(ctx);
+ return runManuscriptLlmCheck(ctx, {
+ stage: OBJECT_MOTIVATION_STAGE,
category: 'continuity',
- max: ctx.config?.maxFindings ?? 12,
- withIssueNumber: true,
+ // The objects-attachment summary is fixed per-call overhead.
+ overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS + estimateTokens(objects),
+ buildVars: (manuscript) => ({ manuscript, objects }),
});
},
},
@@ -680,11 +712,6 @@ export const EDITORIAL_CHECKS = [
configSchema: z.object({
// Cap findings per run so a long manuscript can't flood the review.
maxFindings: z.number().int().min(1).max(50).default(12),
- // Bound the prompt so a long series can't overflow a small/local
- // provider's context window (which would reject/clip the call and yield
- // zero findings). This is a single-call safeguard — full per-provider
- // context-window chunking (à la completenessPass) is tracked separately.
- maxManuscriptChars: z.number().int().min(2000).max(200_000).default(48_000),
}),
configFields: [
{
@@ -696,31 +723,14 @@ export const EDITORIAL_CHECKS = [
step: 1,
help: 'Cap findings so a long manuscript can not flood the review.',
},
- {
- key: 'maxManuscriptChars',
- label: 'Max manuscript characters analyzed',
- type: 'number',
- min: 2000,
- max: 200_000,
- step: 1000,
- help: 'Bounds the prompt so a long series can not overflow a small provider context window.',
- },
],
gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
- run: async (ctx) => {
- const manuscript = capManuscript(ctx.manuscript, ctx.config?.maxManuscriptChars ?? 48_000);
- const { content } = await ctx.callStagedLLM(
- INFO_DUMPING_STAGE,
- { manuscript },
- { returnsJson: true, source: INFO_DUMPING_STAGE },
- );
- return mapLlmFindings(content?.findings, {
- severityDefault: ctx.severityDefault,
- category: 'exposition',
- max: ctx.config?.maxFindings ?? 12,
- withIssueNumber: true,
- });
- },
+ run: (ctx) => runManuscriptLlmCheck(ctx, {
+ stage: INFO_DUMPING_STAGE,
+ category: 'exposition',
+ overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS,
+ buildVars: (manuscript) => ({ manuscript }),
+ }),
},
{
id: 'style.reading-level',
@@ -791,9 +801,6 @@ export const EDITORIAL_CHECKS = [
configSchema: z.object({
// Cap findings per run so a long manuscript can't flood the review.
maxFindings: z.number().int().min(1).max(50).default(12),
- // Bound the prompt so a long series can't overflow a small/local
- // provider's context window. Single-call safeguard — mirrors info-dumping.
- maxManuscriptChars: z.number().int().min(2000).max(200_000).default(48_000),
}),
configFields: [
{
@@ -805,34 +812,20 @@ export const EDITORIAL_CHECKS = [
step: 1,
help: 'Cap findings so a long manuscript can not flood the review.',
},
- {
- key: 'maxManuscriptChars',
- label: 'Max manuscript characters analyzed',
- type: 'number',
- min: 2000,
- max: 200_000,
- step: 1000,
- help: 'Bounds the prompt so a long series can not overflow a small provider context window.',
- },
],
// Skip unless there's prose AND the style guide declares at least one
// conformance-relevant field (tense / POV / rating / profanity / audience).
gate: (ctx) => (ctx.manuscript || '').trim().length > 0
&& hasConformanceFields(ctx.series?.styleGuide),
- run: async (ctx) => {
+ run: (ctx) => {
const expectations = styleGuideExpectations(ctx.series?.styleGuide);
if (!expectations) return [];
- const manuscript = capManuscript(ctx.manuscript, ctx.config?.maxManuscriptChars ?? 48_000);
- const { content } = await ctx.callStagedLLM(
- STYLE_CONFORMANCE_STAGE,
- { manuscript, styleGuide: expectations },
- { returnsJson: true, source: STYLE_CONFORMANCE_STAGE },
- );
- return mapLlmFindings(content?.findings, {
- severityDefault: ctx.severityDefault,
+ return runManuscriptLlmCheck(ctx, {
+ stage: STYLE_CONFORMANCE_STAGE,
category: 'style',
- max: ctx.config?.maxFindings ?? 12,
- withIssueNumber: true,
+ // The style-guide expectations are fixed per-call overhead.
+ overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS + estimateTokens(expectations),
+ buildVars: (manuscript) => ({ manuscript, styleGuide: expectations }),
});
},
},
diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.js
index 765982d108..578b74f3d9 100644
--- a/server/lib/editorial/checkRegistry.test.js
+++ b/server/lib/editorial/checkRegistry.test.js
@@ -144,43 +144,76 @@ describe('editorial check registry — config + state resolution', () => {
});
describe('prose.info-dumping — LLM check', () => {
- it('caps the manuscript sent to the model so a long corpus cannot overflow context', async () => {
- let sent = null;
- const ctx = {
- manuscript: 'x'.repeat(100_000),
- config: { maxManuscriptChars: 10_000, maxFindings: 12 },
- severityDefault: 'medium',
- callStagedLLM: async (_stage, vars) => { sent = vars.manuscript; return { content: { findings: [] } }; },
- };
- await getCheck(INFODUMP).run(ctx);
- expect(sent.length).toBeLessThan(11_000); // 10k cap + a short truncation note
- expect(sent).toContain('truncated');
+ // Default ctx: the runner-injected chunker resolves to a single whole-corpus
+ // chunk (the common "provider fits the book" case). Tests that exercise
+ // chunking override `planManuscriptChunks`.
+ const wholeCtx = (overrides = {}) => ({
+ manuscript: 'As you know, Bob, the kingdom fell.',
+ config: { maxFindings: 12 },
+ severityDefault: 'medium',
+ planManuscriptChunks: async () => [overrides.manuscript ?? 'As you know, Bob, the kingdom fell.'],
+ callStagedLLM: async () => ({ content: { findings: [] } }),
+ ...overrides,
});
- it('passes a short manuscript through untruncated and shapes findings', async () => {
- const ctx = {
- manuscript: 'As you know, Bob, the kingdom fell.',
- config: { maxManuscriptChars: 48_000, maxFindings: 12 },
- severityDefault: 'medium',
+ it('feeds each planned manuscript chunk to the model and merges findings across them', async () => {
+ // A long series the provider can't hold in one call → chunked into two.
+ const seen = [];
+ const ctx = wholeCtx({
+ config: { maxFindings: 12 },
+ planManuscriptChunks: async (_stage, opts) => {
+ // The check passes a fixed prompt-overhead budget so the chunker leaves
+ // room for the template.
+ expect(opts.overheadTokens).toBeGreaterThan(0);
+ return ['# Issue 1\n\nchunk one', '# Issue 2\n\nchunk two'];
+ },
callStagedLLM: async (_stage, vars) => {
- expect(vars.manuscript).not.toContain('truncated');
+ seen.push(vars.manuscript);
+ const n = seen.length;
+ return { content: { findings: [{ severity: 'medium', issueNumber: n, problem: `dump ${n}`, anchorQuote: `a${n}` }] } };
+ },
+ });
+ const findings = await getCheck(INFODUMP).run(ctx);
+ expect(seen).toEqual(['# Issue 1\n\nchunk one', '# Issue 2\n\nchunk two']);
+ // One finding per chunk, merged across both.
+ expect(findings).toHaveLength(2);
+ expect(findings.map((f) => f.issueNumber).sort()).toEqual([1, 2]);
+ expect(findings.every((f) => f.category === 'exposition')).toBe(true);
+ });
+
+ it('dedups a finding surfaced in more than one chunk (first-wins)', async () => {
+ const dup = { severity: 'high', issueNumber: 1, problem: 'same dump', anchorQuote: 'As you know' };
+ const ctx = wholeCtx({
+ planManuscriptChunks: async () => ['chunk a', 'chunk b'],
+ callStagedLLM: async () => ({ content: { findings: [dup] } }),
+ });
+ const findings = await getCheck(INFODUMP).run(ctx);
+ expect(findings).toHaveLength(1);
+ expect(findings[0].problem).toBe('same dump');
+ });
+
+ it('passes the whole corpus through in one call when the provider fits it', async () => {
+ const ctx = wholeCtx({
+ callStagedLLM: async (_stage, vars) => {
+ expect(vars.manuscript).toBe('As you know, Bob, the kingdom fell.');
return { content: { findings: [{ severity: 'high', issueNumber: 1, problem: 'dump', anchorQuote: 'As you know', suggestion: 'cut' }] } };
},
- };
+ });
const findings = await getCheck(INFODUMP).run(ctx);
expect(findings).toHaveLength(1);
expect(findings[0].category).toBe('exposition');
expect(findings[0].issueNumber).toBe(1);
});
- it('respects maxFindings', async () => {
- const many = Array.from({ length: 30 }, (_, i) => ({ severity: 'low', problem: `p${i}`, anchorQuote: `a${i}` }));
- const ctx = {
- manuscript: 'short',
- config: { maxManuscriptChars: 48_000, maxFindings: 5 },
- severityDefault: 'medium',
- callStagedLLM: async () => ({ content: { findings: many } }),
- };
+ it('respects maxFindings as a whole-run cap (across chunks)', async () => {
+ // Two chunks each return 30 distinct findings; the run cap of 5 bounds the merged total.
+ const many = (tag) => Array.from({ length: 30 }, (_, i) => ({ severity: 'low', problem: `${tag}-p${i}`, anchorQuote: `${tag}-a${i}` }));
+ let call = 0;
+ const ctx = wholeCtx({
+ config: { maxFindings: 5 },
+ planManuscriptChunks: async () => ['c1', 'c2'],
+ callStagedLLM: async () => ({ content: { findings: many(call++ === 0 ? 'x' : 'y') } }),
+ });
const findings = await getCheck(INFODUMP).run(ctx);
expect(findings).toHaveLength(5);
});
@@ -428,17 +461,22 @@ describe('objects.unattached-significant — deterministic check (#1288)', () =>
});
describe('objects.unmotivated-interaction — LLM check (#1288)', () => {
- const baseCtx = (overrides = {}) => ({
- manuscript: 'She clutched the watch as if it meant everything.',
- canon: {
- objects: [{ id: 'o1', name: 'Watch', significance: 'heirloom', attachments: [{ characterId: 'c1', emotion: 'grief' }] }],
- characters: [{ id: 'c1', name: 'Mara' }],
- },
- config: { maxManuscriptChars: 48_000, maxFindings: 12 },
- severityDefault: 'low',
- callStagedLLM: async () => ({ content: { findings: [] } }),
- ...overrides,
- });
+ const baseCtx = (overrides = {}) => {
+ const manuscript = overrides.manuscript ?? 'She clutched the watch as if it meant everything.';
+ return {
+ manuscript,
+ canon: {
+ objects: [{ id: 'o1', name: 'Watch', significance: 'heirloom', attachments: [{ characterId: 'c1', emotion: 'grief' }] }],
+ characters: [{ id: 'c1', name: 'Mara' }],
+ },
+ config: { maxFindings: 12 },
+ severityDefault: 'low',
+ // Default chunker: a single whole-corpus chunk.
+ planManuscriptChunks: async () => [manuscript],
+ callStagedLLM: async () => ({ content: { findings: [] } }),
+ ...overrides,
+ };
+ };
it('passes the manuscript AND an objects-attachment summary to the model', async () => {
let vars = null;
@@ -450,21 +488,24 @@ describe('objects.unmotivated-interaction — LLM check (#1288)', () => {
expect(vars.objects).toContain('Mara'); // resolved character name, not the id
});
- it('caps the manuscript so a long corpus cannot overflow context', async () => {
- let sent = null;
+ it('budgets the objects summary as prompt overhead and re-sends it on every chunk', async () => {
+ let overhead = null;
+ const objectsSeen = [];
await getCheck('objects.unmotivated-interaction').run(baseCtx({
- manuscript: 'x'.repeat(100_000),
- config: { maxManuscriptChars: 10_000, maxFindings: 12 },
- callStagedLLM: async (_stage, v) => { sent = v.manuscript; return { content: { findings: [] } }; },
+ planManuscriptChunks: async (_stage, opts) => { overhead = opts.overheadTokens; return ['chunk a', 'chunk b']; },
+ callStagedLLM: async (_stage, v) => { objectsSeen.push(v.objects); return { content: { findings: [] } }; },
}));
- expect(sent.length).toBeLessThan(11_000);
- expect(sent).toContain('truncated');
+ // Overhead exceeds the fixed template reserve because the objects summary is counted in.
+ expect(overhead).toBeGreaterThan(0);
+ // The objects summary rides every chunk (it's not part of the chunked manuscript).
+ expect(objectsSeen).toHaveLength(2);
+ expect(objectsSeen.every((o) => o.includes('Watch'))).toBe(true);
});
it('shapes findings into the continuity category and respects maxFindings', async () => {
const many = Array.from({ length: 30 }, (_, i) => ({ severity: 'low', problem: `p${i}`, anchorQuote: `a${i}` }));
const findings = await getCheck('objects.unmotivated-interaction').run(baseCtx({
- config: { maxManuscriptChars: 48_000, maxFindings: 4 },
+ config: { maxFindings: 4 },
callStagedLLM: async () => ({ content: { findings: many } }),
}));
expect(findings).toHaveLength(4);
@@ -598,11 +639,13 @@ describe('style.conformance — LLM check (#1303)', () => {
it('passes the declared expectations + manuscript to the model and maps findings', async () => {
let sentVars = null;
+ const manuscript = '# Issue 2 — Drift (prose)\n\nI walk to the door.';
const findings = await check.run({
series: { styleGuide: { tense: 'past', povPerson: 'first', contentRating: 'PG' } },
- manuscript: '# Issue 2 — Drift (prose)\n\nI walk to the door.',
+ manuscript,
config: { maxFindings: 5 },
severityDefault: 'medium',
+ planManuscriptChunks: async () => [manuscript],
callStagedLLM: async (_stage, vars) => {
sentVars = vars;
return { content: { findings: [{ severity: 'high', issueNumber: 2, problem: 'present-tense slip', anchorQuote: 'I walk' }] } };
diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.js
index 0e599cc052..a3b550c359 100644
--- a/server/services/pipeline/editorial/checkRunner.js
+++ b/server/services/pipeline/editorial/checkRunner.js
@@ -17,13 +17,14 @@
import { randomUUID } from 'crypto';
import { createSseRunner } from '../../../lib/sseUtils.js';
-import { runStagedLLM } from '../../../lib/stageRunner.js';
+import { runStagedLLM, resolveStageContext } from '../../../lib/stageRunner.js';
+import { planManuscriptPass } from '../../../lib/contextBudget.js';
import { getEnabledChecks, getEnabledCheckRows } from '../../../lib/editorial/index.js';
import { getSettings } from '../../settings.js';
import { getSeries } from '../series.js';
import { listIssues } from '../issues.js';
import { getSeriesCanon } from '../seriesCanon.js';
-import { collectManuscriptSections, sectionsCorpus } from '../arcPlanner.js';
+import { collectManuscriptSections, sectionsCorpus, manuscriptSectionHeader } from '../arcPlanner.js';
import { seedReviewFromFindings } from '../manuscriptReview.js';
/**
@@ -73,6 +74,24 @@ export async function runEditorialChecks(seriesId, options = {}) {
// provider/model overrides so an LLM check honors the autopilot's choice.
callStagedLLM: (stage, vars, opts = {}) =>
runStagedLLM(stage, vars, { providerOverride, modelOverride, ...opts }),
+ // Injected manuscript chunker — plans the stitched manuscript into chunks
+ // sized to `stage`'s resolved provider context window (reusing the same
+ // budgeter as the completeness pass), so a long series is fully reviewed
+ // instead of truncated on a small/local provider. Returns the chunk-corpus
+ // strings (one for a whole-fits provider) for an LLM check to iterate.
+ // Lives here (not the pure registry) because it resolves the provider.
+ planManuscriptChunks: async (stage, { overheadTokens = 0 } = {}) => {
+ if (!sections.length) return [];
+ const { contextWindow } = await resolveStageContext(stage, { providerOverride, modelOverride });
+ const plan = planManuscriptPass({
+ contextWindow,
+ // Each section's full contribution = header + body, matching sectionsCorpus.
+ sections: sections.map((s) => ({ ...s, text: `${manuscriptSectionHeader(s)}\n\n${s.content || ''}` })),
+ overheadTokens,
+ });
+ if (plan.mode === 'whole') return [manuscript.slice(0, plan.usableChars)];
+ return plan.chunks.map((c) => sectionsCorpus(c.sections).slice(0, plan.usableChars));
+ },
};
const findings = [];
diff --git a/server/services/pipeline/editorial/checkRunner.test.js b/server/services/pipeline/editorial/checkRunner.test.js
index 9a53343698..d805e797e8 100644
--- a/server/services/pipeline/editorial/checkRunner.test.js
+++ b/server/services/pipeline/editorial/checkRunner.test.js
@@ -17,6 +17,7 @@ vi.mock('../arcPlanner.js', () => ({
{ number: 1, title: 'Pilot', stageId: 'prose', content: 'As you know, Bob, the kingdom fell.' },
]),
sectionsCorpus: vi.fn((sections) => sections.map((s) => s.content).join('\n')),
+ manuscriptSectionHeader: vi.fn((s) => `# Issue ${s.number}`),
}));
vi.mock('../../../lib/stageRunner.js', () => ({
runStagedLLM: vi.fn(async () => ({
@@ -27,6 +28,8 @@ vi.mock('../../../lib/stageRunner.js', () => ({
],
},
})),
+ // A roomy window by default → manuscript LLM checks run in one whole-corpus call.
+ resolveStageContext: vi.fn(async () => ({ provider: { type: 'cli' }, model: 'm', contextWindow: 1_000_000 })),
}));
// A real-ish seed that applies the same checkId-aware dedup key the store uses,
@@ -44,7 +47,7 @@ const seedReviewFromFindings = vi.fn(async (_seriesId, findings) => {
vi.mock('../manuscriptReview.js', () => ({ seedReviewFromFindings: (...a) => seedReviewFromFindings(...a) }));
const { runEditorialChecks, buildEditorialCheckPlan } = await import('./checkRunner.js');
-const { runStagedLLM } = await import('../../../lib/stageRunner.js');
+const { runStagedLLM, resolveStageContext } = await import('../../../lib/stageRunner.js');
const { collectManuscriptSections } = await import('../arcPlanner.js');
const { listChecks } = await import('../../../lib/editorial/index.js');
@@ -61,6 +64,7 @@ beforeEach(() => {
seedStore.length = 0;
seedReviewFromFindings.mockClear();
runStagedLLM.mockClear();
+ resolveStageContext.mockClear();
collectManuscriptSections.mockClear();
});
@@ -135,6 +139,29 @@ describe('runEditorialChecks', () => {
expect(seedReviewFromFindings).not.toHaveBeenCalled();
});
+ it('chunks the manuscript per provider window and reviews every section (issue #1340)', async () => {
+ // Three big sections + a small context window → the manuscript can't fit in
+ // one call, so the runner chunks it. Every chunk must reach the model, so a
+ // long series is fully reviewed instead of truncated.
+ const big = (marker) => `${marker} ${'A'.repeat(12_000)}`;
+ collectManuscriptSections.mockResolvedValueOnce([
+ { number: 1, title: 'One', stageId: 'prose', content: big('SEC1') },
+ { number: 2, title: 'Two', stageId: 'prose', content: big('SEC2') },
+ { number: 3, title: 'Three', stageId: 'prose', content: big('SEC3') },
+ ]);
+ resolveStageContext.mockResolvedValueOnce({ provider: { type: 'api', endpoint: 'http://localhost:11434' }, model: 'm', contextWindow: 15_000 });
+
+ await runEditorialChecks('s1', { checkIds: ['prose.info-dumping'] });
+
+ // More than one model call ⇒ the corpus was split across the small window.
+ expect(runStagedLLM.mock.calls.length).toBeGreaterThan(1);
+ // Across all chunks, every section's content was sent to the model.
+ const allSent = runStagedLLM.mock.calls.map((c) => c[1].manuscript).join('\n');
+ expect(allSent).toContain('SEC1');
+ expect(allSent).toContain('SEC2');
+ expect(allSent).toContain('SEC3');
+ });
+
it('one failing check does not abort the pass', async () => {
// Make info-dumping the only enabled LLM check so the single rejection lands
// on it (the object LLM checks would otherwise consume the mockRejectedOnce).