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): token-driven context trim + cap floor at manuscript size (#1459)
Adam Eivyd0d17b12f18b
diff --git a/server/lib/contextBudget.js b/server/lib/contextBudget.jsindex 2268489107..34c31dfa91 100644--- a/server/lib/contextBudget.js+++ b/server/lib/contextBudget.js@@ -167,7 +167,7 @@ export function fitContextToManuscriptFloor(context, {const fixed = Math.max(0, fixedOverheadTokens);const contextTokens = entries.reduce((n, [k]) => n + estimateTokens(blocks[k]), 0);- const { allowedContextChars, trimmed } = capContextOverhead({+ const { allowedContextTokens, trimmed } = capContextOverhead({contextWindow,contextTokens,fixedOverheadTokens: fixed,@@ -180,22 +180,24 @@ export function fitContextToManuscriptFloor(context, {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;+ // Trim the largest block first (by char length) so the unbounded scene map+ // absorbs the cut while bounded blocks survive. Drive the loop on the TOKEN+ // budget, not aggregate chars: `estimateTokens` ceilings per block, so several+ // small blocks could fit the char budget yet still sum to more than+ // `allowedContextTokens` — and the manuscript would undershoot its floor. Re-sum+ // the per-block token estimate after each trim and keep shrinking the current+ // largest until the total token cost is within budget.const largestFirst = entries.map(([k]) => k).sort((a, b) => blocks[b].length - blocks[a].length);+ const tokenSum = () => entries.reduce((n, [k]) => n + estimateTokens(blocks[k]), 0);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;+ if (tokenSum() <= allowedContextTokens) break;+ // Chars this block must give back so the TOTAL token cost fits: the current+ // overshoot (tokens) converted to chars, removed from this (largest) block.+ const overshootTokens = tokenSum() - allowedContextTokens;+ blocks[k] = trimContextToBudget(blocks[k], Math.max(0, blocks[k].length - overshootTokens * CHARS_PER_TOKEN));}- const trimmedContextTokens = entries.reduce((n, [k]) => n + estimateTokens(blocks[k]), 0);- return { context: blocks, overheadTokens: fixed + trimmedContextTokens, trimmed: true };+ return { context: blocks, overheadTokens: fixed + tokenSum(), trimmed: true };}/**diff --git a/server/lib/contextBudget.test.js b/server/lib/contextBudget.test.jsindex a6bcd0f2cd..7e2ac3153f 100644--- a/server/lib/contextBudget.test.js+++ b/server/lib/contextBudget.test.js@@ -312,6 +312,42 @@ describe('contextBudget', () => {expect(estimateTokens(r.context.sceneMap)).toBeLessThan(estimateTokens(ctx.sceneMap));});+ it('keeps the TOTAL token cost within the allowed budget across many small blocks (per-block ceiling)', () => {+ // estimateTokens ceilings per block, so several small blocks could each fit a+ // char budget yet sum to more tokens than allowed. The trim must drive on the+ // token sum, not aggregate chars, or the manuscript undershoots its floor.+ // Odd-length blocks (1001 chars → ceil(1001/4)=251 tokens each) so per-block+ // ceiling rounding accumulates; 30 of them (≈7530 tokens) overflows a 4K window.+ const ctx = Object.fromEntries(Array.from({ length: 30 }, (_, i) => [`b${i}`, 'x'.repeat(1_001)]));+ const window = 4_000;+ const fixed = 500;+ const r = fitContextToManuscriptFloor(ctx, {+ contextWindow: window,+ fixedOverheadTokens: fixed,+ outputReserveTokens: 0,+ safetyMargin: 0,+ });+ expect(r.trimmed).toBe(true);+ const usable = usableInputTokens({ contextWindow: window, overheadTokens: r.overheadTokens, outputReserveTokens: 0, safetyMargin: 0 });+ // The floor holds EXACTLY now — the manuscript keeps at least the full floor,+ // even though per-block ceiling rounding would have undershot a char-only trim.+ expect(usable).toBeGreaterThanOrEqual(MANUSCRIPT_FLOOR_TOKENS);+ });++ it('respects a caller-supplied smaller floor (so a short manuscript is not trimmed needlessly)', () => {+ // A modest context + a low floor that the window comfortably fits → no trim.+ const ctx = { sceneMap: 'S'.repeat(4_000) };+ const r = fitContextToManuscriptFloor(ctx, {+ contextWindow: 8_000,+ fixedOverheadTokens: 500,+ outputReserveTokens: 0,+ safetyMargin: 0,+ floorTokens: 100, // a tiny manuscript only needs a little room+ });+ expect(r.trimmed).toBe(false);+ expect(r.context.sceneMap).toBe(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/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.jsindex 9702a0e124..06c28cdf2a 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, fitContextToManuscriptFloor } from '../../../lib/contextBudget.js';+import { planManuscriptPass, fitContextToManuscriptFloor, estimateTokens, MANUSCRIPT_FLOOR_TOKENS } 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';@@ -373,10 +373,17 @@ export async function runEditorialChecks(seriesId, options = {}) {let effectiveOverhead = overheadTokens;let fittedContext = null;if (context && typeof context === 'object') {+ // Reserve no more than the manuscript actually needs: a short manuscript+ // that fits alongside the full context shouldn't get its context trimmed+ // just to hold open the full floor. Cap the reserved floor at the+ // manuscript's own token cost (the floor only bites a manuscript large+ // enough to want it).+ const floorTokens = Math.min(MANUSCRIPT_FLOOR_TOKENS, estimateTokens(manuscript));const fit = fitContextToManuscriptFloor(context, {contextWindow,fixedOverheadTokens,outputReserveTokens: EDITORIAL_OUTPUT_RESERVE_TOKENS,+ floorTokens,});effectiveOverhead = fit.overheadTokens;fittedContext = fit.context;