@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.
@@ -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);
@@ -85,6 +85,36 @@ export interface Extraction {
85
85
  did: string[];
86
86
  concluded: string[];
87
87
  overturned: string[];
88
+ /**
89
+ * What this turn asked the user and what came back, when it asked anything.
90
+ *
91
+ * Written by the model rather than read off the log. The two cases the log
92
+ * cannot cover are the reason:
93
+ *
94
+ * - A question is often not in the last line. Over 231 real turns that drew a
95
+ * short reply, 34% had prose after the question (p90 = 7 paragraphs, max
96
+ * 24) — a `## 需要你决定` block followed by `## 还没验证的`. The log records
97
+ * text, not which paragraph was the question.
98
+ * - A bare `1` is meaningless without the list it selects from, and that list
99
+ * is usually a paragraph or more above the question, under its own heading.
100
+ * Reading it out needs judgement about which list the question refers to.
101
+ *
102
+ * The model already reads the same prose to fill `did`/`concluded`, so this
103
+ * costs one more field rather than another pass.
104
+ */
105
+ asked: AskedPair[];
106
+ }
107
+ /**
108
+ * One question the assistant put to the user, with the options it offered.
109
+ *
110
+ * No `answer` field: the reply is the next section's `## user` line, already in the
111
+ * digest verbatim. Carrying it here as well printed the same sentence twice.
112
+ */
113
+ export interface AskedPair {
114
+ /** The question, one line. */
115
+ question: string;
116
+ /** The options as offered, each one line; empty when the question offered none. */
117
+ options: string[];
88
118
  }
89
119
  /**
90
120
  * Parse the model's JSON reply into per-slot extractions.
@@ -105,7 +135,43 @@ export declare function parseExtraction(answer: string): Map<string, Extraction>
105
135
  * @returns markdown with a heading per non-empty field; empty string when every
106
136
  * field is empty.
107
137
  */
108
- export declare function renderExtractionBlock(extraction: Extraction | undefined): string;
138
+ export declare function renderExtractionBlock(extraction: Extraction | undefined, level?: number): string;
139
+ /**
140
+ * The group starts a fold walk visits, oldest first, one entry per group.
141
+ *
142
+ * Extracted so the walk's bounds are testable without a session, a logger and a
143
+ * model: the walk itself was where two defects lived — a bound that skipped the
144
+ * last group, and a start advanced from the success count, which retried a failed
145
+ * group on every pass.
146
+ *
147
+ * @param sectionCount - how many sections the digest has.
148
+ * @returns the start index of each group, in order.
149
+ */
150
+ export declare function foldGroupStarts(sectionCount: number): number[];
151
+ /**
152
+ * A folded-up summary of a run of consecutive sections, keyed by the `turnKey` of
153
+ * the first section it covers. The key's second component is always 0: a fold
154
+ * starts at a section boundary, never mid-section.
155
+ *
156
+ * Produced when the plain digest overflows: the oldest turns are handed to the
157
+ * model together and replaced by one paragraph. Deleting those turns instead —
158
+ * what the budget walk used to do — loses what they established, while folding
159
+ * keeps a statement of it in a fraction of the room.
160
+ */
161
+ export interface Condensed {
162
+ /** The folded text, already in the digest's own wording. */
163
+ text: string;
164
+ /**
165
+ * How many sections this block stands in for, counting from the key's own
166
+ * section.
167
+ *
168
+ * Sections, not turns: `buildSections` opens one section per user request, so a
169
+ * run of consecutive requests is a run of consecutive sections. Counting turns
170
+ * would cover only the first section and leave the rest rendering their own
171
+ * blocks — the fold bought nothing.
172
+ */
173
+ covers: number;
174
+ }
109
175
  /**
110
176
  * Build the compact per-turn trace fed to the summarizer.
111
177
  *
@@ -125,23 +191,21 @@ export declare function collectHints(events: readonly SessionEvent[]): string;
125
191
  /** One turn's accumulated digest material. */
