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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: guarantee a manuscript budget floor so large outline/context overhead can't starve the manuscript chunk (#1459)
Adam Eivy0b7fe2a21393
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 214ad004ac..51206bdaed 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,9 @@# Next Release+## Fixed++- **[issue-1459] Editorial LLM checks now guarantee a manuscript budget floor, so a large reverse outline can't starve the manuscript chunk to empty.** The manuscript-consuming editorial checks re-send a fixed context block (the reverse-outline scene map, character arcs, plotline coverage, style-guide expectations, …) on every chunk, counted as `overheadTokens`. On a provider with a small or fallback context window **and** a large reverse outline (many scenes → a large scene map), that overhead could meet or exceed the usable input budget — `planManuscriptPass` then returned `usableChars = 0` and the chunker sliced every manuscript chunk to `''`, so a default-enabled check silently ran on **no prose**. A check now declares its trimmable context as a `context: { varName }` map (instead of baking it into `overheadTokens`); the runner reserves a minimum manuscript budget (`MANUSCRIPT_FLOOR_TOKENS`) and, when the context would push the manuscript below that floor, **trims the context block** (largest first, so the unbounded scene map absorbs the cut while bounded blocks survive) and feeds the model the same trimmed block it was budgeted for — rather than overflowing the window or reviewing an empty manuscript. The floor decision lives centrally in `contextBudget.js` (`fitContextToManuscriptFloor`/`capContextOverhead`/`trimContextToBudget`), so every manuscript+context check benefits. Unit-tested end-to-end: a tiny window + a 400-scene outline still yields a non-empty manuscript chunk. (`server/lib/contextBudget.js`, `server/services/pipeline/editorial/checkRunner.js`, `server/lib/editorial/checkRegistry.js`, #1459)+## Added- **[issue-1408] LoRA training quality-of-life: vision-assisted reference-sheet slicing, caption with Claude/Codex CLI providers, and a richer training queue.** Three improvements to building character LoRAs (Create → LoRA Training). **(1) Smarter sheet slicing** — "Slice reference sheet" now offers *Auto-detect figures with a vision model*, which asks a vision model to draw a tight box around each figure on the turnaround and crops those instead of a rigid grid; it falls back to the columns×rows grid automatically when no vision model is installed or detection finds nothing, so you still get crops to prune either way. **(2) Caption with a CLI model** — the caption-model picker now also lists vision-capable CLI providers (Codex / Claude Code), so you can auto-caption a dataset with `codex` or `claude` (vision) rather than only a local LM Studio / Ollama vision model. **(3) Training queue at a glance** — the new Training queue on the LoRA Training page shows each run's loss curve (a sparkline over its checkpoints) and sample thumbnails right in the row, so you can watch a run learn — and spot a divergence — without opening it. (Part of #1227, #1408)diff --git a/server/lib/README.md b/server/lib/README.mdindex f1db758596..ecb9ef3aeb 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -92,7 +92,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. |+| `contextBudget.js` | Context-window budgeter for editorial passes. `estimateTokens` (chars/4), `usableInputTokens`, `planManuscriptPass({ contextWindow, sections })` → `{ mode: 'whole' \| 'chunked', chunks }`. Also `fitContextToManuscriptFloor`/`capContextOverhead`/`trimContextToBudget` — trim a re-sent context block (scene map, character arcs, …) so a large reverse outline on a small window can't starve the manuscript chunk below a budget floor (#1459). 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). || `hfErrors.js` | Parse huggingface_hub gated-access errors: `extractGatedRepo(text)` → `owner/name` (or null) for the UI's license deep-link. Shared by the image runner and LoRA trainer. Pure. |diff --git a/server/lib/contextBudget.js b/server/lib/contextBudget.jsindex d182a89adb..2268489107 100644--- a/server/lib/contextBudget.js+++ b/server/lib/contextBudget.js@@ -16,6 +16,20 @@ import { chunkRawText } from './catalogChunking.js';export const CHARS_PER_TOKEN = 4;export const DEFAULT_OUTPUT_RESERVE_TOKENS = 8_000;export const DEFAULT_SAFETY_MARGIN = 0.1;+// Minimum manuscript token budget a chunked editorial pass guarantees, even when a+// large re-sent context block (the reverse-outline scene map, character arcs,+// plotline coverage, …) would otherwise consume the whole usable window. A+// manuscript-consuming LLM check re-sends its fixed context as `overheadTokens` on+// every chunk; on a small/fallback window + a large reverse outline that overhead+// can meet or exceed the usable input budget, slicing the manuscript chunk to ''+// so a default-enabled check runs on NO prose (#1459). The floor reserves at least+// this many tokens for the manuscript by trimming the (bounded) context+// contribution — manuscript text keeps budget priority over re-sent context.+// ~6K chars: a few paragraphs, enough for the model to find something per chunk.+export const MANUSCRIPT_FLOOR_TOKENS = 1_500;+// Marker appended to a context block that had to be clipped, so the model can tell+// the context was truncated rather than genuinely ending there.+const CONTEXT_TRIM_MARKER = '\n…[context trimmed to fit the model window]…';// 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;@@ -49,6 +63,141 @@ export function usableInputTokens({return Math.max(0, afterMargin - Math.max(0, outputReserveTokens) - Math.max(0, overheadTokens));}+/**+ * Decide how much of a re-sent context block (the reverse-outline scene map,+ * character arcs, plotline coverage, …) a chunked manuscript pass can afford,+ * guaranteeing the manuscript itself at least `floorTokens` of input budget.+ *+ * A manuscript-consuming LLM check re-sends a fixed context block as overhead on+ * every chunk. On a small/fallback window + a large reverse outline that overhead+ * can meet or exceed the usable input budget, slicing the manuscript chunk to ''+ * so a default-enabled check runs on no prose (#1459). This caps the context+ * contribution so the manuscript keeps `floorTokens` of priority. `fixedOverhead`+ * (the prompt template scaffolding + the finding JSON contract — NOT trimmable) is+ * always reserved; only `contextTokens` (the trimmable block) is squeezed.+ *+ * Returns the allowed context budget as both tokens and chars (chars/4). Never+ * returns more than the context already needs, and never less than 0. When the+ * window comfortably fits everything the input is unchanged (`allowedContextTokens+ * === contextTokens`, `trimmed === false`).+ */+export function capContextOverhead({+ contextWindow,+ contextTokens = 0,+ fixedOverheadTokens = 0,+ outputReserveTokens = DEFAULT_OUTPUT_RESERVE_TOKENS,+ safetyMargin = DEFAULT_SAFETY_MARGIN,+ floorTokens = MANUSCRIPT_FLOOR_TOKENS,+} = {}) {+ const wantContext = Math.max(0, contextTokens);+ const floor = Math.max(0, floorTokens);+ // Budget left for INPUT (manuscript + trimmable context) after the fixed,+ // non-trimmable overhead — but NOT subtracting the trimmable context (that's+ // what we're sizing). usableInputTokens already floors at 0.+ const inputBudget = usableInputTokens({+ contextWindow,+ overheadTokens: fixedOverheadTokens,+ outputReserveTokens,+ safetyMargin,+ });+ // Reserve the manuscript floor first (but never go negative), then let context+ // have whatever's left — capped at what it actually wants.+ const allowedContextTokens = Math.min(wantContext, Math.max(0, inputBudget - floor));+ return {+ allowedContextTokens,+ allowedContextChars: allowedContextTokens * CHARS_PER_TOKEN,+ trimmed: allowedContextTokens < wantContext,+ };+}++/**+ * Trim a context string to fit `maxChars`, preferring a newline boundary so a+ * line-oriented block (the scene map, plotline coverage) is cut between lines, and+ * appending a marker so the model knows the context was truncated. A string within+ * budget passes through unchanged; a 0/negative budget yields ''. Pure — no I/O.+ */+export function trimContextToBudget(text, maxChars) {+ const s = String(text ?? '');+ const cap = Math.max(0, Math.floor(maxChars));+ if (s.length <= cap) return s;+ if (cap <= CONTEXT_TRIM_MARKER.length) return '';+ const bodyBudget = cap - CONTEXT_TRIM_MARKER.length;+ const slice = s.slice(0, bodyBudget);+ // Prefer cutting at the last newline so a line-structured block stays coherent,+ // but only if that doesn't throw away most of the budget.+ const lastNl = slice.lastIndexOf('\n');+ const body = lastNl > bodyBudget * 0.5 ? slice.slice(0, lastNl) : slice;+ return `${body}${CONTEXT_TRIM_MARKER}`;+}++/**+ * Trim a map of re-sent context blocks so they fit a manuscript-floor budget for+ * `contextWindow`, and report the overhead the (trimmed) context now costs. This is+ * the single place that decides the floor (#1459): a manuscript-consuming editorial+ * check re-sends these blocks (scene map, character arcs, plotline coverage, …) on+ * every chunk, so on a small/fallback window + a large reverse outline they can+ * consume the whole usable budget and slice the manuscript chunk to ''. Here we cap+ * the context's token contribution (`capContextOverhead`) and actually shrink the+ * strings (`trimContextToBudget`) so the manuscript keeps `floorTokens` of priority+ * AND the rendered prompt still fits the window (capping the token math without+ * shrinking the strings would overflow the real prompt).+ *+ * The LARGEST blocks are trimmed first — the issue's analysis is that `sceneMap`+ * grows unbounded with scene count while the others (plotlineMap, character arcs)+ * are bounded — so the bounded context survives and the unbounded one absorbs the+ * cut. Each block degrades gracefully when trimmed (the checks already handle an+ * absent block), and trimming is strictly better than feeding the model no prose.+ *+ * @param context - { [varName]: string } of trimmable context blocks (non-strings+ * are coerced; an empty / non-object input yields `{}` and no trimming).+ * @returns { context: { [varName]: string } (trimmed copy),+ * overheadTokens: number (fixedOverheadTokens + trimmed context tokens),+ * trimmed: boolean }+ */+export function fitContextToManuscriptFloor(context, {+ contextWindow,+ fixedOverheadTokens = 0,+ outputReserveTokens = DEFAULT_OUTPUT_RESERVE_TOKENS,+ safetyMargin = DEFAULT_SAFETY_MARGIN,+ floorTokens = MANUSCRIPT_FLOOR_TOKENS,+} = {}) {+ const entries = context && typeof context === 'object' ? Object.entries(context) : [];+ const blocks = {};+ for (const [k, v] of entries) blocks[k] = String(v ?? '');+ const fixed = Math.max(0, fixedOverheadTokens);++ const contextTokens = entries.reduce((n, [k]) => n + estimateTokens(blocks[k]), 0);+ const { allowedContextChars, trimmed } = capContextOverhead({+ contextWindow,+ contextTokens,+ fixedOverheadTokens: fixed,+ outputReserveTokens,+ safetyMargin,+ floorTokens,+ });++ if (!trimmed) {+ return { context: blocks, overheadTokens: fixed + contextTokens, trimmed: false };+ }++ // Trim the largest blocks first until the combined context fits the allowed+ // budget. `need` is the chars we must remove; each pass shrinks the current+ // largest block toward (its size − need), so a single dominant block (sceneMap)+ // absorbs the whole cut and the bounded blocks survive intact.+ const totalChars = entries.reduce((n, [k]) => n + blocks[k].length, 0);+ let need = totalChars - allowedContextChars;+ const largestFirst = entries.map(([k]) => k).sort((a, b) => blocks[b].length - blocks[a].length);+ for (const k of largestFirst) {+ if (need <= 0) break;+ const before = blocks[k].length;+ blocks[k] = trimContextToBudget(blocks[k], Math.max(0, before - need));+ need -= before - blocks[k].length;+ }++ const trimmedContextTokens = entries.reduce((n, [k]) => n + estimateTokens(blocks[k]), 0);+ return { context: blocks, overheadTokens: fixed + trimmedContextTokens, trimmed: true };+}+/*** Expand one section into `{ section, tokens }` units that each fit the usable* budget. A section within budget passes through unchanged. An over-budgetdiff --git a/server/lib/contextBudget.test.js b/server/lib/contextBudget.test.jsindex 6374ffe1dc..a6bcd0f2cd 100644--- a/server/lib/contextBudget.test.js+++ b/server/lib/contextBudget.test.js@@ -3,8 +3,12 @@ import {estimateTokens,usableInputTokens,planManuscriptPass,+ capContextOverhead,+ trimContextToBudget,+ fitContextToManuscriptFloor,CHARS_PER_TOKEN,FALLBACK_CONTEXT_WINDOW,+ MANUSCRIPT_FLOOR_TOKENS,} from './contextBudget.js';const section = (n, chars) => ({ number: n, text: 'x'.repeat(chars) });@@ -202,4 +206,115 @@ describe('contextBudget', () => {expect(total).toBe(10);});});++ // ---------------------------------------------------------------------------+ // Manuscript budget floor (#1459): a large re-sent context block must not+ // starve the manuscript chunk to empty on a small/fallback context window.+ // ---------------------------------------------------------------------------++ describe('capContextOverhead', () => {+ it('passes context through unchanged when the window comfortably fits everything', () => {+ const r = capContextOverhead({ contextWindow: 100_000, contextTokens: 2_000, fixedOverheadTokens: 1_500 });+ expect(r.allowedContextTokens).toBe(2_000);+ expect(r.trimmed).toBe(false);+ });+ it('caps the context to preserve the manuscript floor on a small window', () => {+ // 8k window, 0 margin, 0 reserve -> 8000 input budget; 1000 fixed -> 7000 left.+ // A 10k-token context wants more than (7000 - floor), so it's capped at+ // 7000 - MANUSCRIPT_FLOOR_TOKENS, leaving the floor for the manuscript.+ const r = capContextOverhead({+ contextWindow: 8_000,+ contextTokens: 10_000,+ fixedOverheadTokens: 1_000,+ outputReserveTokens: 0,+ safetyMargin: 0,+ });+ expect(r.allowedContextTokens).toBe(7_000 - MANUSCRIPT_FLOOR_TOKENS);+ expect(r.trimmed).toBe(true);+ });+ it('never returns negative context budget even when the fixed overhead alone exceeds the window', () => {+ const r = capContextOverhead({+ contextWindow: 2_000,+ contextTokens: 5_000,+ fixedOverheadTokens: 4_000,+ outputReserveTokens: 0,+ safetyMargin: 0,+ });+ expect(r.allowedContextTokens).toBe(0);+ expect(r.trimmed).toBe(true);+ });+ });++ describe('trimContextToBudget', () => {+ it('passes a string within budget through unchanged', () => {+ expect(trimContextToBudget('short', 100)).toBe('short');+ });+ it('trims to a newline boundary and appends a marker', () => {+ const text = `${'a'.repeat(60)}\n${'b'.repeat(60)}`;+ const out = trimContextToBudget(text, 90);+ expect(out.length).toBeLessThanOrEqual(90);+ expect(out).toContain('context trimmed');+ // Cut at the newline, so the second line is dropped entirely.+ expect(out).not.toContain('b'.repeat(60));+ });+ it('yields empty string when the budget is at or below the marker length', () => {+ expect(trimContextToBudget('anything long enough', 5)).toBe('');+ expect(trimContextToBudget('x', 0)).toBe('');+ });+ });++ describe('fitContextToManuscriptFloor', () => {+ it('leaves context untouched and reports full overhead when it fits', () => {+ const ctx = { sceneMap: 'a'.repeat(400), arcs: 'b'.repeat(200) };+ const r = fitContextToManuscriptFloor(ctx, { contextWindow: 100_000, fixedOverheadTokens: 1_500 });+ expect(r.trimmed).toBe(false);+ expect(r.context).toEqual(ctx);+ // overhead = fixed + estimateTokens(both blocks)+ expect(r.overheadTokens).toBe(1_500 + estimateTokens(ctx.sceneMap) + estimateTokens(ctx.arcs));+ });++ it('trims the LARGEST block first, preserving the bounded ones', () => {+ // Tiny window, huge sceneMap, small arcs. The cut must land on sceneMap.+ const ctx = { sceneMap: 'S'.repeat(40_000), arcs: 'tiny arcs block' };+ const r = fitContextToManuscriptFloor(ctx, {+ contextWindow: 8_000,+ fixedOverheadTokens: 500,+ outputReserveTokens: 0,+ safetyMargin: 0,+ });+ expect(r.trimmed).toBe(true);+ // The bounded block survives intact; the unbounded one absorbs the cut.+ expect(r.context.arcs).toBe('tiny arcs block');+ expect(r.context.sceneMap.length).toBeLessThan(ctx.sceneMap.length);+ });++ it('GUARANTEES a non-empty manuscript budget — a huge outline on a small window still leaves the floor', () => {+ // This is the #1459 regression: overhead alone used to meet/exceed the usable+ // budget, slicing the manuscript chunk to ''. After the fit, usableInputTokens+ // with the (trimmed) overhead must leave at least the manuscript floor.+ const ctx = { sceneMap: 'S'.repeat(200_000) };+ const window = 8_000;+ const r = fitContextToManuscriptFloor(ctx, {+ contextWindow: window,+ fixedOverheadTokens: 1_000,+ outputReserveTokens: 0,+ safetyMargin: 0,+ });+ const usable = usableInputTokens({+ contextWindow: window,+ overheadTokens: r.overheadTokens,+ outputReserveTokens: 0,+ safetyMargin: 0,+ });+ // The manuscript keeps at least the floor — never sliced to empty.+ expect(usable).toBeGreaterThanOrEqual(MANUSCRIPT_FLOOR_TOKENS);+ // And the rendered context now fits the budget it was trimmed for.+ expect(estimateTokens(r.context.sceneMap)).toBeLessThan(estimateTokens(ctx.sceneMap));+ });++ it('handles an empty / non-object context as a no-op', () => {+ expect(fitContextToManuscriptFloor(null, { contextWindow: 8_000 })).toEqual({ context: {}, overheadTokens: 0, trimmed: false });+ expect(fitContextToManuscriptFloor({}, { contextWindow: 8_000, fixedOverheadTokens: 500 })).toEqual({ context: {}, overheadTokens: 500, trimmed: false });+ });+ });});diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.mdindex 0ed639471c..0f35bf0441 100644--- a/server/lib/editorial/README.md+++ b/server/lib/editorial/README.md@@ -32,6 +32,19 @@ window (a chunk packed to the budget just runs without a digest).earlier part already surfaced) opt in; `prose.info-dumping` stays per-chunk (itsproblems are localized).+A check that re-sends a context block per chunk (the reverse-outline scene map,+character arcs, plotline coverage, style-guide expectations, …) declares it as a+`context: { varName: string }` map on `runManuscriptLlmCheck` rather than baking it+into `overheadTokens`. The runner counts the block as overhead AND, on a small or+fallback context window where a large reverse outline would consume the whole+usable budget and slice the manuscript chunk to `''` (#1459), trims the block to+guarantee the manuscript a budget floor (`MANUSCRIPT_FLOOR_TOKENS`) — the LARGEST+block trimmed first, so the unbounded scene map absorbs the cut while bounded+blocks survive. `buildVars(manuscript, meta, context)` receives the trimmed blocks+as its third arg, so the check feeds the SAME context it was budgeted for. A+plain whole-manuscript scan with no re-sent context keeps the simpler+`overheadTokens` form.+`roster.unmodeled-names` also shows the LLM/deterministic split that keeps achunked judgment correct: the model does ONLY what it alone can — surface a propernoun used as a character name and confirm it's a person (not a place/org/brand/diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.jsindex 003743c3bf..aeb25e679d 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -824,17 +824,43 @@ async function runChunkedManuscriptCheck(ctx, { chunks, category, max, callChunk// checks are all manuscript-scoped, so findings keep a model-supplied issue// number (`withIssueNumber: true`).//-// `overheadTokens` MUST account for every non-manuscript prompt var the check-// re-sends on each chunk (the objects summary, the style-guide expectations,-// etc.) on top of EDITORIAL_PROMPT_OVERHEAD_TOKENS — those vars ride alongside-// the chunked manuscript, so under-counting them lets a chunk overrun the-// provider window.-async function runManuscriptLlmCheck(ctx, { stage, category, overheadTokens = 0, buildVars, crossChunkDigest = false, crossChunkSetup = false, setupFocus = '' }) {+// A check declares its per-chunk non-manuscript overhead in ONE of two ways:+//+// `context` (preferred) — a `{ varName: string }` map of the TRIMMABLE context+// blocks the check re-sends on each chunk (the scene map, character arcs, the+// style-guide expectations, …). The runner counts them as overhead AND, on a+// small/fallback window where they'd starve the manuscript chunk to '', trims+// them to guarantee the manuscript a budget floor (#1459). `buildVars` then+// receives the (possibly trimmed) blocks as its third arg — so the check feeds+// the SAME context it was budgeted for (sending the untrimmed originals would+// overflow the window the trim was sized to fit). `EDITORIAL_PROMPT_OVERHEAD_TOKENS`+// is added automatically as the fixed (non-trimmable) template/contract reserve.+//+// `overheadTokens` (legacy) — a single fixed token count for a check with no+// trimmable context (a plain whole-manuscript scan). MUST account for every+// non-manuscript prompt var, on top of EDITORIAL_PROMPT_OVERHEAD_TOKENS.+//+// `buildVars(chunk, meta, context)` returns the stage vars — only the manuscript+// var changes per chunk; `meta.isFinal` is true on the last (or only) chunk so a+// check can gate whole-corpus judgments to it (the Chekhov "planted, never fired"+// pass), and `context` is the trimmed block map (or `{}` for an `overheadTokens`+// check). Existing checks ignore the extra args. These checks are all+// manuscript-scoped, so findings keep a model-supplied issue number+// (`withIssueNumber: true`).+async function runManuscriptLlmCheck(ctx, { stage, category, overheadTokens = 0, context = null, buildVars, crossChunkDigest = false, crossChunkSetup = false, setupFocus = '' }) {const max = ctx.config?.maxFindings ?? 12;// Chunks are planned at the full usable budget; the digest is fitted into each// later chunk's spare room inside runChunkedManuscriptCheck (it yields to the- // manuscript), so no budget is reserved or carved out here.- const chunks = await ctx.planManuscriptChunks(stage, { overheadTokens });+ // manuscript), so no budget is reserved or carved out here. A `context` map is+ // trimmed to keep the manuscript a budget floor; the trimmed blocks come back on+ // `chunks.context` so they're what we feed the model.+ const chunks = context+ ? await ctx.planManuscriptChunks(stage, { context, fixedOverheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS })+ : await ctx.planManuscriptChunks(stage, { overheadTokens });+ // The runner returns the (possibly trimmed) context on `chunks.context`; fall back+ // to the originals if it didn't echo them (a chunker that doesn't implement the+ // context path), and to `{}` for an `overheadTokens` check with no context.+ const fittedContext = chunks?.context || context || {};// Clean-setup digest (#1403): roll a short "setup so far" summary forward via an// inline summarization call. Only wired when the check opts in AND the runner// injected the stage-scoped inline caller — absent it (unit tests of the@@ -856,7 +882,7 @@ async function runManuscriptLlmCheck(ctx, { stage, category, overheadTokens = 0,crossChunkDigest,summarizeChunk,callChunk: async (manuscript, meta) => {- const { content } = await ctx.callStagedLLM(stage, buildVars(manuscript, meta), { returnsJson: true, source: stage });+ const { content } = await ctx.callStagedLLM(stage, buildVars(manuscript, meta, fittedContext), { returnsJson: true, source: stage });return content;},});@@ -1857,9 +1883,9 @@ export const EDITORIAL_CHECKS = [const findings = await runManuscriptLlmCheck(ctx, {stage: UNMODELED_NAMES_STAGE,category: 'casting',- overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS + estimateTokens(knownCharacters),+ context: { knownCharacters },crossChunkDigest: true,- buildVars: (manuscript) => ({ manuscript, knownCharacters }),+ buildVars: (manuscript, _meta, c) => ({ manuscript, knownCharacters: c.knownCharacters }),});// Deterministic whole-corpus recurrence pass. The model's job is the judgment// it alone can make — is this surfaced proper noun a PERSON (vs a place/org/@@ -2366,8 +2392,8 @@ export const EDITORIAL_CHECKS = [return runManuscriptLlmCheck(ctx, {stage: SENSORY_BALANCE_STAGE,category: 'style',- overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS + estimateTokens(sceneMap),- buildVars: (manuscript) => ({ manuscript, sceneMap }),+ context: { sceneMap },+ buildVars: (manuscript, _meta, c) => ({ manuscript, sceneMap: c.sceneMap }),});},},@@ -2409,8 +2435,8 @@ export const EDITORIAL_CHECKS = [return runManuscriptLlmCheck(ctx, {stage: WHITE_ROOM_STAGE,category: 'style',- overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS + estimateTokens(sceneMap),- buildVars: (manuscript) => ({ manuscript, sceneMap }),+ context: { sceneMap },+ buildVars: (manuscript, _meta, c) => ({ manuscript, sceneMap: c.sceneMap }),});},},@@ -2585,9 +2611,10 @@ export const EDITORIAL_CHECKS = [return runManuscriptLlmCheck(ctx, {stage: HEAD_HOPPING_STAGE,category: 'style',- overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS- + estimateTokens(povMap) + estimateTokens(povPerson),- buildVars: (manuscript) => ({ manuscript, povMap, povPerson }),+ // povPerson is a short fixed label and povMap grows with scene count, so+ // largest-first trimming absorbs the cut into povMap and keeps povPerson.+ context: { povMap, povPerson },+ buildVars: (manuscript, _meta, c) => ({ manuscript, povMap: c.povMap, povPerson: c.povPerson }),});},},@@ -2634,9 +2661,8 @@ export const EDITORIAL_CHECKS = [return runManuscriptLlmCheck(ctx, {stage: ARC_TRANSITIONS_STAGE,category: 'arc',- overheadTokens:- EDITORIAL_PROMPT_OVERHEAD_TOKENS + estimateTokens(sceneMap) + estimateTokens(characterArcs),- buildVars: (manuscript) => ({ manuscript, sceneMap, characterArcs }),+ context: { sceneMap, characterArcs },+ buildVars: (manuscript, _meta, c) => ({ manuscript, sceneMap: c.sceneMap, characterArcs: c.characterArcs }),// Arc change moments accrue across the whole manuscript — a flat-arc// verdict needs to see whether a character ever changed in a LATER// chunk. Roll a "transitions seen so far" digest forward so a@@ -2692,21 +2718,19 @@ export const EDITORIAL_CHECKS = [return runManuscriptLlmCheck(ctx, {stage: PLOT_STRUCTURE_STAGE,category: 'plot',- overheadTokens:- EDITORIAL_PROMPT_OVERHEAD_TOKENS- + estimateTokens(sceneMap)- + estimateTokens(plotlineMap)- + estimateTokens(authoredSetups),+ // sceneMap grows unbounded with scene count; plotlineMap and authoredSetups+ // are bounded — so largest-first trimming absorbs the cut into sceneMap.+ context: { sceneMap, plotlineMap, authoredSetups },// `isFinal` gates the whole-corpus judgments — a sagging middle, a never-// escalating arc, and a dropped subplot can only be judged once the whole// manuscript is in view; an earlier chunk can't know a thread is picked back// up (or stakes rise) later, so it would false-flag. A single-chunk run is// its own final part and judges the whole text.- buildVars: (manuscript, meta) => ({+ buildVars: (manuscript, meta, c) => ({manuscript,- sceneMap,- plotlineMap,- authoredSetups,+ sceneMap: c.sceneMap,+ plotlineMap: c.plotlineMap,+ authoredSetups: c.authoredSetups,finalPart: meta?.isFinal ? 'true' : '',}),// Plot pathologies span the whole arc — the cross-chunk findings digest keeps@@ -2765,19 +2789,18 @@ export const EDITORIAL_CHECKS = [return runManuscriptLlmCheck(ctx, {stage: THEME_COHERENCE_STAGE,category: 'theme',- overheadTokens:- EDITORIAL_PROMPT_OVERHEAD_TOKENS- + estimateTokens(declaredThemes)- + estimateTokens(sceneMap),+ // declaredThemes is bounded by the authored theme count; sceneMap grows with+ // scene count — so largest-first trimming absorbs the cut into sceneMap.+ context: { declaredThemes, sceneMap },// `isFinal` gates the whole-corpus judgments — a theme that is set up but// never paid off, a theme dropped after the opening, and whether the// climax lands the thematic argument can only be judged once the whole// manuscript is in view; an earlier chunk can't know a theme is paid off// later, so it would false-flag.- buildVars: (manuscript, meta) => ({+ buildVars: (manuscript, meta, c) => ({manuscript,- declaredThemes,- sceneMap,+ declaredThemes: c.declaredThemes,+ sceneMap: c.sceneMap,finalPart: meta?.isFinal ? 'true' : '',}),// Theme coverage accrues across the whole manuscript — the findings digest@@ -3070,9 +3093,10 @@ export const EDITORIAL_CHECKS = [return runManuscriptLlmCheck(ctx, {stage: OBJECT_MOTIVATION_STAGE,category: 'continuity',- // The objects-attachment summary is fixed per-call overhead.- overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS + estimateTokens(objects),- buildVars: (manuscript) => ({ manuscript, objects }),+ // The objects-attachment summary is re-sent per chunk — trimmed to keep the+ // manuscript a budget floor on a small window.+ context: { objects },+ buildVars: (manuscript, _meta, c) => ({ manuscript, objects: c.objects }),// An object's motivation can be set up in an earlier chapter and paid off// later; without the digest a later chunk may flag a "missing setup" an// earlier chunk already accounted for (#1383).@@ -3307,9 +3331,10 @@ export const EDITORIAL_CHECKS = [return runManuscriptLlmCheck(ctx, {stage: STYLE_CONFORMANCE_STAGE,category: 'style',- // The style-guide expectations are fixed per-call overhead.- overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS + estimateTokens(expectations),- buildVars: (manuscript) => ({ manuscript, styleGuide: expectations }),+ // The style-guide expectations are re-sent per chunk — trimmed to keep the+ // manuscript a budget floor on a small window.+ context: { styleGuide: expectations },+ buildVars: (manuscript, _meta, c) => ({ manuscript, styleGuide: c.styleGuide }),// Tense/POV drift is inherently cross-chapter — a per-chunk view can't see// that chapter 1 established past-tense when judging chapter 3 (#1383).crossChunkDigest: true,@@ -3358,13 +3383,13 @@ export const EDITORIAL_CHECKS = [return runManuscriptLlmCheck(ctx, {stage: CHEKHOV_STAGE,category: 'continuity',- overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS + estimateTokens(authoredSetups),+ context: { authoredSetups },// `finalPart` gates the whole-corpus "planted, never fired" judgment to the// last part of a chunked manuscript (#1299) — an earlier part can't know a// setup pays off later, so it would false-flag. A single-chunk run is its own// final part. "fired, never planted" stays enabled on every part (the carried// setup digest tells a later part what was already planted).- buildVars: (manuscript, meta) => ({ manuscript, authoredSetups, finalPart: meta?.isFinal ? 'true' : '' }),+ buildVars: (manuscript, meta, c) => ({ manuscript, authoredSetups: c.authoredSetups, finalPart: meta?.isFinal ? 'true' : '' }),// A setup planted in chapter 2 and paid off (or NOT) in chapter 9 spans// chunks — the cross-chunk digest keeps prior findings in view so a later// chunk doesn't re-flag, and the clean-setup digest rolls forward which@@ -4235,8 +4260,10 @@ export const EDITORIAL_CHECKS = [return runManuscriptLlmCheck(ctx, {stage: VOICE_DISTINCTIVENESS_STAGE,category: 'dialogue',- overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS + estimateTokens(voiceProfiles),- buildVars: (manuscript) => ({ manuscript, voiceProfiles }),+ // The authored voice profiles are re-sent per chunk — trimmed to keep the+ // manuscript a budget floor on a small window.+ context: { voiceProfiles },+ buildVars: (manuscript, _meta, c) => ({ manuscript, voiceProfiles: c.voiceProfiles }),// Voice distinctiveness is a whole-cast judgment: a character's lines are// spread across chapters, so a per-chunk view can't tell "interchangeable"// from "we only saw one speaker this chunk". Roll a per-character voice-@@ -4394,13 +4421,13 @@ export const EDITORIAL_CHECKS = [return runManuscriptLlmCheck(ctx, {stage: ENDINGS_CLIFFHANGER_STAGE,category: 'pacing',- overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS + estimateTokens(authoredCliffhangers),+ context: { authoredCliffhangers },// `finalPart` gates the "leave the terminal chapter alone" exemption (#1298):// on a chunked manuscript, only the LAST part can contain the series finale,// so an earlier part must NOT treat its last visible chapter as terminal// (that would false-negative a soft landing at a chunk boundary). A// single-chunk run is its own final part. Mirrors the Chekhov check.- buildVars: (manuscript, meta) => ({ manuscript, authoredCliffhangers, finalPart: meta?.isFinal ? 'true' : '' }),+ buildVars: (manuscript, meta, c) => ({ manuscript, authoredCliffhangers: c.authoredCliffhangers, finalPart: meta?.isFinal ? 'true' : '' }),});},},diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.jsindex afda9bc946..724fcc5ecc 100644--- a/server/lib/editorial/checkRegistry.test.js+++ b/server/lib/editorial/checkRegistry.test.js@@ -400,7 +400,10 @@ describe('pov.head-hopping — LLM check (#1311)', () => {let seenOverhead = 0;const ctx = wholeCtx({planManuscriptChunks: async (_stage, opts) => {- seenOverhead = opts.overheadTokens;+ // The trimmable context blocks ride alongside the manuscript as overhead;+ // the fixed template reserve is passed separately (#1459).+ seenOverhead = opts.fixedOverheadTokens;+ expect(opts.context).toHaveProperty('povMap');return ['# Issue 1\n\nchunk'];},callStagedLLM: async (_stage, vars) => {@@ -478,7 +481,10 @@ describe.each([let seenOverhead = 0;const ctx = wholeCtx({planManuscriptChunks: async (_stage, opts) => {- seenOverhead = opts.overheadTokens;+ // The scene map rides as trimmable context (#1459); the fixed template+ // reserve is passed separately.+ seenOverhead = opts.fixedOverheadTokens;+ expect(opts.context).toHaveProperty('sceneMap');return ['# Issue 1\n\nchunk'];},callStagedLLM: async (_stage, vars) => {@@ -487,7 +493,7 @@ describe.each([},});const findings = await getCheck(id).run(ctx);- // The scene map rode along as a prompt var and inflated the overhead budget.+ // The scene map rode along as a prompt var (and was budgeted as context overhead).expect(seenVars.sceneMap).toContain('Issue 1: The void');expect(seenOverhead).toBeGreaterThan(0);expect(findings).toHaveLength(1);@@ -608,8 +614,9 @@ describe('chekhov.setups-payoffs — LLM check (#1299)', () => {const ctx = wholeCtx({series: { arc: { readerMap: { hooks: [{ label: 'The locked drawer', note: 'planted in Issue 1' }], payoffs: [] } } },planManuscriptChunks: async (_stage, opts) => {- // Authored hooks/payoffs ride alongside the manuscript as fixed overhead.- expect(opts.overheadTokens).toBeGreaterThan(0);+ // Authored hooks/payoffs ride alongside the manuscript as trimmable context (#1459).+ expect(opts.context).toHaveProperty('authoredSetups');+ expect(opts.fixedOverheadTokens).toBeGreaterThan(0);return ['# Issue 1\n\nThe drawer stayed locked forever.'];},callStagedLLM: async (_stage, vars) => {@@ -719,8 +726,11 @@ describe('plot.structure-momentum — LLM check (#1310)', () => {const ctx = wholeCtx({series: { arc: { readerMap: { hooks: [{ label: 'Where is the brother?', note: 'planted Issue 1' }], payoffs: [] } } },planManuscriptChunks: async (_stage, opts) => {- // Scene map + plotline coverage + authored setups all ride as fixed overhead.- expect(opts.overheadTokens).toBeGreaterThan(0);+ // Scene map + plotline coverage + authored setups all ride as trimmable context (#1459).+ expect(opts.context).toHaveProperty('sceneMap');+ expect(opts.context).toHaveProperty('plotlineMap');+ expect(opts.context).toHaveProperty('authoredSetups');+ expect(opts.fixedOverheadTokens).toBeGreaterThan(0);return ['# Issue 1\n\nThe brother thread is never mentioned again.'];},callStagedLLM: async (_stage, vars) => {@@ -843,8 +853,10 @@ describe('theme.coherence — LLM check (#1317)', () => {let seenVars = null;const ctx = wholeCtx({planManuscriptChunks: async (_stage, opts) => {- // Declared themes + scene map both ride as fixed overhead.- expect(opts.overheadTokens).toBeGreaterThan(0);+ // Declared themes + scene map both ride as trimmable context (#1459).+ expect(opts.context).toHaveProperty('declaredThemes');+ expect(opts.context).toHaveProperty('sceneMap');+ expect(opts.fixedOverheadTokens).toBeGreaterThan(0);return ['# Issue 1\n\nForgiveness is never mentioned again.'];},callStagedLLM: async (_stage, vars) => {@@ -954,8 +966,9 @@ describe('roster.unmodeled-names — LLM check (#1412)', () => {let seenVars = null;const ctx = wholeCtx({planManuscriptChunks: async (_stage, opts) => {- // The known-character roster rides as fixed overhead.- expect(opts.overheadTokens).toBeGreaterThan(0);+ // The known-character roster rides as trimmable context (#1459).+ expect(opts.context).toHaveProperty('knownCharacters');+ expect(opts.fixedOverheadTokens).toBeGreaterThan(0);return ['# Issue 1\n\nMarguerite drew her sword.'];},callStagedLLM: async (_stage, vars) => {@@ -1128,8 +1141,9 @@ describe('endings.cliffhanger — LLM check (#1298)', () => {const ctx = wholeCtx({series: { arc: { readerMap: { cliffhangers: [{ note: 'the door opens', atIssueBoundary: 1 }] } } },planManuscriptChunks: async (_stage, opts) => {- // Authored cliffhangers ride alongside the manuscript as fixed overhead.- expect(opts.overheadTokens).toBeGreaterThan(0);+ // Authored cliffhangers ride alongside the manuscript as trimmable context (#1459).+ expect(opts.context).toHaveProperty('authoredCliffhangers');+ expect(opts.fixedOverheadTokens).toBeGreaterThan(0);return ['# Issue 1\n\nThe war ended and everyone went home.'];},callStagedLLM: async (_stage, vars) => {@@ -2142,14 +2156,14 @@ describe('objects.unmotivated-interaction — LLM check (#1288)', () => {});it('budgets the objects summary as prompt overhead and re-sends it on every chunk', async () => {- let overhead = null;+ let sawObjectsContext = false;const objectsSeen = [];await getCheck('objects.unmotivated-interaction').run(baseCtx({- planManuscriptChunks: async (_stage, opts) => { overhead = opts.overheadTokens; return ['chunk a', 'chunk b']; },+ planManuscriptChunks: async (_stage, opts) => { sawObjectsContext = Object.prototype.hasOwnProperty.call(opts.context || {}, 'objects'); return ['chunk a', 'chunk b']; },callStagedLLM: async (_stage, v) => { objectsSeen.push(v.objects); return { content: { findings: [] } }; },}));- // Overhead exceeds the fixed template reserve because the objects summary is counted in.- expect(overhead).toBeGreaterThan(0);+ // The objects summary is passed as trimmable context (#1459), re-sent per chunk.+ expect(sawObjectsContext).toBe(true);// 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);@@ -2231,7 +2245,9 @@ describe('cross-chunk continuity digest (#1383)', () => {// No usableChars on the returned array → unbounded headroom, so the digest// always fits (the fits-in-budget gate is exercised separately below).planManuscriptChunks: async (_stage, opts) => {- overhead = opts.overheadTokens;+ // A context-based check (#1459) passes { context, fixedOverheadTokens }; a+ // legacy plain-scan check passes { overheadTokens }. Capture whichever is set.+ overhead = opts.context ? opts.fixedOverheadTokens : opts.overheadTokens;return ['CHUNK_ONE', 'CHUNK_TWO'];},callStagedLLM: async (_stage, vars) => {diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.jsindex dc74a668c8..9702a0e124 100644--- a/server/services/pipeline/editorial/checkRunner.js+++ b/server/services/pipeline/editorial/checkRunner.js@@ -18,7 +18,7 @@import { randomUUID, createHash } from 'crypto';import { createSseRunner } from '../../../lib/sseUtils.js';import { runStagedLLM, runInlineLLM, runStageScopedInlineLLM, resolveStageContext } from '../../../lib/stageRunner.js';-import { planManuscriptPass } from '../../../lib/contextBudget.js';+import { planManuscriptPass, fitContextToManuscriptFloor } from '../../../lib/contextBudget.js';import { getEnabledChecks, getEnabledCheckRows, getAllChecks, EDITORIAL_SOURCES, comicLetteringIssues } from '../../../lib/editorial/index.js';import { getSettings } from '../../settings.js';import { getSeries } from '../series.js';@@ -354,21 +354,49 @@ export async function runEditorialChecks(seriesId, options = {}) {// 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 } = {}) => {+ //+ // Two ways to declare per-chunk overhead:+ // { overheadTokens } — legacy: a fixed, non-trimmable overhead+ // (the custom-check prompt wrapper).+ // { context, fixedOverheadTokens } — the trimmable re-sent context blocks+ // (scene map, character arcs, …) plus the+ // fixed template/contract overhead. The+ // context is trimmed to GUARANTEE the+ // manuscript a budget floor (#1459) so a+ // large reverse outline on a small window+ // can't starve the manuscript chunk to ''.+ // When `context` is given, the (possibly trimmed) blocks are attached to the+ // returned array as `.context` so the check feeds the trimmed values to the LLM.+ planManuscriptChunks: async (stage, { overheadTokens = 0, context = null, fixedOverheadTokens = 0 } = {}) => {if (!sections.length) return [];const { contextWindow } = await resolveStageContext(stage, { providerOverride, modelOverride });+ let effectiveOverhead = overheadTokens;+ let fittedContext = null;+ if (context && typeof context === 'object') {+ const fit = fitContextToManuscriptFloor(context, {+ contextWindow,+ fixedOverheadTokens,+ outputReserveTokens: EDITORIAL_OUTPUT_RESERVE_TOKENS,+ });+ effectiveOverhead = fit.overheadTokens;+ fittedContext = fit.context;+ if (fit.trimmed) {+ console.warn(`✂️ editorial context trimmed to keep manuscript budget — stage=${stage || 'inline'} window=${contextWindow}`);+ }+ }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,+ overheadTokens: effectiveOverhead,outputReserveTokens: EDITORIAL_OUTPUT_RESERVE_TOKENS,});// One whole chunk or many — the same usable-char budget caps each. Do NOT// floor this above plan.usableChars: on a genuinely small configured window// that would push the prompt back over the provider's context and get it- // clipped/rejected. The editorial-sized output reserve above is what keeps- // usableChars positive on the common unknown/8K-fallback provider.+ // clipped/rejected. The editorial-sized output reserve above plus the+ // context floor (when context is given) is what keeps usableChars positive+ // on the common unknown/8K-fallback provider.const corpora = plan.mode === 'whole'? [manuscript]: plan.chunks.map((c) => sectionsCorpus(c.sections));@@ -377,6 +405,10 @@ export async function runEditorialChecks(seriesId, options = {}) {// digest into each chunk's spare room without overflowing the window or// displacing manuscript text (see runChunkedManuscriptCheck).chunks.usableChars = plan.usableChars;+ // Expose the trimmed context so the check sends the SAME (possibly shrunk)+ // blocks it was budgeted for — sending the untrimmed originals would overflow+ // the window the trim was computed to fit.+ if (fittedContext) chunks.context = fittedContext;return chunks;},};diff --git a/server/services/pipeline/editorial/checkRunner.test.js b/server/services/pipeline/editorial/checkRunner.test.jsindex cc38574021..d5750b5dd1 100644--- a/server/services/pipeline/editorial/checkRunner.test.js+++ b/server/services/pipeline/editorial/checkRunner.test.js@@ -236,6 +236,34 @@ describe('runEditorialChecks', () => {expect(sent).toContain('kingdom fell'); // the actual section content, not an empty slice});+ it('guarantees a non-empty manuscript when a huge reverse outline + a tiny window would starve the chunk (issue #1459)', async () => {+ // A context-bearing check (arc.transitions re-sends the scene map per chunk).+ // A reverse outline with many scenes makes the sceneMap overhead alone meet/+ // exceed a small window's usable budget — which used to slice the manuscript+ // chunk to ''. The context floor must trim the scene map so the manuscript+ // (the actual prose under review) still reaches the model non-empty.+ const manyScenes = Array.from({ length: 400 }, (_, i) => ({+ issueNumber: 1,+ sceneLabel: `Scene ${i + 1}`,+ setting: `An elaborately described location number ${i + 1} that goes on at length to inflate the scene map`,+ charactersPresent: ['Alina', 'Alana', 'Zog'],+ }));+ outlineState = { scenes: manyScenes };+ collectManuscriptSections.mockResolvedValueOnce([+ { number: 1, title: 'Pilot', stageId: 'prose', content: 'Alina chose to betray Zog, and in that moment she became someone new.' },+ ]);+ resolveStageContext.mockResolvedValueOnce({ provider: { type: 'api', endpoint: 'http://localhost:1234' }, model: 'm', contextWindow: 8_192 });+ let sent = null;+ runStagedLLM.mockImplementationOnce(async (_stage, vars) => { sent = vars.manuscript; return { content: { findings: [] } }; });++ await runEditorialChecks('s1', { checkIds: ['arc.transitions'] });++ expect(sent).toBeTruthy();+ // The manuscript chunk is non-empty — the scene map was trimmed, not the prose.+ expect(sent.trim().length).toBeGreaterThan(0);+ expect(sent).toContain('chose to betray');+ });+it('stops launching chunk calls once cancelled mid-run (issue #1340)', async () => {// Three chunks; cancel during the first chunk's LLM call. The remaining// chunks must NOT be sent to the model, and the run is canceled (no seed).