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
address review (codex): fit digest into each chunk's spare room so it never drops manuscript coverage (#1383)
[._.]/ Adam Eivyd96af341e076
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.mdindex 713d2d78b4..b8064b8a5a 100644--- a/server/lib/editorial/README.md+++ b/server/lib/editorial/README.md@@ -21,11 +21,12 @@ Checks whose problems span chapters can opt into a **cross-chunk continuitydigest** (#1383): pass `crossChunkDigest: true` to `runManuscriptLlmCheck` andeach chunk after the first is prefixed with `editorialPriorFindingsDigest` of thefindings gathered so far (it rides INSIDE the manuscript var, so no prompt-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+template change). The digest body is capped (`EDITORIAL_PRIOR_DIGEST_CHARS`) and+**yields to manuscript coverage**: the runner's chunker reports each chunk's+`usableChars` budget, and the digest is prepended only when it fits the chunk's+spare room — so it never displaces manuscript text or overflows the provider+window (a chunk packed to the budget just runs without a digest).+`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.jsindex 7a75f099ad..0bc2c25073 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -25,7 +25,7 @@*/import { z } from 'zod';-import { estimateTokens, CHARS_PER_TOKEN } from '../contextBudget.js';+import { estimateTokens } from '../contextBudget.js';export const CHECK_SCOPES = Object.freeze(['series', 'issue', 'scene', 'noun']);export const CHECK_KINDS = Object.freeze(['deterministic', 'llm']);@@ -229,14 +229,11 @@ 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, so the token reserve-// below is an exact upper bound on what gets prepended to a later chunk.+// Whole-digest char ceiling = fixed wrapper + capped body. The digest is only+// prepended to a chunk when it fits in that chunk's spare budget (see+// runChunkedManuscriptCheck), so it never grows a chunk past the provider window.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@@ -264,15 +261,29 @@ export function editorialPriorFindingsDigest(findings) {// chunk text passed to `callChunk`, so the per-check prompt template is// unchanged. Merges incrementally (vs collect-then-merge) so the digest is O(1)// to derive from the running map.+//+// The digest YIELDS to manuscript coverage: it is prepended only when it fits in+// the chunk's spare budget (`usableChars - chunk length`, exposed by the runner's+// chunker). So it never displaces manuscript text and never grows a chunk past+// the provider window — a chunk packed up to the budget simply runs without a+// digest rather than dropping its tail. When the chunker doesn't report a budget+// (a fits-in-one-call provider, or a test stub), there is unbounded headroom.async function runChunkedManuscriptCheck(ctx, { chunks, category, max, callChunk, crossChunkDigest = false }) {+ const usableChars = Number.isFinite(chunks?.usableChars) ? chunks.usableChars : Infinity;const merged = new Map();for (const manuscript of chunks) {// Stop launching further chunk calls once the run is cancelled — the runner// only checks the signal around the whole check, so without this a multi-// chunk check keeps paying for LLM calls whose results will be discarded.if (ctx.signal?.aborted) break;- const digest = crossChunkDigest && merged.size ? editorialPriorFindingsDigest([...merged.values()]) : '';- const content = await callChunk(`${digest}${manuscript}`);+ let text = manuscript;+ if (crossChunkDigest && merged.size) {+ const digest = editorialPriorFindingsDigest([...merged.values()]);+ // Only prepend when the digest fits the chunk's spare room — never trim the+ // manuscript (would drop review coverage) or overflow the window.+ if (digest && digest.length <= usableChars - manuscript.length) text = `${digest}${manuscript}`;+ }+ const content = await callChunk(text);for (const f of mapLlmFindings(content?.findings, {severityDefault: ctx.severityDefault,category,@@ -301,14 +312,10 @@ 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;- // 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,- });+ // 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 });return runChunkedManuscriptCheck(ctx, {chunks,category,diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.jsindex d8c4c62a96..6492708dd2 100644--- a/server/lib/editorial/checkRegistry.test.js+++ b/server/lib/editorial/checkRegistry.test.js@@ -21,7 +21,6 @@ import {editorialPriorFindingsDigest,EDITORIAL_PRIOR_DIGEST_MAX,EDITORIAL_PRIOR_DIGEST_CHARS,- EDITORIAL_PRIOR_DIGEST_TOKENS,} from './checkRegistry.js';const NAMING = 'naming.dissimilar-names';@@ -596,13 +595,13 @@ 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',+ // 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;- digestReserve = opts.digestReserveTokens;return ['CHUNK_ONE', 'CHUNK_TWO'];},callStagedLLM: async (_stage, vars) => {@@ -616,11 +615,11 @@ describe('cross-chunk continuity digest (#1383)', () => {},...ctxExtras,});- return { seen, overhead, digestReserve };+ return { seen, overhead };};- it('style.conformance feeds the prior-chunk digest to later chunks and reserves budget for it', async () => {- const { seen, overhead, digestReserve } = await runTwoChunks('style.conformance', {+ it('style.conformance feeds the prior-chunk digest to later chunks', async () => {+ const { seen, overhead } = await runTwoChunks('style.conformance', {series: { styleGuide: { tense: 'past', povPerson: 'first' } },});// First chunk is untouched (no prior findings yet).@@ -629,10 +628,35 @@ 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, and the digest- // reserve is passed to the planner so it can carve room out of later chunks.+ // The style-guide expectations are budgeted as prompt overhead.expect(overhead).toBeGreaterThan(0);- expect(digestReserve).toBe(EDITORIAL_PRIOR_DIGEST_TOKENS);+ });++ it('skips the digest (sends the manuscript whole) when it would not fit the chunk budget', async () => {+ const seen = [];+ // usableChars is just barely above the chunk text, so the (larger) digest can't+ // fit — manuscript coverage must win, so the chunk is sent without a digest.+ await getCheck('style.conformance').run({+ config: { maxFindings: 12 },+ severityDefault: 'medium',+ series: { styleGuide: { tense: 'past', povPerson: 'first' } },+ planManuscriptChunks: async () => {+ const chunks = ['CHUNK_ONE', 'CHUNK_TWO'];+ chunks.usableChars = 'CHUNK_TWO'.length; // no spare room for any digest+ return chunks;+ },+ callStagedLLM: async (_stage, vars) => {+ seen.push(vars.manuscript);+ const findings = seen.length === 1+ ? [{ severity: 'high', issueNumber: 1, problem: 'tense slip', anchorQuote: 'q' }]+ : [];+ return { content: { findings } };+ },+ });+ // Even though chunk one produced a finding, the tight budget means chunk two is+ // sent verbatim — no digest, no dropped manuscript text.+ expect(seen[1]).toBe('CHUNK_TWO');+ expect(seen[1]).not.toContain('EARLIER parts of this manuscript');});it('objects.unmotivated-interaction feeds the prior-chunk digest to later chunks', async () => {@@ -648,7 +672,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, digestReserve } = await runTwoChunks(INFODUMP, {+ const { seen } = await runTwoChunks(INFODUMP, {manuscript: 'CHUNK_ONE',});expect(seen[0]).toBe('CHUNK_ONE');@@ -656,8 +680,6 @@ 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.jsindex fa5e87f2d7..fa1afc4ceb 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, CHARS_PER_TOKEN } from '../../../lib/contextBudget.js';+import { planManuscriptPass } 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, digestReserveTokens = 0 } = {}) => {+ planManuscriptChunks: async (stage, { overheadTokens = 0 } = {}) => {if (!sections.length) return [];const { contextWindow } = await resolveStageContext(stage, { providerOverride, modelOverride });const plan = planManuscriptPass({@@ -156,12 +156,12 @@ export async function runEditorialChecks(seriesId, options = {}) {const corpora = plan.mode === 'whole'? [manuscript]: plan.chunks.map((c) => sectionsCorpus(c.sections));- // 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))));+ const chunks = corpora.map((c) => c.slice(0, plan.usableChars));+ // Expose the per-chunk budget so a cross-chunk-digest check can fit its+ // digest into each chunk's spare room without overflowing the window or+ // displacing manuscript text (see runChunkedManuscriptCheck).+ chunks.usableChars = plan.usableChars;+ return chunks;},};