Skip to content

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

address review (codex): reserve digest budget on later chunks only, full budget for the first (#1383)

[._.]/ Adam Eivycc99f7281613
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.md
index 193c5fe41d..713d2d78b4 100644
--- a/server/lib/editorial/README.md
+++ b/server/lib/editorial/README.md
@@ -21,10 +21,11 @@ Checks whose problems span chapters can opt into a **cross-chunk continuity
digest** (#1383): pass `crossChunkDigest: true` to `runManuscriptLlmCheck` and
each chunk after the first is prefixed with `editorialPriorFindingsDigest` of the
findings gathered so far (it rides INSIDE the manuscript var, so no prompt
-template change). The digest body is capped (`EDITORIAL_PRIOR_DIGEST_CHARS`) so it
-rides in the budgeter's safety margin rather than reserving a slice of the usable
-budget — which would needlessly truncate the first/only chunk that carries no
-digest. `style.conformance` (tense/POV established earlier) and
+template change). The digest body is capped (`EDITORIAL_PRIOR_DIGEST_CHARS`); the
+planner carves that room (`EDITORIAL_PRIOR_DIGEST_TOKENS`) out of the chunks
+AFTER the first only — the first/only chunk carries no digest and keeps its full
+budget, while later chunks reserve exactly enough that `digest + manuscript`
+can't overrun the provider window. `style.conformance` (tense/POV established earlier) and
`objects.unmotivated-interaction` (setup/payoff across chapters) opt in;
`prose.info-dumping` stays per-chunk (its problems are localized).
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index ec36375757..7a75f099ad 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -25,7 +25,7 @@
*/
import { z } from 'zod';
-import { estimateTokens } from '../contextBudget.js';
+import { estimateTokens, CHARS_PER_TOKEN } from '../contextBudget.js';
export const CHECK_SCOPES = Object.freeze(['series', 'issue', 'scene', 'noun']);
export const CHECK_KINDS = Object.freeze(['deterministic', 'llm']);
@@ -229,11 +229,14 @@ const EDITORIAL_PRIOR_DIGEST_HEADER = '# Editorial findings already recorded for
+ 'continuity these earlier findings reveal (e.g. an object set up earlier, or a tense/POV '
+ 'choice established in an earlier chapter).\n\n';
const EDITORIAL_PRIOR_DIGEST_SEPARATOR = '\n\n---\n\n';
-// Whole-digest char ceiling = fixed wrapper + capped body. Kept small enough to
-// ride inside the budgeter's safety margin rather than reserving a slice of the
-// usable budget (see runManuscriptLlmCheck).
+// Whole-digest char ceiling = fixed wrapper + capped body, so the token reserve
+// below is an exact upper bound on what gets prepended to a later chunk.
export const EDITORIAL_PRIOR_DIGEST_CHARS =
EDITORIAL_PRIOR_DIGEST_HEADER.length + EDITORIAL_PRIOR_DIGEST_BODY_CHARS + EDITORIAL_PRIOR_DIGEST_SEPARATOR.length;
+// Budget the planner carves out of chunks AFTER the first to make room for the
+// prepended digest, so `digest + manuscript` can't overflow the provider window
+// even on a small/local provider (the first/only chunk keeps its full budget).
+export const EDITORIAL_PRIOR_DIGEST_TOKENS = Math.ceil(EDITORIAL_PRIOR_DIGEST_CHARS / CHARS_PER_TOKEN);
// One-block digest of findings already recorded for earlier chunks, prepended
// INSIDE the next chunk's manuscript var so no prompt template changes (mirrors
@@ -298,12 +301,14 @@ async function runChunkedManuscriptCheck(ctx, { chunks, category, max, callChunk
// provider window.
async function runManuscriptLlmCheck(ctx, { stage, category, overheadTokens = 0, buildVars, crossChunkDigest = false }) {
const max = ctx.config?.maxFindings ?? 12;
- // No extra digest reserve here: the digest is only prepended to chunks AFTER
- // the first, but the planner's usableChars budget is uniform across chunks —
- // reserving would needlessly truncate the first/only chunk (which carries no
- // digest). The digest body is capped (EDITORIAL_PRIOR_DIGEST_CHARS) to ride in
- // the budgeter's safety margin instead, mirroring completenessPass.
- const chunks = await ctx.planManuscriptChunks(stage, { overheadTokens });
+ // When this check prepends a cross-chunk digest, tell the planner to carve the
+ // digest's room out of the chunks AFTER the first (the first/only chunk carries
+ // no digest, so it keeps its full budget) — so `digest + manuscript` can't
+ // overrun the provider window even on a small/local provider.
+ const chunks = await ctx.planManuscriptChunks(stage, {
+ overheadTokens,
+ digestReserveTokens: crossChunkDigest ? EDITORIAL_PRIOR_DIGEST_TOKENS : 0,
+ });
return runChunkedManuscriptCheck(ctx, {
chunks,
category,
diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.js
index d5044b51b8..d8c4c62a96 100644
--- a/server/lib/editorial/checkRegistry.test.js
+++ b/server/lib/editorial/checkRegistry.test.js
@@ -21,6 +21,7 @@ import {
editorialPriorFindingsDigest,
EDITORIAL_PRIOR_DIGEST_MAX,
EDITORIAL_PRIOR_DIGEST_CHARS,
+ EDITORIAL_PRIOR_DIGEST_TOKENS,
} from './checkRegistry.js';
const NAMING = 'naming.dissimilar-names';
@@ -595,10 +596,15 @@ describe('cross-chunk continuity digest (#1383)', () => {
const runTwoChunks = async (checkId, ctxExtras) => {
const seen = [];
let overhead = null;
+ let digestReserve = null;
await getCheck(checkId).run({
config: { maxFindings: 12 },
severityDefault: 'medium',
- planManuscriptChunks: async (_stage, opts) => { overhead = opts.overheadTokens; return ['CHUNK_ONE', 'CHUNK_TWO']; },
+ planManuscriptChunks: async (_stage, opts) => {
+ overhead = opts.overheadTokens;
+ digestReserve = opts.digestReserveTokens;
+ return ['CHUNK_ONE', 'CHUNK_TWO'];
+ },
callStagedLLM: async (_stage, vars) => {
seen.push(vars.manuscript);
// Only the first chunk surfaces a finding, so the digest fed to chunk two
@@ -610,11 +616,11 @@ describe('cross-chunk continuity digest (#1383)', () => {
},
...ctxExtras,
});
- return { seen, overhead };
+ return { seen, overhead, digestReserve };
};
it('style.conformance feeds the prior-chunk digest to later chunks and reserves budget for it', async () => {
- const { seen, overhead } = await runTwoChunks('style.conformance', {
+ const { seen, overhead, digestReserve } = await runTwoChunks('style.conformance', {
series: { styleGuide: { tense: 'past', povPerson: 'first' } },
});
// First chunk is untouched (no prior findings yet).
@@ -623,10 +629,10 @@ describe('cross-chunk continuity digest (#1383)', () => {
expect(seen[1]).toContain('EARLIER parts of this manuscript');
expect(seen[1]).toContain('tense slip in chapter one');
expect(seen[1].endsWith('CHUNK_TWO')).toBe(true);
- // The style-guide expectations are budgeted as prompt overhead; the digest is
- // NOT reserved (it rides the safety margin, so the first/only chunk keeps its
- // full budget).
+ // The style-guide expectations are budgeted as prompt overhead, and the digest
+ // reserve is passed to the planner so it can carve room out of later chunks.
expect(overhead).toBeGreaterThan(0);
+ expect(digestReserve).toBe(EDITORIAL_PRIOR_DIGEST_TOKENS);
});
it('objects.unmotivated-interaction feeds the prior-chunk digest to later chunks', async () => {
@@ -642,7 +648,7 @@ describe('cross-chunk continuity digest (#1383)', () => {
});
it('prose.info-dumping stays per-chunk — no digest is prepended (its problems are localized)', async () => {
- const { seen } = await runTwoChunks(INFODUMP, {
+ const { seen, digestReserve } = await runTwoChunks(INFODUMP, {
manuscript: 'CHUNK_ONE',
});
expect(seen[0]).toBe('CHUNK_ONE');
@@ -650,6 +656,8 @@ describe('cross-chunk continuity digest (#1383)', () => {
// produced a finding.
expect(seen[1]).toBe('CHUNK_TWO');
expect(seen[1]).not.toContain('EARLIER parts of this manuscript');
+ // And it reserves no digest budget (so chunks keep their full size).
+ expect(digestReserve).toBe(0);
});
});
diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.js
index 0455227ff5..fa5e87f2d7 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, resolveStageContext } from '../../../lib/stageRunner.js';
-import { planManuscriptPass } from '../../../lib/contextBudget.js';
+import { planManuscriptPass, CHARS_PER_TOKEN } from '../../../lib/contextBudget.js';
import { getEnabledChecks, getEnabledCheckRows, getAllChecks } from '../../../lib/editorial/index.js';
import { getSettings } from '../../settings.js';
import { getSeries } from '../series.js';
@@ -138,7 +138,7 @@ 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 } = {}) => {
+ planManuscriptChunks: async (stage, { overheadTokens = 0, digestReserveTokens = 0 } = {}) => {
if (!sections.length) return [];
const { contextWindow } = await resolveStageContext(stage, { providerOverride, modelOverride });
const plan = planManuscriptPass({
@@ -156,7 +156,12 @@ export async function runEditorialChecks(seriesId, options = {}) {
const corpora = plan.mode === 'whole'
? [manuscript]
: plan.chunks.map((c) => sectionsCorpus(c.sections));
- return corpora.map((c) => c.slice(0, plan.usableChars));
+ // A cross-chunk-digest check prepends a digest to every chunk AFTER the
+ // first. Carve that room out of the later chunks ONLY (the first/only chunk
+ // carries no digest, so it keeps the full budget) — so `digest + manuscript`
+ // never exceeds the planned per-chunk window even on a small provider.
+ const reserveChars = Math.max(0, digestReserveTokens) * CHARS_PER_TOKEN;
+ return corpora.map((c, i) => c.slice(0, Math.max(0, plan.usableChars - (i === 0 ? 0 : reserveChars))));
},
};
diff --git a/server/services/pipeline/editorial/checkRunner.test.js b/server/services/pipeline/editorial/checkRunner.test.js
index ba2b13cec0..ee713bf3d2 100644
--- a/server/services/pipeline/editorial/checkRunner.test.js
+++ b/server/services/pipeline/editorial/checkRunner.test.js
@@ -171,6 +171,32 @@ describe('runEditorialChecks', () => {
expect(allSent).toContain('SEC3');
});
+ it('feeds a prior-chunk digest to later chunks for a cross-chunk-digest check, but not the first (#1383)', async () => {
+ // A long manuscript + small window → chunked. style.conformance opts into the
+ // cross-chunk digest, so chunks AFTER the first carry a digest of prior findings.
+ const big = (marker) => `${marker} ${'A'.repeat(12_000)}`;
+ getSeries.mockResolvedValueOnce({ id: 's1', universeId: 'u1', styleGuide: { tense: 'past', povPerson: 'first' } });
+ 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: 10_000 });
+ // The default runStagedLLM mock returns a finding on every call, so the first
+ // chunk seeds the digest fed to later chunks (no custom impl needed — that
+ // would leak past this test).
+
+ await runEditorialChecks('s1', { checkIds: ['style.conformance'] });
+ const sent = runStagedLLM.mock.calls.map((c) => c[1].manuscript);
+ expect(sent.length).toBeGreaterThan(1);
+ // First chunk: no digest preamble.
+ expect(sent[0]).not.toContain('EARLIER parts of this manuscript');
+ // At least one later chunk carries the digest of the first chunk's finding.
+ const withDigest = sent.slice(1).filter((m) => m.includes('EARLIER parts of this manuscript'));
+ expect(withDigest.length).toBeGreaterThan(0);
+ expect(withDigest[0]).toContain('Info dump in opening');
+ });
+
it('still sends a non-empty manuscript on a small/fallback context window (issue #1340)', async () => {
// An unknown local provider falls back to the 8K window. With the contextBudget
// default 8K output reserve this would leave a 0-char input budget and feed the