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

make manuscript editorial passes context-window-aware (whole ↔ chunked)

[._.]/ Adam Eivy57783f8b1e83
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 6139651bc2..d184eb43d7 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,7 +2,8 @@
## Added
-- **[local-llm-large-narrative-models] Local LLM install picker now suggests a large narrative / long-context tier.** Added Mistral Large 2 123B, Command R+ 104B, Llama 3.3 70B, and Qwen3 30B-A3B to the curated catalog — workstation-class (64–128GB unified memory) models suited to whole-manuscript editorial review where prose quality and a long context window matter most. Verified Ollama pull ids and sizes; Qwen3 235B is intentionally omitted (142GB won't fit 128GB).
+- **[local-llm-large-narrative-models] Local LLM install picker now suggests a large narrative / long-context tier.** Added Mistral Large 2 123B, Command R+ 104B, Llama 3.3 70B, Qwen3 30B-A3B, and Google Gemma 4 (31B dense + 26B-A4B MoE, both 256K context, vision) to the curated catalog — workstation-class (64–128GB unified memory) models suited to whole-manuscript editorial review where prose quality and a long context window matter most. Verified Ollama pull ids and sizes; the Gemma 4 builds also ship MLX variants (`gemma4:31b-mlx` / `gemma4:26b-mlx`) for faster inference on Apple Silicon. Qwen3 235B is intentionally omitted (142GB won't fit 128GB).
+- **[context-aware-editorial-budgeting] Manuscript editorial passes now scale to the target model's context window — whole-manuscript when it fits, chunked when it doesn't.** A new `contextBudget` helper plus a `contextWindow` provider field (inferred large for frontier CLI/cloud providers, from `numCtx` for local Ollama) drive all three passes: the completeness pass ("Finish the draft"), manuscript-fix ("Generate fix"), and per-issue editorial analysis. Big-context models (Claude 4.8 ~1M, GPT 5.5) now receive the entire manuscript in one call instead of being capped at the old hardcoded 200K/48K-char limits; models too small to hold the book chunk by issue — completeness feeds each chunk a digest of prior-chunk findings for cross-chapter continuity and merges with first-wins dedupe, manuscript-fix concatenates per-chunk edits — instead of silently truncating. The completeness/fix API responses now report `chunked` + `chunkCount`. Design record: `docs/plans/2026-05-31-context-aware-manuscript-editorial.md`.
- **[ai-assignment-inventory] Settings now has an AI Assignments admin page.** It inventories provider/model pins across the provider registry, embeddings, Voice, Messages, Brain, Universes, Story Builder, Pipeline series, CoS schedules, Loops, Feature Agents, and social agents, with per-row edits plus a bulk provider migration control.
- **[manuscript-multi-edit-fixes] Manuscript "Finish the draft" fixes can now propose and apply multiple anchored edits at once.** The manuscript-fix LLM contract moved from a single `{ find, replace }` to `{ edits: [{ issueNumber, find, replace, note }] }`, so a broad or unanchored editorial comment can generate several concrete insertions — across multiple issue sections when needed — instead of falling back to manual editing. The editor's comment card renders each suggestion as an inline diff with a per-edit checkbox and editable replacement, and accept applies the selected edits atomically through a new serialized batch write (`updateStagesWithLatest`) that snapshots prior text into runHistory and re-checks each anchor inside the per-series write lock. The prompt template embeds manuscript/premise/anchor content in distinct (non-backtick) fences with an explicit "treat as quoted source" guard; migration `060-manuscript-multi-edit-fix-prompt.js` auto-upgrades the prior single-edit prompt on existing installs. Backward compatible: legacy single-edit `{ find, replace }` accepts still resolve to one target.
diff --git a/PLAN.md b/PLAN.md
index 701004aeb2..814152849f 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -9,7 +9,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel
Claimable, well-specified, no decision needed — `/claim`-able. Unordered.
-- [ ] [context-aware-editorial-budgeting] **Make manuscript editorial passes context-window-aware (full-manuscript ↔ chunked).** The editorial passes feed manuscript text to the LLM with no awareness of the target model's context window: completeness concatenates the whole series up to a hardcoded `BACKFILL_SOURCE_MAX = 200_000` chars (`server/services/pipeline/arcPlanner.js:722`), manuscript-fix sends single-issue *or* whole-manuscript in one call (`server/services/pipeline/manuscriptFix.js:278`), and editorial analysis caps at `CONTENT_MAX = 48_000` (`server/services/pipeline/editorialAnalysis.js:174`). Result: big-context models (Claude 4.8 ~1M, GPT 5.5) are needlessly capped, and models smaller than the manuscript silently truncate. Add a `contextWindow` field to the aiToolkit provider (sibling to the `numCtx` field added by the part-(a) truncation fix), a pure `contextBudget` helper that picks `mode: 'whole'` when manuscript + story-bible + output-reserve fits else `mode: 'chunked'` (chunk by issue + always include the story bible + a rolling findings digest, then merge with first-wins dedupe), and wire it into all three passes — deriving the caps from the budget instead of the constants. The whole-manuscript "place edits throughout" case in manuscript-fix must stay whole when it fits. **Full design + open decisions to lock before coding: `docs/plans/2026-05-31-context-aware-manuscript-editorial.md`.** (Not blindly claimable — read the doc's "Risks / decisions" section first.)
+- [ ] [editorial-chunk-count-ui] **Surface chunked-review coverage in the Manuscript Editor.** The editorial passes are now context-window-aware (`[context-aware-editorial-budgeting]`, shipped) and the completeness + fix API responses return `chunked` + `chunkCount`. The Manuscript Editor (`client/src/pages/PipelineManuscriptEditor.jsx`) doesn't yet show this — when a review ran in N chunks (small local model) vs. whole (big-context model), the user can't tell the coverage shape. Add a small badge/line near the review header reading e.g. "Reviewed in 4 chunks" (with a tooltip explaining a larger-context model reviews the whole manuscript at once) when `chunked` is true. Low risk, read-only display of an already-returned field. Design context: `docs/plans/2026-05-31-context-aware-manuscript-editorial.md`.
- [ ] [unify-media-job-sse-hook-imagegen-videogen] **Unify ImageGen + VideoGen SSE attach into `useMediaJobSse` hook.** Both pages now have near-duplicate EventSource handlers (ImageGen `startLocalGeneration` ~lines 655 + resume block ~317; VideoGen `attachJobEvents` ~line 450). Build a hook on top of `useSseProgress` (`client/src/hooks/useSseProgress.js`) that handles the queued / started / status / progress / complete / error / canceled SSE types and consolidate both sites.
- [ ] [capabilities-cheap-memory-count] **Capabilities route should count active memories without sorting/paginating.** `GET /api/capabilities` calls `getMemories({ status: 'active' })` (`server/routes/capabilities.js` ~line 69) only to read `.total`, but `getMemories` loads the full index, filters, sorts, and paginates before returning `{ total, memories }` — the sort + slice is wasted work on a page polled every ~20s. Add a lightweight `countMemories({ status })` (or a `countOnly` option) to `server/services/memory.js` that returns the filtered count without the sort/paginate, and switch the route to it. Micro-opt; the index is cached via `loadIndex`, so low urgency.
- [ ] [banner-icon-aria-hidden] **Apply `aria-hidden="true"` to `<Banner>`'s rendered icon.** `client/src/components/ui/Banner.jsx` (~line 62) renders the `icon` prop as a bare `<Icon …>` — when the icon is decorative (the body text already conveys the meaning), screen readers should skip it. Either wrap the icon render in `<span aria-hidden="true">` inside Banner, or thread an `iconAriaHidden` prop. Once landed, re-migrate the `ImportTab.jsx` error row to `<Banner tone="error" size="md" icon={AlertCircle} actions={…}>` (it was reverted from `<Banner>` because the icon prop doesn't pass through a11y attributes).
diff --git a/server/lib/README.md b/server/lib/README.md
index 6bb14404dd..fe74339518 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -83,6 +83,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `runners.js` | Image-runner family constants. |
| `codexAssistantExtract.js` | Strip Codex CLI banner + echoed metadata from session transcript. |
| `codexCliOutput.js` | Network/system error patterns for `agentErrorAnalysis.js`. |
+| `contextBudget.js` | Context-window budgeter for editorial passes. `estimateTokens` (chars/4), `usableInputTokens`, `planManuscriptPass({ contextWindow, sections })` → `{ mode: 'whole' \| 'chunked', chunks }`. Decides whole-manuscript vs chunked given a model's window. |
| `ansiStrip.js` | Streaming ANSI / control-byte stripper. |
| `hfToken.js` | HuggingFace token resolution (settings > env > CLI). |
| `hfCache.js` | HuggingFace Hub cache inspection (`inspectModelCache(repoId)` → `{cached,sizeBytes,snapshotPath}`, `isModelCached`, `getHfCacheRoot`). Drives the inline "Available / Download" badge on the image + video gen forms. |
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index 5e446ea435..2dad6d6d88 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -222,6 +222,7 @@ export function createProviderService(config = {}) {
fallbackProvider: providerData.fallbackProvider || null,
fallbackModel: providerData.fallbackModel || null,
numCtx: providerData.numCtx || null,
+ contextWindow: providerData.contextWindow || null,
timeout: providerData.timeout || 300000,
enabled: providerData.enabled !== false,
envVars: providerData.envVars || {},
diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.js
index 22273f99ef..91b4fdedc8 100644
--- a/server/lib/aiToolkit/validation.js
+++ b/server/lib/aiToolkit/validation.js
@@ -28,6 +28,10 @@ export const providerSchema = z.object({
// Per-request context window (Ollama num_ctx). Lifts the ~4K default so long
// prompts (e.g. a whole manuscript) aren't silently truncated. Null = unset.
numCtx: z.number().int().min(512).max(1048576).nullable().optional(),
+ // Planning-time context window (tokens) the editorial budgeter may assume for
+ // this provider — distinct from numCtx (what we *ask Ollama for*). For cloud
+ // providers numCtx stays null and this reflects the model's real ceiling.
+ contextWindow: z.number().int().min(512).max(2097152).nullable().optional(),
timeout: z.number().int().min(1000).max(1800000).optional(),
enabled: z.boolean().optional(),
envVars: z.record(z.string()).optional(),
diff --git a/server/lib/contextBudget.js b/server/lib/contextBudget.js
new file mode 100644
index 0000000000..7fb8b0cff6
--- /dev/null
+++ b/server/lib/contextBudget.js
@@ -0,0 +1,91 @@
+/**
+ * Context-window budgeter for manuscript editorial passes.
+ *
+ * The editorial passes (completeness, manuscript-fix, per-issue analysis) feed
+ * manuscript text to an LLM. Whether the whole manuscript fits in one call —
+ * or has to be chunked — depends on the target model's context window. This
+ * module makes that decision with a deliberately conservative heuristic: no
+ * tokenizer dependency (chars/4), combined with an output reserve and a safety
+ * margin, so a slight under-estimate never overflows the window.
+ *
+ * Pure / side-effect-free — unit-tested in contextBudget.test.js.
+ */
+
+export const CHARS_PER_TOKEN = 4;
+export const DEFAULT_OUTPUT_RESERVE_TOKENS = 8_000;
+export const DEFAULT_SAFETY_MARGIN = 0.1;
+// Conservative floor when a provider declares no usable window at all — matches
+// Ollama's historical default so we never plan for more than we can be sure of.
+export const FALLBACK_CONTEXT_WINDOW = 8_192;
+
+/** chars/4 token estimate. Conservative (real tokenizers pack denser). */
+export const estimateTokens = (text) => Math.ceil(String(text ?? '').length / CHARS_PER_TOKEN);
+
+const clampMargin = (m) => (Number.isFinite(m) && m >= 0 && m < 1 ? m : DEFAULT_SAFETY_MARGIN);
+
+const resolveWindow = (contextWindow) =>
+ (Number(contextWindow) > 0 ? Number(contextWindow) : FALLBACK_CONTEXT_WINDOW);
+
+/**
+ * Usable INPUT token budget for the manuscript text itself, after reserving
+ * output space, a safety margin, and any fixed prompt/context overhead
+ * (template scaffolding, canon JSON, the finding, etc.).
+ */
+export function usableInputTokens({
+ contextWindow,
+ overheadTokens = 0,
+ outputReserveTokens = DEFAULT_OUTPUT_RESERVE_TOKENS,
+ safetyMargin = DEFAULT_SAFETY_MARGIN,
+} = {}) {
+ const afterMargin = Math.floor(resolveWindow(contextWindow) * (1 - clampMargin(safetyMargin)));
+ return Math.max(0, afterMargin - Math.max(0, outputReserveTokens) - Math.max(0, overheadTokens));
+}
+
+/**
+ * Plan how to feed a multi-section manuscript to a model with a given window.
+ *
+ * @param sections - [{ ...meta, text }] where `text` is the section's full
+ * contribution to the corpus (header + body). Order is preserved.
+ * @returns
+ * { mode: 'whole', usableTokens, usableChars, totalTokens }
+ * { mode: 'chunked', usableTokens, usableChars, totalTokens,
+ * chunks: [{ sections, tokens }] }
+ *
+ * A single section larger than the usable budget becomes its own (over-budget)
+ * chunk — the caller truncates that chunk's text but it is never silently
+ * dropped. With ≤1 section the result is always `whole` (nothing to split).
+ */
+export function planManuscriptPass({
+ contextWindow,
+ sections,
+ overheadTokens = 0,
+ outputReserveTokens = DEFAULT_OUTPUT_RESERVE_TOKENS,
+ safetyMargin = DEFAULT_SAFETY_MARGIN,
+} = {}) {
+ const list = Array.isArray(sections) ? sections : [];
+ const usableTokens = usableInputTokens({ contextWindow, overheadTokens, outputReserveTokens, safetyMargin });
+ const usableChars = usableTokens * CHARS_PER_TOKEN;
+ const withTokens = list.map((s) => ({ section: s, tokens: estimateTokens(s?.text) }));
+ const totalTokens = withTokens.reduce((n, x) => n + x.tokens, 0);
+
+ if (list.length <= 1 || totalTokens <= usableTokens) {
+ return { mode: 'whole', usableTokens, usableChars, totalTokens };
+ }
+
+ // Greedy first-fit packing, order-preserving. Each chunk stays under the
+ // usable budget unless a single section already exceeds it (own chunk).
+ const chunks = [];
+ let cur = [];
+ let curTokens = 0;
+ for (const { section, tokens } of withTokens) {
+ if (cur.length && curTokens + tokens > usableTokens) {
+ chunks.push({ sections: cur, tokens: curTokens });
+ cur = [];
+ curTokens = 0;
+ }
+ cur.push(section);
+ curTokens += tokens;
+ }
+ if (cur.length) chunks.push({ sections: cur, tokens: curTokens });
+ return { mode: 'chunked', usableTokens, usableChars, totalTokens, chunks };
+}
diff --git a/server/lib/contextBudget.test.js b/server/lib/contextBudget.test.js
new file mode 100644
index 0000000000..12f3cb060c
--- /dev/null
+++ b/server/lib/contextBudget.test.js
@@ -0,0 +1,84 @@
+import { describe, it, expect } from 'vitest';
+import {
+ estimateTokens,
+ usableInputTokens,
+ planManuscriptPass,
+ CHARS_PER_TOKEN,
+ FALLBACK_CONTEXT_WINDOW,
+} from './contextBudget.js';
+
+const section = (n, chars) => ({ number: n, text: 'x'.repeat(chars) });
+
+describe('contextBudget', () => {
+ describe('estimateTokens', () => {
+ it('estimates chars/4, rounding up, and tolerates null', () => {
+ expect(estimateTokens('')).toBe(0);
+ expect(estimateTokens('abcd')).toBe(1);
+ expect(estimateTokens('abcde')).toBe(2);
+ expect(estimateTokens(null)).toBe(0);
+ expect(estimateTokens(undefined)).toBe(0);
+ });
+ });
+
+ describe('usableInputTokens', () => {
+ it('subtracts margin, output reserve, and overhead', () => {
+ // 100k window, 10% margin -> 90k; minus 8k reserve minus 2k overhead = 80k
+ expect(usableInputTokens({ contextWindow: 100_000, overheadTokens: 2_000 })).toBe(80_000);
+ });
+ it('falls back to the conservative window when none is declared', () => {
+ const u = usableInputTokens({ contextWindow: null, outputReserveTokens: 0, safetyMargin: 0 });
+ expect(u).toBe(FALLBACK_CONTEXT_WINDOW);
+ });
+ it('never goes negative when reserves exceed the window', () => {
+ expect(usableInputTokens({ contextWindow: 4_000, outputReserveTokens: 8_000 })).toBe(0);
+ });
+ it('clamps a nonsensical margin back to the default', () => {
+ // margin 2 (>1) is invalid -> default 0.1; 100k -> 90k - 8k = 82k
+ expect(usableInputTokens({ contextWindow: 100_000, safetyMargin: 2 })).toBe(82_000);
+ });
+ });
+
+ describe('planManuscriptPass', () => {
+ it('returns whole when the corpus fits the window', () => {
+ const plan = planManuscriptPass({
+ contextWindow: 1_000_000,
+ sections: [section(1, 4_000), section(2, 4_000)],
+ outputReserveTokens: 0,
+ safetyMargin: 0,
+ });
+ expect(plan.mode).toBe('whole');
+ expect(plan.totalTokens).toBe(2_000);
+ expect(plan.usableChars).toBe(plan.usableTokens * CHARS_PER_TOKEN);
+ });
+
+ it('returns whole for a single section even if it exceeds the window', () => {
+ const plan = planManuscriptPass({
+ contextWindow: 8_192,
+ sections: [section(1, 1_000_000)],
+ });
+ expect(plan.mode).toBe('whole');
+ });
+
+ it('chunks an over-budget multi-section corpus, preserving order and dropping nothing', () => {
+ // window 8192, margin 0, reserve 0 -> usable 8192 tokens = 32768 chars.
+ // four 5000-tok sections (20000 chars each) -> packs 1 per chunk (2 would be 10000 > 8192).
+ const sections = [section(1, 20_000), section(2, 20_000), section(3, 20_000), section(4, 20_000)];
+ const plan = planManuscriptPass({ contextWindow: 8_192, sections, outputReserveTokens: 0, safetyMargin: 0 });
+ expect(plan.mode).toBe('chunked');
+ const order = plan.chunks.flatMap((c) => c.sections.map((s) => s.number));
+ expect(order).toEqual([1, 2, 3, 4]);
+ expect(plan.chunks.length).toBe(4);
+ });
+
+ it('packs multiple small sections into one chunk up to the budget', () => {
+ // usable 8192 tokens; sections of 1000 tokens (4000 chars) each -> 8 fit per chunk
+ const sections = Array.from({ length: 10 }, (_, i) => section(i + 1, 4_000));
+ const plan = planManuscriptPass({ contextWindow: 8_192, sections, outputReserveTokens: 0, safetyMargin: 0 });
+ expect(plan.mode).toBe('chunked');
+ expect(plan.chunks[0].sections.length).toBe(8); // 8 * 1000 = 8000 <= 8192
+ expect(plan.chunks[1].sections.length).toBe(2);
+ const total = plan.chunks.reduce((n, c) => n + c.sections.length, 0);
+ expect(total).toBe(10);
+ });
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index e5da568906..228f53c998 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -66,6 +66,7 @@ export * from './cliProviderArgs.js';
export * from './cliProviderRun.js';
export * from './codexAssistantExtract.js';
export * from './codexCliOutput.js';
+export * from './contextBudget.js';
export * from './hfToken.js';
export * from './hfCache.js';
export * from './hfDownload.js';
diff --git a/server/lib/stageRunner.js b/server/lib/stageRunner.js
index 9c80fe71c7..57f8bd1487 100644
--- a/server/lib/stageRunner.js
+++ b/server/lib/stageRunner.js
@@ -84,6 +84,52 @@ export function resolveModel(provider, modelHint) {
return modelHint;
}
+// A conservative-large window assumed for frontier CLI / cloud-API providers
+// that haven't declared one. 128K is below every current frontier model's real
+// ceiling (Claude/GPT/Gemini are ≥128K, often ~1M), so it means "a typical
+// whole manuscript fits in one call" without over-promising. Users with very
+// large manuscripts can set an explicit `contextWindow` to lift it further.
+export const DEFAULT_LARGE_CONTEXT_WINDOW = 128_000;
+
+const LOCAL_ENDPOINT_RE = /^(https?:\/\/)?(localhost|127\.0\.0\.1|0\.0\.0\.0|\[?::1\]?)(:|\/|$)/i;
+const isLocalEndpoint = (endpoint) =>
+ typeof endpoint === 'string' && LOCAL_ENDPOINT_RE.test(endpoint.trim());
+
+// CLI/TUI providers (Claude Code, Codex, Antigravity) are frontier models;
+// non-local API providers are cloud. Local backends (ollama/lmstudio on
+// localhost) are the only genuinely small-window case.
+const isLikelyLargeContextProvider = (provider) => {
+ if (provider?.type === 'cli' || provider?.type === 'tui') return true;
+ if (provider?.type === 'api') return !isLocalEndpoint(provider.endpoint);
+ return false;
+};
+
+// Planning-time context window for a provider: an explicit `contextWindow`
+// wins, else the Ollama per-request `numCtx`, else a large default for frontier
+// providers, else null (the budgeter applies a conservative floor for unknown
+// local backends). Model-level windows can be layered in later.
+export function effectiveContextWindow(provider) {
+ if (Number(provider?.contextWindow) > 0) return Number(provider.contextWindow);
+ if (Number(provider?.numCtx) > 0) return Number(provider.numCtx);
+ if (isLikelyLargeContextProvider(provider)) return DEFAULT_LARGE_CONTEXT_WINDOW;
+ return null;
+}
+
+/**
+ * Resolve which provider/model a stage WOULD run against (without executing)
+ * plus its planning context window — for callers that must budget the prompt
+ * before building it (e.g. manuscript editorial chunking).
+ *
+ * Best-effort planning: this resolves the PRIMARY provider; a runtime fallback
+ * to a different (possibly smaller-window) provider is not reflected here.
+ */
+export async function resolveStageContext(stageName, options = {}) {
+ const stage = getStage(stageName);
+ const provider = await resolveProviderForStage(stage, options);
+ const model = resolveModel(provider, options.modelOverride || stage?.model);
+ return { provider, model, contextWindow: effectiveContextWindow(provider) };
+}
+
// Stage config can pin a specific provider via `stage.provider`. If set we
// must use it (or fail) — falling back to the active provider would route
// silently through whatever's currently selected, defeating the override.
diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.js
index 3e4ed09945..b7136433a1 100644
--- a/server/services/pipeline/arcPlanner.js
+++ b/server/services/pipeline/arcPlanner.js
@@ -19,7 +19,8 @@
* committing it (Phase 4's confirm-before-seeding pattern).
*/
-import { runStagedLLM } from '../../lib/stageRunner.js';
+import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';
+import { planManuscriptPass, estimateTokens } from '../../lib/contextBudget.js';
import { ServerError } from '../../lib/errorHandler.js';
import { stripAnsi } from '../../lib/ansiStrip.js';
import { getSeries, updateSeries, updateSeasonOnSeries, ARC_LOCKABLE_FIELDS, MANUSCRIPT_TYPES } from './series.js';
@@ -712,37 +713,130 @@ async function buildCompletenessContext(series, manuscript, preloadedWorld) {
};
}
+const COMPLETENESS_STAGE = 'pipeline-manuscript-completeness';
+// Output room for the findings list; comic-structure suggestions are full page
+// rewrites, so reserve generously.
+const COMPLETENESS_OUTPUT_RESERVE_TOKENS = 6_000;
+// Earlier-chapter findings summarized into the rolling digest fed to later
+// chunks, and the char cap on that digest (kept small so it fits the margin).
+const COMPLETENESS_PRIOR_DIGEST_MAX = 40;
+const COMPLETENESS_PRIOR_DIGEST_CHARS = 2_000;
+
+// Corpus string for a set of sections — byte-identical to collectIssueSourceText's
+// join so anchorQuote/find matching against the editor's per-section text holds.
+const sectionsCorpus = (sections) =>
+ sections.map((s) => `${manuscriptSectionHeader(s)}\n\n${s.content}`).join('\n\n---\n\n');
+
+// One-line digest of prior-chunk findings so later chunks keep cross-chapter
+// continuity in view. Rides INSIDE the manuscript field, so the prompt template
+// is unchanged (no migration).
+function priorFindingsDigest(findings) {
+ if (!findings.length) return '';
+ const lines = findings.slice(0, COMPLETENESS_PRIOR_DIGEST_MAX).map((f) => {
+ const where = Number.isInteger(f.issueNumber) ? `Issue ${f.issueNumber}` : (f.location || 'general');
+ return `- [${where}] ${f.category}: ${f.problem}`;
+ });
+ const more = findings.length > COMPLETENESS_PRIOR_DIGEST_MAX
+ ? `\n(+${findings.length - COMPLETENESS_PRIOR_DIGEST_MAX} more earlier findings)` : '';
+ const body = `${lines.join('\n')}${more}`.slice(0, COMPLETENESS_PRIOR_DIGEST_CHARS);
+ return `# Editorial findings already recorded for EARLIER chapters\n`
+ + `Do not repeat these. Flag only NEW gaps in the chapters below, plus any cross-chapter `
+ + `continuity problems these earlier findings reveal.\n\n${body}\n\n---\n\n`;
+}
+
+// First-wins dedupe across chunks — a finding the same on (issue, category,
+// anchor, problem) is recorded once even if two chunks surface it.
+const findingKey = (f) => [
+ f.issueNumber ?? '',
+ f.category,
+ (f.anchorQuote || '').trim().toLowerCase().slice(0, 120),
+ (f.problem || '').trim().toLowerCase().slice(0, 120),
+].join('|');
+
+function mergeFindingGroups(groups) {
+ const seen = new Set();
+ const out = [];
+ for (const group of groups) {
+ for (const f of group) {
+ const k = findingKey(f);
+ if (seen.has(k)) continue;
+ seen.add(k);
+ out.push(f);
+ }
+ }
+ return out;
+}
+
/**
* Editor pass over the drafted manuscript itself: returns categorized
* suggestions for rounding out and finishing a near-complete draft — missing
* pages/beats, arc holes, and character-development gaps. Read-only; advisory
* (no auto-resolve). Complements verifyArc/verifyVolume, which stay at synopsis
* depth and never see the script.
+ *
+ * Context-window-aware: when the whole manuscript + canon context fits the
+ * target model's window it runs in one call (frontier models hold the entire
+ * book); otherwise it chunks by issue, feeds each chunk a digest of prior-chunk
+ * findings for continuity, and merges with first-wins dedupe.
*/
export async function analyzeManuscriptCompleteness(seriesId, options = {}) {
const series = await getSeries(seriesId);
// Manuscript-only: exclude `idea` so an outline/synopsis seed can't pass the
// guard below and get graded as if it were a drafted manuscript.
- const manuscript = await collectIssueSourceText(seriesId, { stageOrder: MANUSCRIPT_STAGES });
- if (!manuscript) {
+ const sections = await collectManuscriptSections(seriesId, { stageOrder: MANUSCRIPT_STAGES });
+ if (!sections.length) {
throw makeErr(
'No manuscript to analyze — write a comic script, prose, or teleplay on at least one issue first',
ERR_VALIDATION,
);
}
- const ctx = await buildCompletenessContext(series, manuscript, options.preloadedWorld);
- const { content, runId, providerId, model } = await runStagedLLM(
- 'pipeline-manuscript-completeness',
- ctx,
- {
- providerOverride: options.providerOverride,
- modelOverride: options.modelOverride,
- returnsJson: true,
- source: 'pipeline-manuscript-completeness',
- },
- );
- const issues = shapeCompletenessFindings(content?.issues);
- return { issues, raw: content, runId, providerId, model };
+
+ // Base (non-manuscript) context is fixed overhead present in every call.
+ const baseCtx = await buildCompletenessContext(series, '', options.preloadedWorld);
+ const overheadTokens = estimateTokens(JSON.stringify(baseCtx)) + 2_000; // + template/instructions
+ const { contextWindow } = await resolveStageContext(COMPLETENESS_STAGE, {
+ providerOverride: options.providerOverride,
+ modelOverride: options.modelOverride,
+ });
+ const plan = planManuscriptPass({
+ contextWindow,
+ sections: sections.map((s) => ({ ...s, text: `${manuscriptSectionHeader(s)}\n\n${s.content}` })),
+ overheadTokens,
+ outputReserveTokens: COMPLETENESS_OUTPUT_RESERVE_TOKENS,
+ });
+
+ const runOne = (manuscript) => runStagedLLM(COMPLETENESS_STAGE, { ...baseCtx, manuscript }, {
+ providerOverride: options.providerOverride,
+ modelOverride: options.modelOverride,
+ returnsJson: true,
+ source: 'pipeline-manuscript-completeness',
+ });
+
+ if (plan.mode === 'whole') {
+ const { content, runId, providerId, model } = await runOne(sectionsCorpus(sections).slice(0, plan.usableChars));
+ return { issues: shapeCompletenessFindings(content?.issues), raw: content, runId, providerId, model, chunked: false, chunkCount: 1 };
+ }
+
+ console.log(`📚 completeness: chunked review series=${String(seriesId).slice(0, 12)} chunks=${plan.chunks.length} window=${contextWindow ?? 'floor'}`);
+ const groups = [];
+ let first = null;
+ for (const chunk of plan.chunks) {
+ const digest = priorFindingsDigest(mergeFindingGroups(groups));
+ const corpus = sectionsCorpus(chunk.sections).slice(0, plan.usableChars);
+ const result = await runOne(`${digest}${corpus}`);
+ if (!first) first = result;
+ groups.push(shapeCompletenessFindings(result.content?.issues));
+ }
+ const issues = mergeFindingGroups(groups);
+ return {
+ issues,
+ raw: { issues },
+ runId: first?.runId,
+ providerId: first?.providerId,
+ model: first?.model,
+ chunked: true,
+ chunkCount: plan.chunks.length,
+ };
}
// Reader-map context: the protagonist arc + the Vonnegut shape backbone + the
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index 5c6bd4fae9..94f50a0483 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -3,6 +3,7 @@ import { mockNoPeerSync, mockNoPeers } from '../../lib/mockPathsDataRoot.js';
const fileStore = new Map();
let stageRunnerSpy;
+let stageContextSpy;
vi.mock('../../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
@@ -26,6 +27,11 @@ vi.mock('../sharing/peerSync.js', () => mockNoPeerSync());
vi.mock('../../lib/stageRunner.js', () => ({
runStagedLLM: vi.fn((...args) => stageRunnerSpy(...args)),
extractJson: (raw) => JSON.parse(raw),
+ // Large window by default so completeness runs as a single call (mode:
+ // 'whole'); a test can set `stageContextSpy` to force a small window.
+ resolveStageContext: vi.fn((...args) => (stageContextSpy
+ ? stageContextSpy(...args)
+ : Promise.resolve({ provider: { id: 'p' }, model: 'm', contextWindow: 1_000_000 }))),
}));
const seriesSvc = await import('./series.js');
@@ -1483,6 +1489,7 @@ describe('arcPlanner — manuscript completeness + derive-from-manuscript', () =
fileStore.clear();
uuidCounter = 0;
stageRunnerSpy = undefined;
+ stageContextSpy = undefined;
});
it('issueSynopsisFromSeason joins logline + synopsis (and is empty for nothing)', () => {
@@ -1525,6 +1532,41 @@ describe('arcPlanner — manuscript completeness + derive-from-manuscript', () =
const out = await planner.analyzeManuscriptCompleteness(s.id);
expect(out.issues).toHaveLength(1);
expect(out.issues[0]).toMatchObject({ category: 'arc-gap', severity: 'high' });
+ expect(out.chunked).toBe(false);
+ });
+
+ it('chunks a large manuscript that exceeds the model window and merges findings (first-wins dedupe + prior-findings digest)', async () => {
+ const s = await setupSeries();
+ const big = 'word '.repeat(12_000); // ~60k chars (~15k tokens) per issue
+ await issuesSvc.createIssue({ seriesId: s.id, title: 'One', arcPosition: 1, stages: { prose: { output: `ONE ${big}`, status: 'ready' } } });
+ await issuesSvc.createIssue({ seriesId: s.id, title: 'Two', arcPosition: 2, stages: { prose: { output: `TWO ${big}`, status: 'ready' } } });
+ await issuesSvc.createIssue({ seriesId: s.id, title: 'Three', arcPosition: 3, stages: { prose: { output: `THREE ${big}`, status: 'ready' } } });
+ stageContextSpy = vi.fn(async () => ({ provider: { id: 'p' }, model: 'm', contextWindow: 40_000 }));
+ let n = 0;
+ stageRunnerSpy = vi.fn(async () => {
+ n += 1;
+ return {
+ content: { issues: [
+ // same finding surfaced by every chunk — must be recorded once
+ { severity: 'high', category: 'arc-gap', issueNumber: 1, anchorQuote: 'dup', problem: 'duplicated finding', suggestion: 'x' },
+ { severity: 'low', category: 'pacing', problem: `unique ${n}`, suggestion: '' },
+ ] },
+ runId: `r${n}`, providerId: 'p', model: 'm',
+ };
+ });
+
+ const out = await planner.analyzeManuscriptCompleteness(s.id);
+
+ expect(out.chunked).toBe(true);
+ expect(out.chunkCount).toBeGreaterThanOrEqual(2);
+ expect(stageRunnerSpy).toHaveBeenCalledTimes(out.chunkCount);
+ // duplicate finding collapsed to one; each chunk's unique finding kept
+ expect(out.issues.filter((f) => f.anchorQuote === 'dup')).toHaveLength(1);
+ expect(out.issues.filter((f) => f.problem.startsWith('unique'))).toHaveLength(out.chunkCount);
+ // later chunks get a digest of earlier findings inside the manuscript field
+ const secondManuscript = stageRunnerSpy.mock.calls[1][1].manuscript;
+ expect(secondManuscript).toContain('already recorded for EARLIER chapters');
+ expect(secondManuscript).toContain('duplicated finding');
});
it('analyzeManuscriptCompleteness refuses when no manuscript exists', async () => {
diff --git a/server/services/pipeline/editorialAnalysis.js b/server/services/pipeline/editorialAnalysis.js
index 6e27dc4804..df2d5375e2 100644
--- a/server/services/pipeline/editorialAnalysis.js
+++ b/server/services/pipeline/editorialAnalysis.js
@@ -18,7 +18,8 @@
import { join } from 'path';
import { createHash } from 'crypto';
import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';
-import { runStagedLLM } from '../../lib/stageRunner.js';
+import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';
+import { usableInputTokens, estimateTokens, CHARS_PER_TOKEN } from '../../lib/contextBudget.js';
import { getIssue, listIssues } from './issues.js';
import { getSeries } from './series.js';
import { getSeriesCanon } from './seriesCanon.js';
@@ -40,8 +41,12 @@ const NOTE_MAX = 500;
// malformed response that extractJson rejects (it throws "Invalid JSON in AI
// response", surfacing as an analysis error rather than a silent empty
// snapshot). ~48K chars (~12K tokens) leaves ample room for the prompt + a
-// heavy-tier reply.
+// heavy-tier reply. This is a FLOOR — the real cap scales up to the target
+// model's context window (see analyzeIssue), so a big-context model isn't
+// needlessly truncated to 48K.
const CONTENT_MAX = 48_000;
+// Output reserve for the analysis JSON (sections + character arcs).
+const ANALYSIS_OUTPUT_RESERVE_TOKENS = 4_000;
const nowIso = () => new Date().toISOString();
@@ -188,6 +193,20 @@ export async function analyzeIssue(issueId, { providerId, model, force = false }
const characterNames = (canon.characters || []).map((c) => c?.name).filter(Boolean).slice(0, 40);
const arc = series?.arc || null;
+ // Scale the content cap to the target model's context window — never below
+ // CONTENT_MAX (so we never truncate more than before), but a big-context
+ // model gets the whole issue instead of a 48K slice.
+ const { contextWindow } = await resolveStageContext(STAGE, { providerOverride: providerId, modelOverride: model });
+ const overheadTokens = 1_500 + estimateTokens(
+ [characterNames.join(', '), arc?.protagonistArc || '', (arc?.themes || []).join(', ')].join(' '),
+ );
+ const budgetChars = usableInputTokens({
+ contextWindow,
+ overheadTokens,
+ outputReserveTokens: ANALYSIS_OUTPUT_RESERVE_TOKENS,
+ }) * CHARS_PER_TOKEN;
+ const contentMax = Math.max(CONTENT_MAX, budgetChars);
+
const ctx = {
series: { name: series?.name || 'Untitled series', logline: series?.logline || '' },
issue: { number: issue.number, title: issue.title, arcRole: issue.arcRole || '' },
@@ -201,8 +220,8 @@ export async function analyzeIssue(issueId, { providerId, model, force = false }
knownCharacters: characterNames.join(', '),
format: picked.sourceStage === 'comicScript' ? 'comic script'
: picked.sourceStage === 'teleplay' ? 'teleplay' : 'prose',
- content: picked.text.length > CONTENT_MAX
- ? `${picked.text.slice(0, CONTENT_MAX)}\n\n[content truncated for analysis — ${picked.text.length} chars total]`
+ content: picked.text.length > contentMax
+ ? `${picked.text.slice(0, contentMax)}\n\n[content truncated for analysis — ${picked.text.length} chars total]`
: picked.text,
};
diff --git a/server/services/pipeline/editorialAnalysis.test.js b/server/services/pipeline/editorialAnalysis.test.js
index f396373b24..51146757a1 100644
--- a/server/services/pipeline/editorialAnalysis.test.js
+++ b/server/services/pipeline/editorialAnalysis.test.js
@@ -20,6 +20,8 @@ vi.mock('../../lib/stageRunner.js', () => ({
const content = llmQueue.shift();
return { content, model: 'mock-model', providerId: 'mock-provider', runId: 'run-1' };
}),
+ // Large window so the content cap stays at its CONTENT_MAX floor in tests.
+ resolveStageContext: vi.fn(async () => ({ provider: { id: 'mock-provider' }, model: 'mock-model', contextWindow: 1_000_000 })),
}));
// Fixture issue/series stores.
diff --git a/server/services/pipeline/manuscriptEditor.test.js b/server/services/pipeline/manuscriptEditor.test.js
index 1b7a898868..9574d9f8d5 100644
--- a/server/services/pipeline/manuscriptEditor.test.js
+++ b/server/services/pipeline/manuscriptEditor.test.js
@@ -24,6 +24,8 @@ vi.mock('../sharing/peerSync.js', () => mockNoPeerSync());
vi.mock('../../lib/stageRunner.js', () => ({
runStagedLLM: vi.fn((...args) => stageRunnerSpy(...args)),
extractJson: (raw) => JSON.parse(raw),
+ // Large window so manuscript-fix runs as a single call (mode: 'whole').
+ resolveStageContext: vi.fn(async () => ({ provider: { id: 'p' }, model: 'm', contextWindow: 1_000_000 })),
}));
const seriesSvc = await import('./series.js');
diff --git a/server/services/pipeline/manuscriptFix.js b/server/services/pipeline/manuscriptFix.js
index ce8e9cb7d5..c65c4f6c64 100644
--- a/server/services/pipeline/manuscriptFix.js
+++ b/server/services/pipeline/manuscriptFix.js
@@ -13,7 +13,8 @@
*/
import { randomUUID } from 'crypto';
-import { runStagedLLM } from '../../lib/stageRunner.js';
+import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';
+import { planManuscriptPass, estimateTokens } from '../../lib/contextBudget.js';
import { getSeries, MANUSCRIPT_TYPES } from './series.js';
import { getIssue, updateStageWithLatest, updateStagesWithLatest } from './issues.js';
import { collectManuscriptSections, stageVersionsOf } from './arcPlanner.js';
@@ -275,6 +276,34 @@ export async function saveManuscriptSection(seriesId, { issueId, stageId, output
* can't be located verbatim in the current stage text, that edit is flagged
* `fuzzy: true` so the client can warn before apply.
*/
+const FIX_STAGE = 'pipeline-manuscript-fix';
+// Output room for the edits list (each `replace` can be a full page rewrite).
+const FIX_OUTPUT_RESERVE_TOKENS = 6_000;
+
+// Merge per-chunk fixes into one, concatenating edits with first-wins dedupe on
+// (issue, stage, find, replace), and rebuilding the single-edit convenience
+// fields normalizeFix sets so the accept path stays uniform.
+function mergeFixes(fixes) {
+ const edits = [];
+ const seen = new Set();
+ for (const fx of fixes) {
+ for (const e of (fx?.edits || [])) {
+ const k = `${e.issueId}|${e.stageId}|${e.find}|${e.replace}`;
+ if (seen.has(k)) continue;
+ seen.add(k);
+ edits.push(e);
+ }
+ }
+ if (edits.length === 0) return null;
+ const fix = { edits };
+ if (edits.length === 1) {
+ fix.find = edits[0].find;
+ fix.replace = edits[0].replace;
+ if (edits[0].fuzzy) fix.fuzzy = true;
+ }
+ return fix;
+}
+
export async function generateManuscriptFix(seriesId, { commentId, providerOverride, modelOverride } = {}) {
const series = await getSeries(seriesId);
const comment = await getComment(seriesId, commentId);
@@ -286,21 +315,12 @@ export async function generateManuscriptFix(seriesId, { commentId, providerOverr
}
const arc = series.arc || {};
- const manuscript = manuscriptTextOf(targets);
- const ctx = {
+ const baseCtx = {
series: { name: series.name, logline: series.logline, premise: series.premise },
arc: {
logline: arc.logline || '',
themesCsv: Array.isArray(arc.themes) ? arc.themes.join(', ') : '',
},
- scope: targets.length === 1 ? sectionLabel(targets[0]) : 'Full manuscript',
- sections: targets.map((s) => ({
- issueNumber: s.number,
- title: s.title || '',
- stageId: s.stageId,
- manuscript: s.content || '',
- })),
- manuscript,
finding: {
category: comment.category,
severity: comment.severity,
@@ -309,19 +329,66 @@ export async function generateManuscriptFix(seriesId, { commentId, providerOverr
anchorQuote: comment.anchorQuote,
},
};
-
- const { content, runId } = await runStagedLLM('pipeline-manuscript-fix', ctx, {
+ const buildCtx = (sections) => ({
+ ...baseCtx,
+ scope: sections.length === 1 ? sectionLabel(sections[0]) : 'Full manuscript',
+ sections: sections.map((s) => ({
+ issueNumber: s.number,
+ title: s.title || '',
+ stageId: s.stageId,
+ manuscript: s.content || '',
+ })),
+ manuscript: manuscriptTextOf(sections),
+ });
+ const runChunk = (sections) => runStagedLLM(FIX_STAGE, buildCtx(sections), {
providerOverride,
modelOverride,
returnsJson: true,
source: 'pipeline-manuscript-fix',
});
- const fix = normalizeFix(content, targets);
+ // A whole-manuscript fix (unanchored/structural comment) must place edits
+ // across the whole book — so we keep it whole when it fits the model's
+ // window, and only chunk by issue (degrading the holistic view) when it
+ // can't. Single-issue comments are always one section → always whole.
+ const { contextWindow } = await resolveStageContext(FIX_STAGE, { providerOverride, modelOverride });
+ const overheadTokens = estimateTokens(JSON.stringify(baseCtx)) + 2_000;
+ const plan = planManuscriptPass({
+ contextWindow,
+ sections: targets.map((s) => ({ ...s, text: `${manuscriptSectionHeader(s)}\n\n${s.content || ''}` })),
+ overheadTokens,
+ outputReserveTokens: FIX_OUTPUT_RESERVE_TOKENS,
+ });
+
+ let fix;
+ let runId;
+ if (plan.mode === 'whole') {
+ const r = await runChunk(targets);
+ fix = normalizeFix(r.content, targets);
+ runId = r.runId;
+ } else {
+ console.log(`📚 manuscript-fix: chunked series=${String(seriesId).slice(0, 12)} chunks=${plan.chunks.length} window=${contextWindow ?? 'floor'}`);
+ const fixes = [];
+ let first = null;
+ for (const chunk of plan.chunks) {
+ const r = await runChunk(chunk.sections);
+ if (!first) first = r;
+ const f = normalizeFix(r.content, chunk.sections);
+ if (f) fixes.push(f);
+ }
+ fix = mergeFixes(fixes);
+ runId = first?.runId;
+ }
if (!fix) throw makeErr('The model did not return a usable fix — try again', ERR_VALIDATION);
const updated = await updateComment(seriesId, commentId, { fix });
- return { comment: updated, fix, runId };
+ return {
+ comment: updated,
+ fix,
+ runId,
+ chunked: plan.mode === 'chunked',
+ chunkCount: plan.mode === 'whole' ? 1 : plan.chunks.length,
+ };
}
/**