@logictan/dsh-verbatim-compaction 0.11.1 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -15,7 +15,7 @@
15
15
  * This backend keeps the base class's replay, range selection, durable
16
16
  * transaction and shrink guard untouched and overrides only `summarize()`, the
17
17
  * one hook the base class documents for exactly this purpose. The replacement
18
- * summary is built deterministically, with no model call:
18
+ * summary is built from the log, with one model call per batch of turns:
19
19
  *
20
20
  * - user and assistant prose verbatim, per turn;
21
21
  * - tool results reduced to one line (tool names, call counts, bytes);
@@ -55,8 +55,6 @@ export const DIGEST_TOKEN_CEILING = 20000;
55
55
  const FRAME_TOKENS = 86;
56
56
  /** Safety margin below the shrink guard, in tokens. */
57
57
  const SHRINK_MARGIN_TOKENS = 512;
58
- /** Per-turn floor when assistant prose has to be truncated, in characters. */
59
- const MIN_TURN_CHARS = 800;
60
58
  /**
61
59
  * Share of the budget user prose may occupy before oldest-first truncation.
62
60
  *
@@ -233,27 +231,25 @@ export function isErrorResult(event) {
233
231
  }
234
232
  /** Directive appended as the final user message of the extraction call. */
235
233
  const EXTRACT_INSTRUCTION = [
236
- 'You are summarizing a batch of turns from a coding session for a compaction checkpoint.',
237
- 'Each item is introduced by a line `=== SLOT <key> (turn <n>) ===` and contains the user request, the assistant prose (may be empty), and a trace of the tool calls it made (descriptions only) plus any results the log marked as errors.',
238
- '',
239
234
  'Reply with ONE JSON object and nothing else. No prose, no code fence, no markdown.',
240
- 'Shape: {"slots":[{"key":"<the slot key>","did":["…"],"concluded":["…"],"overturned":["…"]}]}',
241
- '',
242
- 'Rules for the fields:',
243
- '- `key` must be copied exactly from the `=== SLOT <key> ===` line. One entry per slot.',
244
- '- `did`: what was actually done, concretely. `concluded`: findings, decisions or measurements a later turn would need. `overturned`: earlier conclusions this turn disproved.',
245
- '- Each field is an array of short strings, at most two per field. Use `[]` for a field with nothing to say. Omit the whole entry when nothing substantive happened.',
246
- '- Write only the content of a line. Never write a heading, a bullet, or a field name inside a string.',
247
- '- Do not describe the tool calls themselves ("ran bash", "explored the repo"). State what came out of them.',
248
- '- Do not repeat a conclusion an earlier turn already stated.',
235
+ 'Shape: {"slots":[{"key":"<the slot key>","did":["…"],"concluded":["…"],"overturned":["…"],"asked":[{"question":"…","options":["…"]}]}]}',
236
+ 'Rules:',
237
+ '- `key` must be copied exactly from the `=== SLOT <key> ===` line. One entry per slot, in the order given. Never skip a slot.',
238
+ '- `did`: what was done, at most two short strings. `concluded`: findings a later turn needs, at most two. `overturned`: earlier conclusions this turn disproved.',
239
+ '- Each field is an array of short strings. Use [] for a field with nothing to say.',
240
+ '- Never write a heading, a bullet, or a field name inside a string.',
249
241
  '- Never invent. If the material does not support a claim, leave the field empty.',
242
+ // A question is not reliably the last paragraph: measured over 231 real turns
243
+ // that drew a short reply, 34% had prose after it (p90 = 7 paragraphs, max 24).
244
+ '- `asked`: one entry per question this turn put to the user and was still waiting on when it ended. A question is anywhere in the prose, not only the last paragraph.',
245
+ // And the options are usually further up: in 26 of 231 turns was the list in the
246
+ // question's own paragraph or the one before it.
247
+ '- `options`: what the user could pick from, in order, one short line each, with their own numbering stripped. The list is often a paragraph or two above the question. Use [] when the question offered none.',
248
+ // The reply is the next turn's `## user` line, already verbatim in the digest.
249
+ // Asking for it here printed the same sentence twice.
250
+ "- Use [] for `asked` when the turn asked nothing. Do not report the user's reply.",
250
251
  '',
251
- 'Do not report questions and answers: those are read from the session log directly and need no summary.',
252
- '',
253
- // Measured on a real 32-slot session: whole batches came back in English while
254
- // the material was Chinese, so the digest mixed two languages for one
255
- // conversation.
256
- 'Write the strings in the same language as the material. A session whose requests are Chinese gets Chinese text; do not switch to English.',
252
+ 'Write strings in the same language as the material. A session whose requests are Chinese gets Chinese text; do not switch to English.',
257
253
  ].join('\n');
258
254
  /**
259
255
  * Parse the model's JSON reply into per-slot extractions.
@@ -296,6 +292,31 @@ export function parseExtraction(answer) {
296
292
  .filter((item) => !/^(?:\(?none\)?|n\/a|na|-{1,2}|无|沒有|没有)$/i.test(item))
297
293
  .filter((item) => !/^(?:未提问|无提问|没有提问|no questions? (?:were |was )?asked|none asked)[。.!!]*$/i.test(item))
298
294
  : []);
295
+ // Asked is a list of objects, not of strings: a question without its options
296
+ // turns the user's `1` into a number that selects nothing.
297
+ const pairs = (value) => (Array.isArray(value)
298
+ ? value
299
+ .flatMap((item) => {
300
+ if (typeof item !== 'object' || item === null)
301
+ return [];
302
+ const record = item;
303
+ const question = typeof record['question'] === 'string'
304
+ ? record['question'].replace(/\s+/g, ' ').trim()
305
+ : '';
306
+ if (question.length === 0)
307
+ return [];
308
+ const options = Array.isArray(record['options'])
309
+ ? record['options']
310
+ .filter((option) => typeof option === 'string')
311
+ // The renderer supplies the numbering, so a model that echoes the source
312
+ // list's own `1.` would print `1. 1. …`. Stripped here rather than asked
313
+ // for in the prompt alone: three of five real runs kept it.
314
+ .map((option) => option.replace(/\s+/g, ' ').replace(/^\s*\d{1,2}\s*[.、)]\s*/, '').trim())
315
+ .filter((option) => option.length > 0)
316
+ : [];
317
+ return [{ question, options }];
318
+ })
319
+ : []);
299
320
  for (const slot of slots) {
300
321
  if (typeof slot !== 'object' || slot === null)
301
322
  continue;
@@ -307,6 +328,7 @@ export function parseExtraction(answer) {
307
328
  did: strings(record['did']),
308
329
  concluded: strings(record['concluded']),
309
330
  overturned: strings(record['overturned']),
331
+ asked: pairs(record['asked']),
310
332
  });
311
333
  }
312
334
  return out;
