@logictan/dsh-verbatim-compaction 0.12.0 → 0.13.0

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.
@@ -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);
@@ -67,19 +67,14 @@ export interface SummaryResult {
67
67
  provider: string;
68
68
  model: string;
69
69
  }
70
- /**
71
- * Whether one tool result is a failure.
72
- *
73
- * Reads `data.message.isError` and nothing else. Matching the serialized text
74
- * for /error/i was tried and is wrong: tool output routinely contains that word
75
- * (grep misses, compiler logs, dumps of source files), so it labelled every
76
- * result in a 347-result turn as failed and the summarizer reported the whole
77
- * turn as a failure.
78
- *
79
- * @param event - a `tool/result` event.
80
- * @returns true only when the log itself marks the result as an error.
81
- */
82
- export declare function isErrorResult(event: SessionEvent): boolean;
70
+ /** One question the user answered through the question tool, with its answer. */
71
+ interface AnsweredQuestion {
72
+ question: string;
73
+ /** The labels the user picked, in the order they were offered. */
74
+ selected: string[];
75
+ /** What the user typed instead of picking, when they did. */
76
+ typed: string;
77
+ }
83
78
  /** One slot's extraction, as the model returns it. */
84
79
  export interface Extraction {
85
80
  did: string[];
@@ -135,15 +130,53 @@ export declare function parseExtraction(answer: string): Map<string, Extraction>
135
130
  * @returns markdown with a heading per non-empty field; empty string when every
136
131
  * field is empty.
137
132
  */
138
- export declare function renderExtractionBlock(extraction: Extraction | undefined): string;
133
+ export declare function renderExtractionBlock(extraction: Extraction | undefined, level?: number): string;
134
+ /**
135
+ * The group starts a fold walk visits, oldest first, one entry per group.
136
+ *
137
+ * Extracted so the walk's bounds are testable without a session, a logger and a
138
+ * model: the walk itself was where two defects lived — a bound that skipped the
139
+ * last group, and a start advanced from the success count, which retried a failed
140
+ * group on every pass.
141
+ *
142
+ * @param sectionCount - how many sections the digest has.
143
+ * @returns the start index of each group, in order.
144
+ */
145
+ export declare function foldGroupStarts(sectionCount: number): number[];
146
+ /**
147
+ * A folded-up summary of a run of consecutive sections, keyed by the `turnKey` of
148
+ * the first section it covers. The key's second component is always 0: a fold
149
+ * starts at a section boundary, never mid-section.
150
+ *
151
+ * Produced when the plain digest overflows: the oldest turns are handed to the
152
+ * model together and replaced by one paragraph. Deleting those turns instead —
153
+ * what the budget walk used to do — loses what they established, while folding
154
+ * keeps a statement of it in a fraction of the room.
155
+ */
156
+ export interface Condensed {
157
+ /** The folded text, already in the digest's own wording. */
158
+ text: string;
159
+ /**
160
+ * How many sections this block stands in for, counting from the key's own
161
+ * section.
162
+ *
163
+ * Sections, not turns: `buildSections` opens one section per user request, so a
164
+ * run of consecutive requests is a run of consecutive sections. Counting turns
165
+ * would cover only the first section and leave the rest rendering their own
166
+ * blocks — the fold bought nothing.
167
+ */
168
+ covers: number;
169
+ }
139
170
  /**
140
171
  * Build the compact per-turn trace fed to the summarizer.
141
172
  *
142
173
  * This is what lets a turn whose assistant prose is empty still leave a record:
143
174
  * in the measured session one turn ran 342 tool calls and emitted zero prose, so
144
175
  * the verbatim digest reduced it to a single `tools:` count line. The trace names
145
- * what was attempted and which attempts failed, which is enough for a model to
146
- * state the outcome.
176
+ * what was attempted, which is enough for a model to state the outcome.
177
+ *
178
+ * Tool results are not read. Their only contribution used to be a first-line
179
+ * error string, and that string was never the part of a failure that mattered.
147
180
  *
148
181
  * Bounded on purpose — 500 calls would otherwise produce a prompt larger than the
149
182
  * material it summarizes.
@@ -155,12 +188,32 @@ export declare function collectHints(events: readonly SessionEvent[]): string;
155
188
  /** One turn's accumulated digest material. */
156
189
  interface Turn {
157
190
  turn: number | undefined;
191
+ /**
192
+ * True when a human request opened this turn, false when a `goal` objective did.
193
+ *
194
+ * Both fill the `user` slot, so `user.length > 0` cannot tell them apart — and
195
+ * the difference decides which turn is kept when the budget is too small to
196
+ * hold the digest: dropping the newest human request loses what the next turn
197
+ * is answering, while dropping a goal round only loses a restated objective.
198
+ */
199
+ fromRequest: boolean;
158
200
  user: string[];
159
201
  assistant: string[];
160
202
  tools: Map<string, number>;
161
- resultBytes: number;
162
- errors: string[];
163
203
  writes: string[];
204
+ /**
205
+ * Questions this turn put to the user through `ask_user_question`, with the
206
+ * answers they got.
207
+ *
208
+ * Read from the log rather than asked of the model, and rendered as its own
209
+ * `## Answers` section. The model's `asked` field covers questions written in
210
+ * prose; a question asked through the tool is answered in the tool's own picker,
211
+ * and that answer is the tool result. Measured on one real session: three such
212
+ * questions were answered inside the picker and no `user/message` was written at
213
+ * all, so both the question and the choice were absent from two consecutive
214
+ * checkpoints.
215
+ */
216
+ answered: AnsweredQuestion[];
164
217
  /**
165
218
  * The extracted summary for this turn, when extraction succeeded.
166
219
  *
@@ -190,29 +243,37 @@ export declare function buildSections(events: readonly SessionEvent[]): Section[
190
243
  /**
191
244
  * Render the digest under a hard character budget.
192
245
  *
193
- * The two truncation tiers are the plan's T1 and T1', in that order:
246
+ * Three tiers, in order:
194
247
  *
195
248
  * - **T1** user prose is verbatim unless it alone exceeds `USER_BUDGET_SHARE` of
196
249
  * the budget, then the oldest turns are cut first. The share is 0.9 rather than
197
250
  * 0.5 because real user prose is a few percent of the digest: at 0.5 the
198
251
  * extracted blocks crowded out the oldest human messages, which are exactly the
199
252
  * standing constraints (「请用pixi管理开发环境」) that must survive.
200
- * - **T1'** assistant prose is verbatim unless the whole digest overflows, then
201
- * it is cut evenly per turn down to `MIN_TURN_CHARS`.
253
+ * - **T1'** the graded ladder: each block drops Overturned, then Concluded, then
254
+ * Did, while Asked survives every level.
255
+ * - **T2** whole turn bodies go, oldest first, when even the surviving sections
256
+ * overflow. The user lines stay; only what the assistant produced is dropped.
202
257
  *
203
258
  * T1' runs *after* T1 because a user's own words are the least reconstructible
204
- * thing in the log: an assistant's reply can be inferred from its tool calls
205
- * and the surrounding turns, a user's request cannot. The 800-character floor
206
- * exists so a tight budget thins every turn instead of erasing the last few.
259
+ * thing in the log: an assistant's reply can be inferred from its tool calls and
260
+ * the surrounding turns, a user's request cannot.
207
261
  *
208
- * Both tiers run on a long session, and that is by design: the ceiling is
262
+ * All three tiers run on a long session, and that is by design: the ceiling is
209
263
  * absolute (`DIGEST_TOKEN_CEILING`), so a 122-turn history with 316k characters
210
264
  * of assistant prose cannot fit verbatim. In the extractive design most turns
211
265
  * carry an extraction instead of prose, which keeps the digest far below the
212
266
  * ceiling; the tiers exist for the turns where extraction was unavailable and
213
267
  * the prose is all that remains.
268
+ *
269
+ * When `condensed` is supplied the tiers are skipped and the digest is returned
270
+ * whole. That path is entered only by `condenseOldest`, which owns the overflow:
271
+ * degrading here would report "fits" at a level that has already dropped the
272
+ * sections the fold was meant to preserve, and the fold loop would stop early
273
+ * having bought nothing. Measured at 1200 turns: the ladder dropped 475 turn
274
+ * bodies, leaving only `## Asked`, before condensation ever got a chance.
214
275
  */
215
- export declare function renderDigest(events: readonly SessionEvent[], budgetTokens: number, extracted?: ReadonlyMap<string, Extraction>): string;
276
+ export declare function renderDigest(events: readonly SessionEvent[], budgetTokens: number, extracted?: ReadonlyMap<string, Extraction>, condensed?: ReadonlyMap<string, Condensed>): string;
216
277
  /**
217
278
  * The surface seqs this compaction shadows, recovered from the summarization
218
279
  * input's message count.
@@ -261,7 +322,7 @@ export declare function digestSource(session: Session, retainedSeqs: ReadonlySet
261
322
  */
262
323
  export declare function buildExtractionMaterial(turn: readonly SessionEvent[], prose: string): string;
263
324
  /**
264
- * Deterministic compaction backend: verbatim prose, pointerized tools, no model
325
+ * Extractive compaction backend: verbatim user prose, one model call per batch,
265
326
  * call.
266
327
  *
267
328
  * Everything except `summarize()` is inherited. The base class prices pressure,
@@ -287,6 +348,14 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
287
348
  * the same behaviour as before this cache existed.
288
349
  */
289
350
  private readonly extractionCache;
351
+ /**
352
+ * Folded text, keyed by provider, model and a hash of the material folded.
353
+ *
354
+ * Same reasoning as `extractionCache`: the fold is a model call over material
355
+ * rebuilt from the raw log on every compaction, so the same run of old turns is
356
+ * re-folded on every later compaction unless it is remembered.
357
+ */
358
+ private readonly condensedCache;
290
359
  /**
291
360
  * Build the replacement checkpoint content from the session log.
292
361
  *
@@ -299,10 +368,44 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
299
368
  *
300
369
  * @param input - replayed conversation prefix the base class is shadowing.
301
370
  * @param agent - owner of the session being compacted.
302
- * @param _signal - unused: the digest is synchronous and cannot be cancelled midway.
371
+ * @param signal - cancellation forwarded to the extraction and fold calls.
303
372
  * @returns text summary blocks, unmarked by any LLM call.
304
373
  */
305
- protected summarize(input: SummarizationInput, agent: Agent, _signal?: AbortSignal): Promise<SummaryResult>;
374
+ protected summarize(input: SummarizationInput, agent: Agent, signal?: AbortSignal): Promise<SummaryResult>;
375
+ /**
376
+ * Fold the oldest turns into condensed blocks until the digest fits.
377
+ *
378
+ * Only reached when the plain digest overflows `budget`. The oldest turns are
379
+ * the right ones to fold: they describe work already superseded, while the
380
+ * newest are what the next request depends on.
381
+ *
382
+ * Linear in groups, not bisected: a fold is not monotone in how much is folded —
383
+ * a paragraph's length depends on what the model chose to keep — so there is no
384
+ * boundary to bisect. The walk stops at the first size that fits, which is the
385
+ * fewest calls that buy enough room. Each block covers `CONDENSE_GROUP`
386
+ * consecutive sections, so the number of calls is proportional to the digest,
387
+ * not to the number of turns.
388
+ *
389
+ * Cached by content, like the extraction: the same prefix of turns folds to the
390
+ * same text, and a later compaction re-reads the same history.
391
+ *
392
+ * @param source - digest source events, in log order.
393
+ * @param extracted - per-turn extractions already computed.
394
+ * @param agent - owner of the session being compacted.
395
+ * @param budget - token budget the digest must fit.
396
+ * @param signal - cancellation forwarded to every call.
397
+ * @returns condensed blocks keyed by the `turnKey` of the first covered section.
398
+ */
399
+ private condenseOldest;
400
+ /**
401
+ * Hand one group of turns to the model and return its folded text.
402
+ *
403
+ * @param group - consecutive sections to fold into one paragraph.
404
+ * @param agent - owner of the session being compacted.
405
+ * @param signal - cancellation forwarded to the call.
406
+ * @returns the folded paragraph, or undefined when the call produced nothing.
407
+ */
408
+ private condenseGroup;
306
409
  /**
307
410
  * Run the extraction for every turn in the digest source.
308
411
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logictan/dsh-verbatim-compaction",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "Deterministic compaction backend that keeps conversation prose verbatim in the checkpoint instead of re-summarizing it: user and assistant text survive word for word, tool results collapse to one-line pointers, reasoning is never read, and no model call is made.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",