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 (claude): budget for the inter-section join separator when packing chunks

[._.]/ Adam Eivya68ee05331e4
diff --git a/server/lib/contextBudget.js b/server/lib/contextBudget.js
index c251dbee13..d182a89adb 100644
--- a/server/lib/contextBudget.js
+++ b/server/lib/contextBudget.js
@@ -23,6 +23,12 @@ export const FALLBACK_CONTEXT_WINDOW = 8_192;
/** chars/4 token estimate. Conservative (real tokenizers pack denser). */
export const estimateTokens = (text) => Math.ceil(String(text ?? '').length / CHARS_PER_TOKEN);
+// Token cost of the separator `sectionsCorpus` inserts between packed sections
+// (mirrors its `\n\n---\n\n` join). The packer budgets for it so a chunk packed
+// to the token limit doesn't overflow `usableChars` by the separators and get
+// its last section's tail trimmed by the consumer's slice.
+const SECTION_SEPARATOR_TOKENS = estimateTokens('\n\n---\n\n');
+
const clampMargin = (m) => (Number.isFinite(m) && m >= 0 && m < 1 ? m : DEFAULT_SAFETY_MARGIN);
const resolveWindow = (contextWindow) =>
@@ -109,8 +115,12 @@ export function planManuscriptPass({
const withTokens = list.map((s) => ({ section: s, tokens: estimateTokens(s?.text) }));
const totalTokens = withTokens.reduce((n, x) => n + x.tokens, 0);
- // Everything fits → one call.
- if (totalTokens <= usableTokens) {
+ // Everything fits → one call. The whole-corpus render joins the sections with
+ // a separator, so the fit decision counts those too — otherwise a corpus that
+ // only fits *without* separators is mislabeled `whole` and the consumer's
+ // slice trims its tail.
+ const renderedTokens = totalTokens + Math.max(0, list.length - 1) * SECTION_SEPARATOR_TOKENS;
+ if (renderedTokens <= usableTokens) {
return { mode: 'whole', usableTokens, usableChars, totalTokens };
}
@@ -129,17 +139,21 @@ export function planManuscriptPass({
// Greedy first-fit packing, order-preserving. Each chunk stays under the
// usable budget unless a single (unsplittable) section already exceeds it.
+ // The join separator between packed sections is counted so a chunk's rendered
+ // corpus never overflows usableChars (and gets sliced) once the consumer
+ // re-joins the sections.
const chunks = [];
let cur = [];
let curTokens = 0;
for (const { section, tokens } of units) {
- if (cur.length && curTokens + tokens > usableTokens) {
+ const sep = cur.length ? SECTION_SEPARATOR_TOKENS : 0;
+ if (cur.length && curTokens + sep + tokens > usableTokens) {
chunks.push({ sections: cur, tokens: curTokens });
cur = [];
curTokens = 0;
}
+ curTokens += (cur.length ? SECTION_SEPARATOR_TOKENS : 0) + tokens;
cur.push(section);
- curTokens += tokens;
}
if (cur.length) chunks.push({ sections: cur, tokens: curTokens });
return { mode: 'chunked', usableTokens, usableChars, totalTokens, chunks };
diff --git a/server/lib/contextBudget.test.js b/server/lib/contextBudget.test.js
index b01805e9f8..6374ffe1dc 100644
--- a/server/lib/contextBudget.test.js
+++ b/server/lib/contextBudget.test.js
@@ -141,6 +141,28 @@ describe('contextBudget', () => {
expect(plan.mode).toBe('whole');
});
+ it('budgets for the inter-section join separator when packing whole sections', () => {
+ // 8 sections of exactly 1024 tokens (4096 chars) each sum to exactly the
+ // 8192-token budget. Without accounting for the `\n\n---\n\n` join, all 8
+ // would pack into one chunk whose rendered corpus (32831 chars) overflows
+ // usableChars (32768) and the consumer's slice trims the last section's tail.
+ const paddedSection = (n) => {
+ const title = 'T';
+ const h = header(n, title);
+ return { number: n, title, stageId: 'script', content: 'x'.repeat(4_096 - (h.length + 2)), text: `${h}\n\n${'x'.repeat(4_096 - (h.length + 2))}` };
+ };
+ const sections = Array.from({ length: 8 }, (_, i) => paddedSection(i + 1));
+ const plan = planManuscriptPass({ contextWindow: 8_192, sections, outputReserveTokens: 0, safetyMargin: 0 });
+ expect(plan.mode).toBe('chunked');
+ // Every chunk fits usableChars once rendered the way the consumers render it.
+ for (const chunk of plan.chunks) {
+ const corpus = chunk.sections.map((s) => `${header(s.number, s.title)}\n\n${s.content}`).join('\n\n---\n\n');
+ expect(corpus.length).toBeLessThanOrEqual(plan.usableChars);
+ }
+ // ...and at least one chunk genuinely packs multiple whole sections.
+ expect(plan.chunks.some((c) => c.sections.length > 1)).toBe(true);
+ });
+
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.