@@ -318,7 +340,7 @@ export function parseExtraction(answer) {
318
340
  * @returns markdown with a heading per non-empty field; empty string when every
319
341
  * field is empty.
320
342
  */
321
- export function renderExtractionBlock(extraction) {
343
+ export function renderExtractionBlock(extraction, level = 3) {
322
344
  if (extraction === undefined)
323
345
  return '';
324
346
  const lines = [];
@@ -327,15 +349,100 @@ export function renderExtractionBlock(extraction) {
327
349
  return;
328
350
  lines.push(`## ${heading}`, ...items.map((item) => `- ${item}`));
329
351
  };
330
- section('Did', extraction.did);
331
- section('Concluded', extraction.concluded);
332
- section('Overturned', extraction.overturned);
352
+ // `level` is how many of the graded sections survive: 3 keeps all, 2 drops
353
+ // Overturned, 1 keeps only Did, 0 keeps only Asked. Asked is never dropped by
354
+ // the level because it is the one section nothing later can rebuild — the
355
+ // reply arrives in the next turn, but the question and its options exist only
356
+ // here. See `renderDigest` for why the ladder exists at all.
357
+ if (level >= 1)
358
+ section('Did', extraction.did);
359
+ if (level >= 2)
360
+ section('Concluded', extraction.concluded);
361
+ if (level >= 3)
362
+ section('Overturned', extraction.overturned);
363
+ // Asked goes last and its options are listed under it, so the user's reply — the
364
+ // next `## user` line — lands directly under the list it chose from.
365
+ if (extraction.asked.length > 0) {
366
+ lines.push('## Asked');
367
+ for (const pair of extraction.asked) {
368
+ lines.push(`- ${pair.question}`);
369
+ // Indented under the question so a reader cannot mistake an option for a
370
+ // separate question, and numbered so the reply's digit has something to
371
+ // point at.
372
+ for (const [index, option] of pair.options.entries()) {
373
+ lines.push(` ${index + 1}. ${option}`);
374
+ }
375
+ }
376
+ }
333
377
  return lines.join('\n');
334
378
  }
379
+ /**
380
+ * The group starts a fold walk visits, oldest first, one entry per group.
381
+ *
382
+ * Extracted so the walk's bounds are testable without a session, a logger and a
383
+ * model: the walk itself was where two defects lived — a bound that skipped the
384
+ * last group, and a start advanced from the success count, which retried a failed
385
+ * group on every pass.
386
+ *
387
+ * @param sectionCount - how many sections the digest has.
388
+ * @returns the start index of each group, in order.
389
+ */
390
+ export function foldGroupStarts(sectionCount) {
391
+ const starts = [];
392
+ for (let start = 0; start < sectionCount; start += CONDENSE_GROUP)
393
+ starts.push(start);
394
+ return starts;
395
+ }
335
396
  /** Turns handed to one extraction call. */
336
397
  const TURNS_PER_CALL = 8;
337
- /** Output tokens allowed per turn in an extraction call. */
338
- const EXTRACT_TOKENS_PER_TURN = 220;
398
+ /**
399
+ * Sections folded into one condensed block when the digest overflows.
400
+ *
401
+ * Each fold is a model call, so the group size trades calls against compression.
402
+ * Simulated on a 700- and a 1200-turn digest at the measured 8.2% fold ratio:
403
+ *
404
+ * group 20 → 19 and 52 calls
405
+ * group 50 → 8 and 21 calls
406
+ * group 100 → 4 and 11 calls
407
+ *
408
+ * Larger groups fold more text per call, which is also where the ratio holds
409
+ * best: a 20-section group is small enough that the model's own paragraph is a
410
+ * larger share of it. 100 keeps a long session to a handful of calls.
411
+ */
412
+ const CONDENSE_GROUP = 100;
413
+ /**
414
+ * Output tokens allowed for one condensation call.
415
+ *
416
+ * A condensed block stands in for `CONDENSE_GROUP` sections, so it has to be far
417
+ * smaller than what it replaces to buy any room at all. Measured on 12000
418
+ * characters of real digest: the answer ran 565 tokens and produced 987
419
+ * characters, 8.2% of the input.
420
+ *
421
+ * The cap is far above that answer because thinking is charged to the same
422
+ * budget and is not small: the same call spent 1873 tokens thinking. At a 1200
423
+ * cap it returned an empty string in one run out of one — the thinking block
424
+ * took the whole allowance, the same failure the extraction call had.
425
+ */
426
+ const CONDENSE_TOKENS = 6000;
427
+ const CONDENSE_INSTRUCTION = [
428
+ 'The text above is the digest of a run of already-finished turns from a coding session.',
429
+ 'Fold it into one short paragraph that a later turn can read to know what that stretch established.',
430
+ 'Keep: decisions still in force, constraints that still apply, conclusions a later turn would otherwise redo, and anything later turns disproved.',
431
+ 'Drop: per-turn narration, restatements, and detail already superseded by later turns in the same run.',
432
+ 'Reply with the paragraph and nothing else. No heading, no bullets, no code fence, no preamble.',
433
+ 'Write in the same language as the material.',
434
+ ].join('\n');
435
+ /**
436
+ * Output tokens allowed per turn in an extraction call.
437
+ *
438
+ * Raised from 220 when `asked` was added. The model thinks before it answers and
439
+ * thinking is charged to the same `maxTokens`, so the answer's own budget has to
440
+ * cover both. Measured on real 8-slot batches: thinking alone ran 1057–4086
441
+ * tokens, and a cap of `220 x 8 + 1000` cut one run off mid-JSON, which parsed to
442
+ * zero slots and lost the whole batch. `900` per slot plus the reserve below
443
+ * parsed 8 of 8 on every attempt.
444
+ */
445
+ const EXTRACT_TOKENS_PER_TURN = 900;
339
446
  /**
340
447
  * Fixed thinking reserve added to every extraction call's `maxTokens`.
341
448
  *
@@ -485,89 +592,14 @@ function pathArgumentOf(argumentsJson) {
485
592
  return undefined;
486
593
  }
487
594
  }
488
- /**
489
- * The question an `ask_user_question` call put, with its options, or undefined.
490
- *
491
- * @param argumentsJson - the call's raw arguments.
492
- * @returns one line per question, options appended in brackets.
493
- */
494
- function questionTextOf(argumentsJson) {
495
- let parsed;
496
- try {
497
- parsed = JSON.parse(argumentsJson);
498
- }
499
- catch {
500
- return undefined;
501
- }
502
- if (typeof parsed !== 'object' || parsed === null)
503
- return undefined;
504
- const questions = parsed['questions'];
505
- if (!Array.isArray(questions))
506
- return undefined;
507
- const lines = questions
508
- .map((question) => {
509
- if (typeof question !== 'object' || question === null)
510
- return '';
511
- const record = question;
512
- const text = typeof record['question'] === 'string'
513
- ? record['question']
514
- : typeof record['header'] === 'string' ? record['header'] : '';
515
- if (text.trim().length === 0)
516
- return '';
517
- const options = Array.isArray(record['options'])
518
- ? record['options']
519
- .map((option) => (typeof option === 'object' && option !== null
520
- ? String(option['label'] ?? '')
521
- : ''))
522
- .filter((label) => label.length > 0)
523
- : [];
524
- return options.length === 0 ? text.trim() : `${text.trim()} [${options.join(' / ')}]`;
525
- })
526
- .filter((line) => line.length > 0);
527
- return lines.length > 0 ? lines.join('\n') : undefined;
528
- }
529
- /**
530
- * The answer carried by an `ask_user_question` result, or undefined.
531
- *
532
- * @param text - the result body.
533
- * @returns the chosen labels, or the typed reply when nothing was chosen.
534
- */
535
- function answerTextOf(text) {
536
- let parsed;
537
- try {
538
- parsed = JSON.parse(text);
539
- }
540
- catch {
541
- return undefined;
542
- }
543
- if (typeof parsed !== 'object' || parsed === null)
544
- return undefined;
545
- const answers = parsed['answers'];
546
- if (!Array.isArray(answers))
547
- return undefined;
548
- const chosen = answers
549
- .flatMap((answer) => {
550
- if (typeof answer !== 'object' || answer === null)
551
- return [];
552
- const record = answer;
553
- const selected = record['selected'];
554
- const picked = Array.isArray(selected) ? selected.map((value) => String(value)) : [];
555
- // A typed answer arrives with `selected: []` and the text in `custom`.
556
- const typed = typeof record['custom'] === 'string' && record['custom'].trim().length > 0
557
- ? [record['custom'].trim()] : [];
558
- return [...picked, ...typed];
559
- })
560
- .filter((value) => value.length > 0);
561
- return chosen.length > 0 ? chosen.join(' / ') : undefined;
562
- }
563
595
  /** The turn number an event belongs to, when the log records one. */
564
596
  function turnOf(event) {
565
597
  const turn = event.data.turn;
566
598
  return typeof turn === 'number' && Number.isInteger(turn) ? turn : undefined;
567
599
  }
568
600
  /** A fresh, empty turn accumulator. */
569
- function emptyTurn(turn) {
570
- return { turn, user: [], assistant: [], tools: new Map(), resultBytes: 0, errors: [], writes: [], asked: [] };
601
+ function emptyTurn(turn, fromRequest = false) {
602
+ return { turn, fromRequest, user: [], assistant: [], tools: new Map(), resultBytes: 0, errors: [], writes: [] };
571
603
  }
572
604
  /**
573
605
  * Group append-origin surface events into per-turn digest material.
@@ -586,12 +618,12 @@ export function buildSections(events) {
586
618
  let current;
587
619
  let currentTurn;
588
620
  let lastTurn;
589
- const openTurn = (turn) => {
621
+ const openTurn = (turn, fromRequest = false) => {
590
622
  if (current === undefined) {
591
623
  current = { turns: [] };
592
624
  sections.push(current);
593
625
  }
594
- const next = emptyTurn(turn);
626
+ const next = emptyTurn(turn, fromRequest);
595
627
  current.turns.push(next);
596
628
  if (turn !== undefined)
597
629
  lastTurn = turn;
@@ -601,8 +633,6 @@ export function buildSections(events) {
601
633
  // objective on every round, so recording each copy would repeat it dozens of
602
634
  // times across a long autonomous run.
603
635
  const recordedObjectives = new Set();
604
- // Question text by tool-call id, so the matching result can be read as its answer.
605
- const pendingQuestions = new Map();
606
636
  for (const event of events) {
607
637
  if (event.type === 'turn/start') {
608
638
  const turn = turnOf(event);
@@ -623,7 +653,7 @@ export function buildSections(events) {
623
653
  // takes the user slot: it is the request this turn serves.
624
654
  current = { turns: [] };
625
655
  sections.push(current);
626
- currentTurn = openTurn(turnOf(event) ?? lastTurn);
656
+ currentTurn = openTurn(turnOf(event) ?? lastTurn, false);
627
657
  currentTurn.user.push(objective);
628
658
  continue;
629
659
  }
@@ -633,16 +663,6 @@ export function buildSections(events) {
633
663
  const text = textOf(event);
634
664
  currentTurn.resultBytes += text.length;
635
665
  const message = messageOf(event);
636
- // A question's own result is its answer. Recorded here rather than left to the
637
- // model, which dropped or reworded it depending on its heading style.
638
- const callId = message?.toolCallId;
639
- if (callId !== undefined) {
640
- const question = pendingQuestions.get(callId);
641
- if (question !== undefined) {
642
- pendingQuestions.delete(callId);
643
- currentTurn.asked.push({ question, answer: answerTextOf(text) ?? '(no answer recorded)' });
644
- }
645
- }
646
666
  if (message?.isError === true) {
647
667
  const firstLine = text.split('\n')[0] ?? '';
648
668
  currentTurn.errors.push(firstLine.slice(0, 100));
@@ -660,7 +680,7 @@ export function buildSections(events) {
660
680
  // what makes the digest readable after a hundred turns.
661
681
  current = { turns: [] };
662
682
  sections.push(current);
663
- currentTurn = openTurn(eventTurn);
683
+ currentTurn = openTurn(eventTurn, true);
664
684
  const text = textOf(event);
665
685
  if (text.length > 0)
666
686
  currentTurn.user.push(text);
@@ -683,11 +703,6 @@ export function buildSections(events) {
683
703
  if (text.length > 0)
684
704
  currentTurn.assistant.push(text);
685
705
  for (const call of toolCallsOf(event)) {
686
- if (call.name === 'ask_user_question') {
687
- const question = questionTextOf(call.arguments);
688
- if (question !== undefined)
689
- pendingQuestions.set(call.id, question);
690
- }
691
706
  currentTurn.tools.set(call.name, (currentTurn.tools.get(call.name) ?? 0) + 1);
692
707
  if (!WRITE_TOOLS.has(call.name))
693
708
  continue;
@@ -730,19 +745,35 @@ function withExtractions(sections, extracted) {
730
745
  function turnKey(sectionIndex, turnIndex) {
731
746
  return `${sectionIndex}:${turnIndex}`;
732
747
  }
748
+ /**
749
+ * A stable hex digest of one string, used as a cache key.
750
+ *
751
+ * FNV-1a, 32-bit, two seeds. Not cryptographic: the risk here is an accidental
752
+ * collision between two inputs, and 64 bits over a few hundred entries makes that
753
+ * vanishingly unlikely.
754
+ *
755
+ * @param input - the text to hash.
756
+ * @returns a stable hex key.
757
+ */
758
+ function hashText(input) {
759
+ let a = 0x811c9dc5;
760
+ let b = 0x01000193;
761
+ for (let index = 0; index < input.length; index += 1) {
762
+ const code = input.charCodeAt(index);
763
+ a = Math.imul(a ^ code, 0x01000193) >>> 0;
764
+ b = Math.imul(b ^ (code + index), 0x85ebca6b) >>> 0;
765
+ }
766
+ return `${a.toString(16)}${b.toString(16)}`;
767
+ }
733
768
  /**
734
769
  * Cache key for one slot's extraction material: a hash of everything the model
735
770
  * would be shown.
736
771
  *
737
772
  * The material, not the slot's position or turn number: positions shift as
738
773
  * history grows and numbers repeat, but identical material must produce an
739
- * identical extraction. Hashing the exact string `buildExtractionMaterial`
740
- * returns means a change anywhere in the user request, the prose, or the tool
741
- * trace invalidates the entry — nothing can silently go stale.
742
- *
743
- * FNV-1a, 32-bit, two seeds. Not cryptographic: the risk here is an accidental
744
- * collision between two turns, and 64 bits over a few hundred entries makes that
745
- * vanishingly unlikely.
774
+ * identical extraction. Hashing the exact string `buildExtractionMaterial` returns
775
+ * means a change anywhere in the user request, the prose, or the tool trace
776
+ * invalidates the entry — nothing can silently go stale.
746
777
  *
747
778
  * @param events - one slot's events, in log order.
748
779
  * @returns a stable hex key.
@@ -753,15 +784,7 @@ function materialKey(events) {
753
784
  .map((event) => textOf(event))
754
785
  .filter((text) => text.length > 0)
755
786
  .join('\n');
756
- const material = buildExtractionMaterial(events, prose);
757
- let a = 0x811c9dc5;
758
- let b = 0x01000193;
759
- for (let index = 0; index < material.length; index += 1) {
760
- const code = material.charCodeAt(index);
761
- a = Math.imul(a ^ code, 0x01000193) >>> 0;
762
- b = Math.imul(b ^ (code + index), 0x85ebca6b) >>> 0;
763
- }
764
- return `${a.toString(16)}${b.toString(16)}`;
787
+ return hashText(buildExtractionMaterial(events, prose));
765
788
  }
766
789
  /**
767
790
  * Render one section to digest text, truncating assistant prose to `capChars`.
@@ -774,77 +797,60 @@ function materialKey(events) {
774
797
  * The tool pointer line stays either way: it is one line, and it is the only
775
798
  * record of what was actually run when the prose and extraction both say little.
776
799
  */
777
- /**
778
- * Move the `## Asked` section to the end of one extraction block.
779
- *
780
- * The digest reads as a conversation, and the user's next message is often just
781
- * "8399" or "继续". That reply only makes sense beside the question it answers, so
782
- * Asked belongs at the bottom of the block. The model puts it first about as often
783
- * as last, so the order is fixed here rather than requested in the prompt.
784
- *
785
- * @param block - one extraction block, possibly malformed.
786
- * @returns the same block with Asked last; unchanged when Asked is absent or already last.
787
- */
788
- export function moveAskedLast(block, asked = []) {
789
- const lines = block.split('\n');
790
- // Recognise every form the model has used for this section, in both languages, so
791
- // it can be dropped. The content is regenerated from the log instead: four format
792
- // changes across runs each broke either the position or the wording, and the log
793
- // already holds both halves verbatim.
794
- const isAsked = (line) => /^\s*(?:#{0,6}\s*|[-*]\s+)?(?:\*\*)?(?:Asked|问)(?:\*\*)?\s*[::]?\s*$/i.test(line);
795
- const isAskedInline = (line) => /^\s*(?:[-*]\s+)?(?:\*\*)?(?:Asked|问)(?:\*\*)?\s*[::]/i.test(line);
796
- const isOther = (line) => /^\s*(?:#{0,6}\s*|[-*]\s+)?(?:\*\*)?(?:Did|Concluded|Overturned|做|结论|推翻)(?:\*\*)?\s*[::]?/i.test(line);
797
- const start = lines.findIndex((line) => isAsked(line) || isAskedInline(line));
798
- const kept = [...lines];
799
- if (start >= 0) {
800
- const inline = isAskedInline(kept[start] ?? '') && !isAsked(kept[start] ?? '');
801
- let end = start + 1;
802
- if (!inline) {
803
- while (end < kept.length && !isOther(kept[end] ?? ''))
804
- end += 1;
800
+ function renderSection(section, level, condensed, sectionIndex) {
801
+ const lines = [];
802
+ // The block that covers this section, if any. Looked up by scanning the keys
803
+ // rather than by probing one key per turn: a fold spans whole sections, so the
804
+ // covering key belongs to an earlier section, not to this turn's own key.
805
+ const index = sectionIndex ?? 0;
806
+ let covering;
807
+ if (condensed !== undefined) {
808
+ for (const [key, block] of condensed) {
809
+ const start = Number(key.split(':')[0]);
810
+ if (index >= start && index < start + block.covers) {
811
+ covering = { key, block };
812
+ break;
813
+ }
805
814
  }
806
- kept.splice(start, end - start);
807
815
  }
808
- while (kept.length > 0 && (kept.at(-1) ?? '').trim().length === 0)
809
- kept.pop();
810
- if (asked.length === 0)
811
- return kept.join('\n');
812
- const block_lines = asked.map(({ question, answer }) => {
813
- const q = question.split('\n').join(' ');
814
- return `- ${q} → ${answer}`;
815
- });
816
- return [...kept, '', '## Asked', ...block_lines].join('\n');
817
- }
818
- function renderSection(section, capChars) {
819
- const lines = [];
820
- for (const turn of section.turns) {
816
+ if (covering !== undefined) {
817
+ // The user line stays: a request is a standing constraint. Only the first
818
+ // covered section prints the folded text — the rest contribute their user
819
+ // lines alone, which is the room the condensation buys.
820
+ const start = Number(covering.key.split(':')[0]);
821
+ for (const turn of section.turns) {
822
+ if (turn.user.length > 0)
823
+ lines.push(`\n## user\n${turn.user.join('\n')}`);
824
+ }
825
+ if (index === start) {
826
+ const range = covering.block.covers <= 1
827
+ ? `section ${start + 1}`
828
+ : `sections ${start + 1}-${start + covering.block.covers}`;
829
+ lines.push(`\n### assistant\n## Condensed (condensed from ${range})\n- ${covering.block.text}`);
830
+ }
831
+ return lines.join('\n');
832
+ }
833
+ for (const [turnIndex, turn] of section.turns.entries()) {
821
834
  if (turn.user.length > 0)
822
835
  lines.push(`\n## user\n${turn.user.join('\n')}`);
823
836
  // An extraction whose every field is empty renders nothing: a heading followed by
824
837
  // no body reads as a turn that did something but says nothing.
825
- if (turn.extracted !== undefined && renderExtractionBlock(turn.extracted).length > 0) {
826
- let block = renderExtractionBlock(turn.extracted);
827
- if (capChars !== undefined && block.length > capChars) {
828
- block = `${block.slice(0, capChars)}\n…(+${block.length - capChars} chars)`;
829
- }
830
- // Errors and writes sit after the block: Asked has to be the last thing in the
831
- // turn, and the errors line directly under `## user` read as if the user had
832
- // said it. Asked is inside the block, so the trailer goes before Asked instead
833
- // — see moveAskedLast being applied after the trailer is joined.
838
+ if (turn.extracted !== undefined && renderExtractionBlock(turn.extracted, level).length > 0) {
839
+ const block = renderExtractionBlock(turn.extracted, level);
840
+ // The trailer goes *above* the block, not below it. `## Asked` is the block's
841
+ // last section and the user's reply is the very next line, so an errors line
842
+ // in between would separate the reply from the question it answers.
834
843
  const trailer = [];
835
844
  if (turn.errors.length > 0) {
836
845
  trailer.push(` errors: ${turn.errors.length}: ${turn.errors.slice(0, 3).join(' | ')}`);
837
846
  }
838
847
  if (turn.writes.length > 0)
839
848
  trailer.push(` wrote: ${turn.writes.join(', ')}`);
840
- const body = trailer.length > 0 ? `${block}\n${trailer.join('\n')}` : block;
841
- lines.push(`### assistant\n${moveAskedLast(body, turn.asked)}`);
849
+ const body = trailer.length > 0 ? `${trailer.join('\n')}\n${block}` : block;
850
+ lines.push(`### assistant\n${body}`);
842
851
  }
843
852
  else {
844
- let body = turn.assistant.join('\n');
845
- if (capChars !== undefined && body.length > capChars) {
846
- body = `${body.slice(0, capChars)}\n…(+${body.length - capChars} chars)`;
847
- }
853
+ const body = turn.assistant.join('\n');
848
854
  if (body.length > 0)
849
855
  lines.push(`### assistant\n${body}`);
850
856
  if (turn.errors.length > 0) {
@@ -856,56 +862,45 @@ function renderSection(section, capChars) {
856
862
  }
857
863
  return lines.join('\n');
858
864
  }
859
- /**
860
- * Total characters of turn bodies across every section: the extraction where a
861
- * turn has one, its prose otherwise.
862
- *
863
- * Both must count, because the cap applies to whichever body is rendered. When
864
- * only prose counted, a digest made almost entirely of extractions reported a
865
- * bound of zero, the bisection had nothing to shrink, and the renderer fell
866
- * through to dropping the oldest turns outright — which deleted the earliest
867
- * human messages, the standing constraints the digest exists to keep.
868
- */
869
- function assistantChars(sections) {
870
- let total = 0;
871
- for (const section of sections) {
872
- for (const turn of section.turns) {
873
- total += turn.extracted !== undefined
874
- ? renderExtractionBlock(turn.extracted).length
875
- : turn.assistant.join('\n').length;
876
- }
877
- }
878
- return total;
879
- }
880
865
  /**
881
866
  * Render the digest under a hard character budget.
882
867
  *
883
- * The two truncation tiers are the plan's T1 and T1', in that order:
868
+ * Three tiers, in order:
884
869
  *
885
870
  * - **T1** user prose is verbatim unless it alone exceeds `USER_BUDGET_SHARE` of
886
871
  * the budget, then the oldest turns are cut first. The share is 0.9 rather than
887
872
  * 0.5 because real user prose is a few percent of the digest: at 0.5 the
888
873
  * extracted blocks crowded out the oldest human messages, which are exactly the
889
874
  * standing constraints (「请用pixi管理开发环境」) that must survive.
890
- * - **T1'** assistant prose is verbatim unless the whole digest overflows, then
891
- * it is cut evenly per turn down to `MIN_TURN_CHARS`.
875
+ * - **T1'** the graded ladder: each block drops Overturned, then Concluded, then
876
+ * Did, while Asked survives every level.
877
+ * - **T2** whole turn bodies go, oldest first, when even the surviving sections
878
+ * overflow. The user lines stay; only what the assistant produced is dropped.
892
879
  *
893
880
  * T1' runs *after* T1 because a user's own words are the least reconstructible
894
- * thing in the log: an assistant's reply can be inferred from its tool calls
895
- * and the surrounding turns, a user's request cannot. The 800-character floor
896
- * exists so a tight budget thins every turn instead of erasing the last few.
881
+ * thing in the log: an assistant's reply can be inferred from its tool calls and
882
+ * the surrounding turns, a user's request cannot.
897
883
  *
898
- * Both tiers run on a long session, and that is by design: the ceiling is
884
+ * All three tiers run on a long session, and that is by design: the ceiling is
899
885
  * absolute (`DIGEST_TOKEN_CEILING`), so a 122-turn history with 316k characters
900
886
  * of assistant prose cannot fit verbatim. In the extractive design most turns
901
887
  * carry an extraction instead of prose, which keeps the digest far below the
902
888
  * ceiling; the tiers exist for the turns where extraction was unavailable and
903
889
  * the prose is all that remains.
890
+ *
891
+ * When `condensed` is supplied the tiers are skipped and the digest is returned
892
+ * whole. That path is entered only by `condenseOldest`, which owns the overflow:
893
+ * degrading here would report "fits" at a level that has already dropped the
894
+ * sections the fold was meant to preserve, and the fold loop would stop early
895
+ * having bought nothing. Measured at 1200 turns: the ladder dropped 475 turn
896
+ * bodies, leaving only `## Asked`, before condensation ever got a chance.
904
897
  */
905
- export function renderDigest(events, budgetTokens, extracted) {
898
+ export function renderDigest(events, budgetTokens, extracted, condensed) {
906
899
  const sections = extracted === undefined ? buildSections(events) : withExtractions(buildSections(events), extracted);
907
900
  const budgetChars = Math.max(0, budgetTokens * 4);
908
- const render = (capChars, trimmed) => (trimmed ?? sections).map((section) => renderSection(section, capChars)).join('\n');
901
+ const render = (trimmed, level = 3) => (trimmed ?? sections)
902
+ .map((section, index) => renderSection(section, level, condensed, index))
903
+ .join('\n');
909
904
  // User prose is reserved before anything else is placed.
910
905
  //
911
906
  // Measured on a 122-turn session: every human message in the span totalled 469
@@ -915,7 +910,7 @@ export function renderDigest(events, budgetTokens, extracted) {
915
910
  // standing constraints (「请用pixi管理开发环境」) that never expire, while the
916
911
  // extraction describes work that is already finished.
917
912
  const userReserve = Math.min(Math.floor(budgetChars * USER_BUDGET_SHARE), sections.reduce((total, section) => total + section.turns.reduce((sum, turn) => sum + turn.user.join('\n').length, 0), 0));
918
- const verbatim = render(undefined);
913
+ const verbatim = render();
919
914
  if (verbatim.length <= budgetChars)
920
915
  return verbatim;
921
916
  // T1: user prose over its share, oldest first. Only the user side changes, so
@@ -943,43 +938,139 @@ export function renderDigest(events, budgetTokens, extracted) {
943
938
  }
944
939
  }
945
940
  }
946
- const afterT1 = render(undefined, t1);
941
+ const afterT1 = render(t1);
947
942
  if (afterT1.length <= budgetChars)
948
943
  return afterT1;
949
944
  // The user side fits inside its reserve; what overflows is the turn bodies
950
945
  // (extraction or prose plus pointers). Thin those, and only drop whole turns
951
946
  // once every body is already at zero — dropping a turn also drops the user
952
947
  // prose in it, which is what the reserve exists to prevent.
953
- // T1': assistant prose, evenly per turn. Length is monotone non-decreasing in
954
- // the cap, so bisection finds the largest cap that fits exactly, in about
955
- // eight renders. The floor is honoured only while it fits; below that the cap
956
- // follows the budget down and the final slice guarantees the ceiling.
948
+ // T1': the graded ladder. Each level drops one section from every block —
949
+ // Overturned first, then Concluded, then Did — and Asked survives all of them.
950
+ //
951
+ // This replaces a character cap applied to each block. That cap sliced every
952
+ // extraction at the same offset, and because Asked is the block's last section
953
+ // it was the first thing eaten: at 490 turns each question rendered as ` 1.`
954
+ // with its options gone, and by 520 both Asked and Overturned were absent from
955
+ // every block. A half-line reads as data, so slicing loses more than dropping:
956
+ // the reader cannot tell a truncated fact from a short one.
957
+ //
958
+ // Asked outranks everything because it is the only section nothing later can
959
+ // rebuild. Did and Concluded describe work whose results are still in the
960
+ // working tree; the question and the options the user chose between exist only
961
+ // in this line.
962
+ //
963
+ // No character cap at any level: a block either renders whole or loses a whole
964
+ // section. Slicing was the original mechanism and it cut Asked's options off
965
+ // mid-list, which reads as data rather than as truncation.
966
+ //
967
+ // The ladder only runs when no condensation was supplied. A condensed digest
968
+ // that still overflows is the caller's problem to fix by folding more turns:
969
+ // degrading it here would report "fits" at a level that has already dropped the
970
+ // sections the fold was meant to preserve, and the fold loop would stop early
971
+ // having bought nothing. Measured at 1200 turns: the ladder dropped 475 turn
972
+ // bodies, leaving only `## Asked`, before condensation ever got a chance.
973
+ if (condensed !== undefined && condensed.size > 0) {
974
+ // Returned whole even when it still overflows. The caller folds more turns and
975
+ // asks again; slicing here would cut the last block mid-line, which is the
976
+ // failure this whole path exists to remove.
977
+ return render(t1, 3);
978
+ }
979
+ for (let level = 3; level >= 0; level -= 1) {
980
+ const whole = render(t1, level);
981
+ if (whole.length <= budgetChars)
982
+ return whole;
983
+ }
984
+ // Every level overflowed with prose already at zero, so the user lines plus the
985
+ // surviving Asked sections alone exceed the budget. Drop the oldest turn
986
+ // *bodies* rather than the oldest sections: a dropped section takes the user's
987
+ // request with it, and those requests are standing constraints ("请用pixi管理
988
+ // 开发环境") that never expire, while a body describes work already superseded.
989
+ // The newest turns are the ones the next request depends on, so the cut runs
990
+ // from the oldest end.
991
+ const positions = [];
992
+ for (const [section, { turns }] of t1.entries()) {
993
+ for (let turn = 0; turn < turns.length; turn += 1)
994
+ positions.push({ section, turn });
995
+ }
996
+ const withoutBodies = (count) => {
997
+ const trimmed = t1.map((section) => ({ turns: section.turns.map((turn) => ({ ...turn })) }));
998
+ for (const { section, turn } of positions.slice(0, count)) {
999
+ const target = trimmed[section]?.turns[turn];
1000
+ if (target === undefined)
1001
+ continue;
1002
+ // The user line stays; only what the assistant produced goes. `delete`
1003
+ // rather than assigning undefined: `exactOptionalPropertyTypes` treats the
1004
+ // key's absence and its undefined value as different types.
1005
+ delete target.extracted;
1006
+ target.assistant = [];
1007
+ target.errors = [];
1008
+ target.writes = [];
1009
+ }
1010
+ return trimmed;
1011
+ };
1012
+ // Lower bound on the drop count: the smallest number that fits. `Math.floor`
1013
+ // rather than `ceil` is load-bearing — with `ceil`, `mid` equals `high` once the
1014
+ // range narrows to two entries, so a fitting `mid` left `high` unchanged and the
1015
+ // loop never terminated. A 2200-turn digest hung here; 2100 happened to converge.
957
1016
  let low = 0;
958
- let high = assistantChars(t1);
1017
+ let high = positions.length;
959
1018
  while (low < high) {
960
- const mid = Math.ceil((low + high) / 2);
961
- if (render(mid, t1).length <= budgetChars)
962
- low = mid;
1019
+ const mid = Math.floor((low + high) / 2);
1020
+ const marker = mid === 0 ? '' : `…(${mid} oldest turn bodies dropped: over budget)\n`;
1021
+ if (marker.length + render(withoutBodies(mid), 0).length <= budgetChars)
1022
+ high = mid;
963
1023
  else
964
- high = mid - 1;
1024
+ low = mid + 1;
965
1025
  }
966
- const capped = render(low, t1);
967
- if (capped.length <= budgetChars)
968
- return capped;
969
- // Even cap 0 overflows, so the headings and pointers alone exceed the budget.
970
- // Drop the oldest sections instead of slicing the head: a truncated tail would
971
- // cut the newest turns, which are exactly the ones the next request needs.
1026
+ const marker = low === 0 ? '' : `…(${low} oldest turn bodies dropped: over budget)\n`;
1027
+ const stripped = render(withoutBodies(low), 0);
1028
+ if (marker.length + stripped.length <= budgetChars)
1029
+ return `${marker}${stripped}`;
1030
+ // Even with every body gone the user lines alone overflow — a budget smaller
1031
+ // than the requests it must hold. Only here do whole sections go, oldest first:
1032
+ // slicing the tail instead would cut the newest turns, which are exactly the
1033
+ // ones the next request depends on.
1034
+ // Still over budget with every body gone. Drop whole turns from the oldest end
1035
+ // — a dropped turn takes its user line with it, which is the price of a budget
1036
+ // too small to hold the requests themselves. The newest turn is never dropped,
1037
+ // and the walk keeps every turn after the cut point rather than only the last
1038
+ // one: a `goal` round records its objective as a user message and can sit after
1039
+ // the newest request, so keeping just `slice(-1)` kept the goal and lost the
1040
+ // request.
1041
+ // The cut never passes the last turn carrying a user request. Without this the
1042
+ // walk reached the very end — the fixture's `goal` round is the last position,
1043
+ // so dropping up to it kept the goal and lost `USER-13`, the newest request.
1044
+ const turnAt = (position) => position === undefined ? undefined : t1[position.section]?.turns[position.turn];
1045
+ let lastRequest = positions.length - 1;
1046
+ while (lastRequest > 0 && turnAt(positions[lastRequest])?.fromRequest !== true)
1047
+ lastRequest -= 1;
972
1048
  let first = 0;
973
- let dropped = 0;
974
- while (first < t1.length - 1) {
975
- dropped += 1;
1049
+ while (first < lastRequest) {
976
1050
  first += 1;
977
- const rest = render(0, t1.slice(first));
978
- const text = `…(${dropped} earlier turn(s) dropped: over budget)\n${rest}`;
1051
+ const cut = positions[first];
1052
+ if (cut === undefined)
1053
+ break;
1054
+ const kept = t1
1055
+ .map((section, sectionIndex) => ({
1056
+ turns: section.turns.filter((_, turnIndex) => sectionIndex > cut.section || (sectionIndex === cut.section && turnIndex >= cut.turn)),
1057
+ }))
1058
+ .filter((section) => section.turns.length > 0);
1059
+ const rest = render(kept, 0);
1060
+ const text = `…(${first} earlier turn(s) dropped: over budget)\n${rest}`;
979
1061
  if (text.length <= budgetChars)
980
1062
  return text;
981
1063
  }
982
- return render(0, t1.slice(-1)).slice(0, budgetChars);
1064
+ // Nothing fit, so keep the one turn the next request depends on: the newest one
1065
+ // carrying a user request, not the last position in the log.
1066
+ // Only the user line: the budget cannot even hold one full turn, and the request
1067
+ // is the part the next turn is answering.
1068
+ const keeperTurn = turnAt(positions[lastRequest]);
1069
+ if (keeperTurn === undefined)
1070
+ return '';
1071
+ const bare = { ...keeperTurn, assistant: [], errors: [], writes: [] };
1072
+ delete bare.extracted;
1073
+ return render([{ turns: [bare] }], 0);
983
1074
  }
984
1075
  /**
985
1076
  * The surface seqs this compaction shadows, recovered from the summarization
@@ -1086,6 +1177,66 @@ export function buildExtractionMaterial(turn, prose) {
1086
1177
  * @param signal - cancellation forwarded to the adapter.
1087
1178
  * @returns the extracted blocks by slot key; empty when extraction is unavailable.
1088
1179
  */
1180
+ /**
1181
+ * One condensation request: fold a run of already-finished turns into a paragraph.
1182
+ *
1183
+ * Module-level and shaped like `extractOnce` rather than a method, so both calls
1184
+ * derive their route and reasoning effort the same way.
1185
+ *
1186
+ * @param ctx - plugin context carrying the `llm` service and a logger.
1187
+ * @param agent - owner of the session being compacted.
1188
+ * @param material - the rendered blocks being folded.
1189
+ * @param signal - cancellation forwarded to the adapter.
1190
+ * @returns the folded paragraph, or undefined when the call produced nothing.
1191
+ */
1192
+ async function condenseOnce(ctx, agent, material, signal) {
1193
+ const llm = ctx.llm;
1194
+ if (llm === undefined) {
1195
+ ctx.logger?.warn('verbatim-compaction: no llm service, condensation skipped');
1196
+ return undefined;
1197
+ }
1198
+ const route = agent.session.requestHeader()?.config;
1199
+ const provider = route?.provider ?? agent.options.provider;
1200
+ const model = route?.model ?? agent.options.model;
1201
+ if (provider === undefined || model === undefined) {
1202
+ ctx.logger?.warn('verbatim-compaction: no route for condensation, skipped');
1203
+ return undefined;
1204
+ }
1205
+ const info = await Promise.resolve()
1206
+ .then(() => llm.resolveModelInfo?.(provider, model, signal))
1207
+ .catch(() => undefined);
1208
+ const cheapest = cheapestEffort(info?.reasoning?.efforts);
1209
+ const chunks = [];
1210
+ try {
1211
+ const stream = llm.stream({
1212
+ provider,
1213
+ model,
1214
+ messages: [{ role: 'user', content: [{ type: 'text', text: `${material}\n\n${CONDENSE_INSTRUCTION}` }] }],
1215
+ maxTokens: CONDENSE_TOKENS,
1216
+ sessionId: agent.session.id,
1217
+ purpose: 'compaction',
1218
+ ...(cheapest === undefined ? {} : { reasoningEffort: cheapest }),
1219
+ ...(signal === undefined ? {} : { signal }),
1220
+ });
1221
+ for await (const chunk of stream) {
1222
+ const delta = chunk;
1223
+ if (delta.type === 'text-delta' && typeof delta.text === 'string')
1224
+ chunks.push(delta.text);
1225
+ }
1226
+ }
1227
+ catch (error) {
1228
+ ctx.logger?.warn(`verbatim-compaction: condensation call failed: ${String(error)}`);
1229
+ return undefined;
1230
+ }
1231
+ const text = chunks.join('').trim();
1232
+ if (text.length === 0) {
1233
+ // Silence here is what makes "the digest stopped folding" invisible at runtime:
1234
+ // the summary still renders, just without the room the fold would have bought.
1235
+ ctx.logger?.warn(`verbatim-compaction: condensation returned no text for ${material.length} chars of material`);
1236
+ return undefined;
1237
+ }
1238
+ return text;
1239
+ }
1089
1240
  async function extractBatch(ctx, agent, batch, signal) {
1090
1241
  const out = new Map();
1091
1242
  if (batch.length === 0)
@@ -1236,7 +1387,7 @@ async function extractOnce(ctx, agent, batch, signal) {
1236
1387
  return { blocks: parseExtraction(answer), truncated };
1237
1388
  }
1238
1389
  /**
1239
- * Deterministic compaction backend: verbatim prose, pointerized tools, no model
1390
+ * Extractive compaction backend: verbatim user prose, one model call per batch,
1240
1391
  * call.
1241
1392
  *
1242
1393
  * Everything except `summarize()` is inherited. The base class prices pressure,
@@ -1262,6 +1413,14 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1262
1413
  * the same behaviour as before this cache existed.
1263
1414
  */
1264
1415
  extractionCache = new Map();
1416
+ /**
1417
+ * Folded text, keyed by provider, model and a hash of the material folded.
1418
+ *
1419
+ * Same reasoning as `extractionCache`: the fold is a model call over material
1420
+ * rebuilt from the raw log on every compaction, so the same run of old turns is
1421
+ * re-folded on every later compaction unless it is remembered.
1422
+ */
1423
+ condensedCache = new Map();
1265
1424
  /**
1266
1425
  * Build the replacement checkpoint content from the session log.
1267
1426
  *
@@ -1274,10 +1433,10 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1274
1433
  *
1275
1434
  * @param input - replayed conversation prefix the base class is shadowing.
1276
1435
  * @param agent - owner of the session being compacted.
1277
- * @param _signal - unused: the digest is synchronous and cannot be cancelled midway.
1436
+ * @param signal - cancellation forwarded to the extraction and fold calls.
1278
1437
  * @returns text summary blocks, unmarked by any LLM call.
1279
1438
  */
1280
- async summarize(input, agent, _signal) {
1439
+ async summarize(input, agent, signal) {
1281
1440
  const session = agent.session;
1282
1441
  const shadowed = shadowedSeqs(session, input);
1283
1442
  const shadowedSet = new Set(shadowed);
@@ -1292,8 +1451,24 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1292
1451
  // size independent of history length; the guard bound only exists for the
1293
1452
  // degenerate case of a span smaller than the ceiling.
1294
1453
  const budget = Math.max(0, Math.min(DIGEST_TOKEN_CEILING, shadowedPrice - FRAME_TOKENS - SHRINK_MARGIN_TOKENS));
1295
- const extracted = await this.extractAll(source, agent, _signal);
1296
- const text = renderDigest(source, budget, extracted);
1454
+ const extracted = await this.extractAll(source, agent, signal);
1455
+ // Fold the oldest turns up only when the plain digest overflows. The fold is an
1456
+ // LLM call, so a digest that already fits must not pay for one.
1457
+ let condensed;
1458
+ if (renderDigest(source, budget, extracted).length > budget * 4) {
1459
+ condensed = await this.condenseOldest(source, extracted, agent, budget, signal);
1460
+ }
1461
+ // The fold path returns its digest whole, so it can still overflow when every
1462
+ // group has been folded and the user lines alone are too long. The budget is a
1463
+ // contract the host's shrink guard depends on, so that case falls back to the
1464
+ // ladder: a degraded digest beats an over-budget one. The fold is the better
1465
+ // outcome, not the only permitted one.
1466
+ let text = renderDigest(source, budget, extracted, condensed);
1467
+ if (text.length > budget * 4) {
1468
+ this.ctx.logger?.warn(`verbatim-compaction: digest still over budget after folding ${condensed?.size ?? 0} group(s) `
1469
+ + `(${text.length} > ${budget * 4} chars), falling back to the graded ladder`);
1470
+ text = renderDigest(source, budget, extracted);
1471
+ }
1297
1472
  const route = session.requestHeader()?.config;
1298
1473
  return {
1299
1474
  summary: [{ type: 'text', text }],
@@ -1301,6 +1476,104 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1301
1476
  model: route?.model ?? agent.options.model ?? 'digest',
1302
1477
  };
1303
1478
  }
1479
+ /**
1480
+ * Fold the oldest turns into condensed blocks until the digest fits.
1481
+ *
1482
+ * Only reached when the plain digest overflows `budget`. The oldest turns are
1483
+ * the right ones to fold: they describe work already superseded, while the
1484
+ * newest are what the next request depends on.
1485
+ *
1486
+ * Linear in groups, not bisected: a fold is not monotone in how much is folded —
1487
+ * a paragraph's length depends on what the model chose to keep — so there is no
1488
+ * boundary to bisect. The walk stops at the first size that fits, which is the
1489
+ * fewest calls that buy enough room. Each block covers `CONDENSE_GROUP`
1490
+ * consecutive sections, so the number of calls is proportional to the digest,
1491
+ * not to the number of turns.
1492
+ *
1493
+ * Cached by content, like the extraction: the same prefix of turns folds to the
1494
+ * same text, and a later compaction re-reads the same history.
1495
+ *
1496
+ * @param source - digest source events, in log order.
1497
+ * @param extracted - per-turn extractions already computed.
1498
+ * @param agent - owner of the session being compacted.
1499
+ * @param budget - token budget the digest must fit.
1500
+ * @param signal - cancellation forwarded to every call.
1501
+ * @returns condensed blocks keyed by the `turnKey` of the first covered section.
1502
+ */
1503
+ async condenseOldest(source, extracted, agent, budget, signal) {
1504
+ const sections = withExtractions(buildSections(source), extracted);
1505
+ const budgetChars = budget * 4;
1506
+ const out = new Map();
1507
+ // One group per iteration, oldest first, checking after each whether the digest
1508
+ // fits. Single loop, `start` monotone: the earlier two-level form advanced its
1509
+ // inner start from `out.size`, so a group whose call failed was retried on every
1510
+ // outer pass (45 calls instead of 4 with the model down), and the outer bound
1511
+ // `covered < sections.length` stopped one group short of the end — at 700
1512
+ // sections the last 100 were never folded, and at 100 or fewer the loop body
1513
+ // never ran at all.
1514
+ for (const start of foldGroupStarts(sections.length)) {
1515
+ if (signal?.aborted === true)
1516
+ break;
1517
+ const group = sections.slice(start, start + CONDENSE_GROUP);
1518
+ if (group.length === 0)
1519
+ continue;
1520
+ const text = await this.condenseGroup(group, agent, signal);
1521
+ // A failed group is skipped rather than retried: the next group still buys
1522
+ // room, and retrying the same material against a failing model only spends
1523
+ // calls. The remaining turns keep their own blocks either way.
1524
+ if (text === undefined)
1525
+ continue;
1526
+ out.set(turnKey(start, 0), { text, covers: group.length });
1527
+ if (renderDigest(source, budget, extracted, out).length <= budgetChars)
1528
+ return out;
1529
+ }
1530
+ return out;
1531
+ }
1532
+ /**
1533
+ * Hand one group of turns to the model and return its folded text.
1534
+ *
1535
+ * @param group - consecutive sections to fold into one paragraph.
1536
+ * @param agent - owner of the session being compacted.
1537
+ * @param signal - cancellation forwarded to the call.
1538
+ * @returns the folded paragraph, or undefined when the call produced nothing.
1539
+ */
1540
+ async condenseGroup(group, agent, signal) {
1541
+ // Both sources, because a turn has one or the other: extraction succeeds and
1542
+ // the block replaces the prose, or it fails and the verbatim prose is what the
1543
+ // digest shows. Reading only `extracted` meant a run of turns whose extraction
1544
+ // failed contributed nothing — and because the fold then still replaced them,
1545
+ // their content vanished from the digest entirely rather than merely being
1546
+ // summarised badly.
1547
+ const material = group
1548
+ .map((section) => section.turns
1549
+ .map((turn) => {
1550
+ const block = renderExtractionBlock(turn.extracted);
1551
+ return block.length > 0 ? block : turn.assistant.join('\n');
1552
+ })
1553
+ .filter((block) => block.length > 0)
1554
+ .join('\n'))
1555
+ .filter((block) => block.length > 0)
1556
+ .join('\n\n');
1557
+ if (material.length === 0)
1558
+ return undefined;
1559
+ const llm = this.ctx.llm;
1560
+ if (llm === undefined)
1561
+ return undefined;
1562
+ const route = agent.session.requestHeader()?.config;
1563
+ const provider = route?.provider ?? agent.options.provider;
1564
+ const model = route?.model ?? agent.options.model;
1565
+ if (provider === undefined || model === undefined)
1566
+ return undefined;
1567
+ const key = `${provider}:${model}:${hashText(material)}`;
1568
+ const cached = this.condensedCache.get(key);
1569
+ if (cached !== undefined)
1570
+ return cached;
1571
+ const text = await condenseOnce(this.ctx, agent, material, signal);
1572
+ if (text === undefined)
1573
+ return undefined;
1574
+ this.condensedCache.set(key, text);
1575
+ return text;
1576
+ }
1304
1577
  /**
1305
1578
  * Run the extraction for every turn in the digest source.
1306
1579
  *