126
192
  interface Turn {
127
193
  turn: number | undefined;
194
+ /**
195
+ * True when a human request opened this turn, false when a `goal` objective did.
196
+ *
197
+ * Both fill the `user` slot, so `user.length > 0` cannot tell them apart — and
198
+ * the difference decides which turn is kept when the budget is too small to
199
+ * hold the digest: dropping the newest human request loses what the next turn
200
+ * is answering, while dropping a goal round only loses a restated objective.
201
+ */
202
+ fromRequest: boolean;
128
203
  user: string[];
129
204
  assistant: string[];
130
205
  tools: Map<string, number>;
131
206
  resultBytes: number;
132
207
  errors: string[];
133
208
  writes: string[];
134
- /**
135
- * Question/answer pairs the assistant put to the user in this turn.
136
- *
137
- * Rendered by code rather than by the model: the model changed its Asked format
138
- * four times across runs, and each change silently broke the position or the
139
- * content. Both halves are in the log, so there is nothing to summarise.
140
- */
141
- asked: {
142
- question: string;
143
- answer: string;
144
- }[];
145
209
  /**
146
210
  * The extracted summary for this turn, when extraction succeeded.
147
211
  *
@@ -168,58 +232,40 @@ interface Section {
168
232
  * @returns one section per non-injected user message.
169
233
  */
170
234
  export declare function buildSections(events: readonly SessionEvent[]): Section[];
171
- /**
172
- * Render one section to digest text, truncating assistant prose to `capChars`.
173
- *
174
- * When the turn carries an extraction, that extraction *replaces* the assistant
175
- * prose. Keeping both was the duplication this design removes: 58.2% of
176
- * assistant characters are substantive conclusions that the extraction restates,
177
- * and the doubled copy pushed real history out through the budget.
178
- *
179
- * The tool pointer line stays either way: it is one line, and it is the only
180
- * record of what was actually run when the prose and extraction both say little.
181
- */
182
- /**
183
- * Move the `## Asked` section to the end of one extraction block.
184
- *
185
- * The digest reads as a conversation, and the user's next message is often just
186
- * "8399" or "继续". That reply only makes sense beside the question it answers, so
187
- * Asked belongs at the bottom of the block. The model puts it first about as often
188
- * as last, so the order is fixed here rather than requested in the prompt.
189
- *
190
- * @param block - one extraction block, possibly malformed.
191
- * @returns the same block with Asked last; unchanged when Asked is absent or already last.
192
- */
193
- export declare function moveAskedLast(block: string, asked?: readonly {
194
- question: string;
195
- answer: string;
196
- }[]): string;
197
235
  /**
198
236
  * Render the digest under a hard character budget.
199
237
  *
200
- * The two truncation tiers are the plan's T1 and T1', in that order:
238
+ * Three tiers, in order:
201
239
  *
202
240
  * - **T1** user prose is verbatim unless it alone exceeds `USER_BUDGET_SHARE` of
203
241
  * the budget, then the oldest turns are cut first. The share is 0.9 rather than
204
242
  * 0.5 because real user prose is a few percent of the digest: at 0.5 the
205
243
  * extracted blocks crowded out the oldest human messages, which are exactly the
206
244
  * standing constraints (「请用pixi管理开发环境」) that must survive.
207
- * - **T1'** assistant prose is verbatim unless the whole digest overflows, then
208
- * it is cut evenly per turn down to `MIN_TURN_CHARS`.
245
+ * - **T1'** the graded ladder: each block drops Overturned, then Concluded, then
246
+ * Did, while Asked survives every level.
247
+ * - **T2** whole turn bodies go, oldest first, when even the surviving sections
248
+ * overflow. The user lines stay; only what the assistant produced is dropped.
209
249
  *
210
250
  * T1' runs *after* T1 because a user's own words are the least reconstructible
211
- * thing in the log: an assistant's reply can be inferred from its tool calls
212
- * and the surrounding turns, a user's request cannot. The 800-character floor
213
- * exists so a tight budget thins every turn instead of erasing the last few.
251
+ * thing in the log: an assistant's reply can be inferred from its tool calls and
252
+ * the surrounding turns, a user's request cannot.
214
253
  *
215
- * Both tiers run on a long session, and that is by design: the ceiling is
254
+ * All three tiers run on a long session, and that is by design: the ceiling is
216
255
  * absolute (`DIGEST_TOKEN_CEILING`), so a 122-turn history with 316k characters
217
256
  * of assistant prose cannot fit verbatim. In the extractive design most turns
218
257
  * carry an extraction instead of prose, which keeps the digest far below the
219
258
  * ceiling; the tiers exist for the turns where extraction was unavailable and
220
259
  * the prose is all that remains.
260
+ *
261
+ * When `condensed` is supplied the tiers are skipped and the digest is returned
262
+ * whole. That path is entered only by `condenseOldest`, which owns the overflow:
263
+ * degrading here would report "fits" at a level that has already dropped the
264
+ * sections the fold was meant to preserve, and the fold loop would stop early
265
+ * having bought nothing. Measured at 1200 turns: the ladder dropped 475 turn
266
+ * bodies, leaving only `## Asked`, before condensation ever got a chance.
221
267
  */
222
- export declare function renderDigest(events: readonly SessionEvent[], budgetTokens: number, extracted?: ReadonlyMap<string, Extraction>): string;
268
+ export declare function renderDigest(events: readonly SessionEvent[], budgetTokens: number, extracted?: ReadonlyMap<string, Extraction>, condensed?: ReadonlyMap<string, Condensed>): string;
223
269
  /**
224
270
  * The surface seqs this compaction shadows, recovered from the summarization
225
271
  * input's message count.
@@ -268,7 +314,7 @@ export declare function digestSource(session: Session, retainedSeqs: ReadonlySet
268
314
  */
269
315
  export declare function buildExtractionMaterial(turn: readonly SessionEvent[], prose: string): string;
270
316
  /**
271
- * Deterministic compaction backend: verbatim prose, pointerized tools, no model
317
+ * Extractive compaction backend: verbatim user prose, one model call per batch,
272
318
  * call.
273
319
  *
274
320
  * Everything except `summarize()` is inherited. The base class prices pressure,
@@ -294,6 +340,14 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
294
340
  * the same behaviour as before this cache existed.
295
341
  */
296
342
  private readonly extractionCache;
343
+ /**
344
+ * Folded text, keyed by provider, model and a hash of the material folded.
345
+ *
346
+ * Same reasoning as `extractionCache`: the fold is a model call over material
347
+ * rebuilt from the raw log on every compaction, so the same run of old turns is
348
+ * re-folded on every later compaction unless it is remembered.
349
+ */
350
+ private readonly condensedCache;
297
351
  /**
298
352
  * Build the replacement checkpoint content from the session log.
299
353
  *
@@ -306,10 +360,44 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
306
360
  *
307
361
  * @param input - replayed conversation prefix the base class is shadowing.
308
362
  * @param agent - owner of the session being compacted.
309
- * @param _signal - unused: the digest is synchronous and cannot be cancelled midway.
363
+ * @param signal - cancellation forwarded to the extraction and fold calls.
310
364
  * @returns text summary blocks, unmarked by any LLM call.
311
365
  */
312
- protected summarize(input: SummarizationInput, agent: Agent, _signal?: AbortSignal): Promise<SummaryResult>;
366
+ protected summarize(input: SummarizationInput, agent: Agent, signal?: AbortSignal): Promise<SummaryResult>;
367
+ /**
368
+ * Fold the oldest turns into condensed blocks until the digest fits.
369
+ *
370
+ * Only reached when the plain digest overflows `budget`. The oldest turns are
371
+ * the right ones to fold: they describe work already superseded, while the
372
+ * newest are what the next request depends on.
373
+ *
374
+ * Linear in groups, not bisected: a fold is not monotone in how much is folded —
375
+ * a paragraph's length depends on what the model chose to keep — so there is no
376
+ * boundary to bisect. The walk stops at the first size that fits, which is the
377
+ * fewest calls that buy enough room. Each block covers `CONDENSE_GROUP`
378
+ * consecutive sections, so the number of calls is proportional to the digest,
379
+ * not to the number of turns.
380
+ *
381
+ * Cached by content, like the extraction: the same prefix of turns folds to the
382
+ * same text, and a later compaction re-reads the same history.
383
+ *
384
+ * @param source - digest source events, in log order.
385
+ * @param extracted - per-turn extractions already computed.
386
+ * @param agent - owner of the session being compacted.
387
+ * @param budget - token budget the digest must fit.
388
+ * @param signal - cancellation forwarded to every call.
389
+ * @returns condensed blocks keyed by the `turnKey` of the first covered section.
390
+ */
391
+ private condenseOldest;
392
+ /**
393
+ * Hand one group of turns to the model and return its folded text.
394
+ *
395
+ * @param group - consecutive sections to fold into one paragraph.
396
+ * @param agent - owner of the session being compacted.
397
+ * @param signal - cancellation forwarded to the call.
398
+ * @returns the folded paragraph, or undefined when the call produced nothing.
399
+ */
400
+ private condenseGroup;
313
401
  /**
314
402
  * Run the extraction for every turn in the digest source.
315
403
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logictan/dsh-verbatim-compaction",
3
- "version": "0.11.1",
3
+ "version": "0.12.1",
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",