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
feat([issue-1386]): split an oversized manuscript section into sub-chunks instead of truncating its tail
[._.]/ Adam Eivy254998bb0b74
diff --git a/server/lib/contextBudget.js b/server/lib/contextBudget.jsindex 7fb8b0cff6..c251dbee13 100644--- a/server/lib/contextBudget.js+++ b/server/lib/contextBudget.js@@ -11,6 +11,8 @@* Pure / side-effect-free — unit-tested in contextBudget.test.js.*/+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;@@ -41,19 +43,58 @@ export function usableInputTokens({return Math.max(0, afterMargin - Math.max(0, outputReserveTokens) - Math.max(0, overheadTokens));}+/**+ * Expand one section into `{ section, tokens }` units that each fit the usable+ * budget. A section within budget passes through unchanged. An over-budget+ * section that follows the `${header}\n\n${body}` convention every consumer+ * uses (its `text` is the header-prefixed `content`) is split on `body` — via+ * the shared, lossless `chunkRawText` boundary splitter (paragraph → newline →+ * sentence → whitespace → hard cut), with the header preserved on each piece+ * via the retained meta fields. So downstream `sectionsCorpus(chunk.sections)`+ * re-attaches identical issue attribution and the consumers' first-wins+ * finding-merge still dedups across the sub-chunks. `maxChunks: Infinity`+ * disables `chunkRawText`'s chunk-count ceiling so an arbitrarily long section+ * is never trimmed — the whole point of this split. A section that can't be+ * split that way (no string body, or a header that alone exceeds the budget)+ * passes through as one over-budget unit the caller truncates, exactly as+ * before.+ */+function expandSection(section, text, tokens, usableTokens, usableChars) {+ if (tokens <= usableTokens) return [{ section, tokens }];+ const body = section?.content;+ if (typeof body !== 'string' || body.length === 0 || typeof text !== 'string' || !text.endsWith(body)) {+ return [{ section, tokens }];+ }+ const prefix = text.slice(0, text.length - body.length); // `${header}\n\n`+ const bodyBudgetChars = usableChars - prefix.length;+ if (bodyBudgetChars <= 0) return [{ section, tokens }]; // header alone over budget+ const pieces = chunkRawText(body, { maxChars: bodyBudgetChars, maxChunks: Number.POSITIVE_INFINITY });+ if (pieces.length <= 1) return [{ section, tokens }];+ return pieces.map((piece) => {+ const sub = { ...section, content: piece, text: `${prefix}${piece}` };+ return { section: sub, tokens: estimateTokens(sub.text) };+ });+}+/*** 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.+ * contribution to the corpus (header + body). Order is preserved. A section+ * that also carries a string `content` (so `text === \`${header}\n\n${content}\``)+ * can be split when it alone overflows the window.* @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).+ * When a single section is larger than the usable budget it is split into+ * multiple header-preserving sub-chunks (on paragraph/sentence boundaries) so+ * its tail is reviewed instead of truncated — unless it can't be split that way+ * (no string body / a header that alone exceeds the budget), in which case it+ * stays one over-budget unit the caller truncates, as before. A corpus that+ * fits the window (including the empty / single-fitting-section case) is+ * `whole`.*/export function planManuscriptPass({contextWindow,@@ -68,16 +109,30 @@ export function planManuscriptPass({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) {+ // Everything fits → one call.+ if (totalTokens <= usableTokens) {+ return { mode: 'whole', usableTokens, usableChars, totalTokens };+ }++ // Over budget → expand any over-budget section into header-preserving+ // sub-sections (so an oversized single section's tail is reviewed, not+ // truncated — #1386), then greedily first-fit order-preserving chunks.+ const units = withTokens.flatMap(({ section, tokens }) =>+ expandSection(section, section?.text, tokens, usableTokens, usableChars));++ // A lone section that couldn't be split stays one over-budget `whole` pass —+ // identical to the prior behavior (the caller truncates it). Only emit+ // `chunked` when there's genuinely more than one unit to feed.+ if (units.length <= 1) {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).+ // usable budget unless a single (unsplittable) section already exceeds it.const chunks = [];let cur = [];let curTokens = 0;- for (const { section, tokens } of withTokens) {+ for (const { section, tokens } of units) {if (cur.length && curTokens + tokens > usableTokens) {chunks.push({ sections: cur, tokens: curTokens });cur = [];diff --git a/server/lib/contextBudget.test.js b/server/lib/contextBudget.test.jsindex 12f3cb060c..b01805e9f8 100644--- a/server/lib/contextBudget.test.js+++ b/server/lib/contextBudget.test.js@@ -9,6 +9,21 @@ import {const section = (n, chars) => ({ number: n, text: 'x'.repeat(chars) });+// A realistic section following the `${header}\n\n${content}` convention every+// consumer builds before calling planManuscriptPass — so it can be split when+// it alone overflows the window.+const header = (n, title) => `# Issue ${n}${title ? ` — ${title}` : ''} (script)`;+const realSection = (n, content, title = `T${n}`) => ({+ number: n,+ title,+ stageId: 'script',+ content,+ text: `${header(n, title)}\n\n${content}`,+});+// A body of `paras` paragraphs, each `chars` long, joined by blank lines.+const paragraphs = (paras, chars) =>+ Array.from({ length: paras }, (_, i) => `${String.fromCharCode(97 + (i % 26))}`.repeat(chars)).join('\n\n');+describe('contextBudget', () => {describe('estimateTokens', () => {it('estimates chars/4, rounding up, and tolerates null', () => {@@ -51,7 +66,9 @@ describe('contextBudget', () => {expect(plan.usableChars).toBe(plan.usableTokens * CHARS_PER_TOKEN);});- it('returns whole for a single section even if it exceeds the window', () => {+ it('returns whole for a single over-budget section that cannot be split (no string body)', () => {+ // `section()` has `text` but no `content`, so it can't be split on a body+ // — it stays one over-budget `whole` pass the caller truncates, as before.const plan = planManuscriptPass({contextWindow: 8_192,sections: [section(1, 1_000_000)],@@ -59,6 +76,88 @@ describe('contextBudget', () => {expect(plan.mode).toBe('whole');});+ it('splits a single over-budget section into header-preserving sub-chunks instead of truncating', () => {+ // window 8192, margin 0, reserve 0 -> usable 8192 tokens = 32768 chars.+ // One section whose body is ~200k chars (~50k tokens) overflows alone.+ const body = paragraphs(40, 5_000); // 40 paras * 5000 chars + separators+ const plan = planManuscriptPass({+ contextWindow: 8_192,+ sections: [realSection(7, body, 'Long One')],+ outputReserveTokens: 0,+ safetyMargin: 0,+ });+ expect(plan.mode).toBe('chunked');+ expect(plan.chunks.length).toBeGreaterThan(1);++ // Every sub-chunk fits the usable budget once rendered (header + piece).+ const rendered = (s) => `${header(s.number, s.title)}\n\n${s.content}`;+ for (const chunk of plan.chunks) {+ const corpus = chunk.sections.map(rendered).join('\n\n---\n\n');+ expect(corpus.length).toBeLessThanOrEqual(plan.usableChars);+ }++ // Header attribution is preserved on every piece (so downstream+ // first-wins finding-merge dedups by the same issue), and no body text+ // is dropped — concatenating the pieces reproduces the original body.+ const subs = plan.chunks.flatMap((c) => c.sections);+ for (const s of subs) {+ expect(s.number).toBe(7);+ expect(s.title).toBe('Long One');+ expect(s.stageId).toBe('script');+ }+ expect(subs.map((s) => s.content).join('')).toBe(body);+ });++ it('splits on paragraph boundaries when they fit the budget', () => {+ // usable 8192 tokens = 32768 chars; budget for the body is usableChars+ // minus the short header prefix. Paragraphs of 6000 chars -> ~5 per piece.+ const body = paragraphs(20, 6_000);+ const plan = planManuscriptPass({+ contextWindow: 8_192,+ sections: [realSection(3, body)],+ outputReserveTokens: 0,+ safetyMargin: 0,+ });+ expect(plan.mode).toBe('chunked');+ const subs = plan.chunks.flatMap((c) => c.sections);+ // Each piece except the last ends on a paragraph boundary (blank line),+ // never mid-paragraph.+ for (const s of subs.slice(0, -1)) {+ expect(s.content.endsWith('\n\n')).toBe(true);+ }+ expect(subs.map((s) => s.content).join('')).toBe(body);+ });++ it('keeps a single over-budget section whole when the header alone exceeds the budget', () => {+ // A pathologically tiny window (4 tokens = 16 chars, smaller than the+ // ~25-char header prefix), so there is no room for any body piece ->+ // falls back to one whole pass.+ const plan = planManuscriptPass({+ contextWindow: 4,+ sections: [realSection(1, paragraphs(10, 2_000))],+ outputReserveTokens: 0,+ safetyMargin: 0,+ });+ expect(plan.mode).toBe('whole');+ });++ it('splits an over-budget section while packing its small neighbors normally', () => {+ // One huge section between two small ones: the huge one splits, the small+ // ones still pack/standalone, and overall order is preserved.+ const sections = [+ realSection(1, paragraphs(2, 1_000)),+ realSection(2, paragraphs(40, 5_000)),+ realSection(3, paragraphs(2, 1_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));+ // Section 2's pieces all carry number 2, appearing contiguously between 1 and 3.+ expect(order[0]).toBe(1);+ expect(order[order.length - 1]).toBe(3);+ expect(order.filter((n) => n === 2).length).toBeGreaterThan(1);+ });+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).