@logictan/dsh-verbatim-compaction 0.6.0 → 0.7.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.
package/README.md CHANGED
@@ -62,7 +62,7 @@
62
62
 
63
63
  所以提取的材料是三段:用户请求(逐字)、助手正文(逐字)、工具轨迹(每条调用的 `description`,失败的调用另记一行首行错误)。模型输出固定的四节:`## Asked` / `## Did` / `## Concluded` / `## Overturned`。
64
64
 
65
- 空节直接删掉,不留 `(none)` 占位。实测一份真实提取块里 `## Asked` 和 `## Overturned` 都是 `(none)`,删掉后 312 → 271 字符;按 130 轮算,这些占位合计约 900 token 只是在记录「什么都没发生」。清理在代码里做(`pruneEmptySections`),不只依赖提示词——模型仍写了 `(none)` 也不会白花 token。判据是整节每一行去掉项目符号后都只是 `(none)` / `none` / `n/a` / `无` 之类的占位;`none of the tests passed`、`无法连接,改用代理` 这类真内容照原样保留。
65
+ 空节直接删掉,不留 `(none)` 占位。判据同时接受 `## Asked` 和裸写 `Asked`——实测模型有时不带 `##`,只认 `^#{1,6}` 会让 `Concluded\n- (none)` 原样留在摘要里。实测一份真实提取块里 `## Asked` 和 `## Overturned` 都是 `(none)`,删掉后 312 → 271 字符;按 130 轮算,这些占位合计约 900 token 只是在记录「什么都没发生」。清理在代码里做(`pruneEmptySections`),不只依赖提示词——模型仍写了 `(none)` 也不会白花 token。判据是整节每一行去掉项目符号后都只是 `(none)` / `none` / `n/a` / `无` 之类的占位;`none of the tests passed`、`无法连接,改用代理` 这类真内容照原样保留。
66
66
 
67
67
  `## Asked` 记的是「**助手**向**用户**提了什么、给了哪些选项」。这一节最容易错成「把用户请求改写一遍」——真实一次压缩里,模型把用户那段中文请求翻成英文塞进了 `Asked`,而用户原话就在它上面逐字抄着,同一件事写了两遍。
68
68
 
@@ -82,6 +82,14 @@
82
82
 
83
83
  缓存的键是提取材料的哈希(用户请求 + 助手正文 + 工具轨迹),不是 slot 位置:位置会随历史增长而错位,内容变了哈希就变,不会读到过期块。缓存是进程内的,重启即失效——代价只是重新提取一次,与加缓存前行为一致。
84
84
 
85
+ `## Asked` 由代码移到最后(`moveAskedLast`),因为用户的回复常常只有「8399」「继续」,只有紧接在提问后面才读得懂。模型用过三种写法——`## Asked`、`**Asked**:`、`- Asked:`——三种都认。
86
+
87
+ `ask_user_question` 的问题与用户选择都会进材料。它没有 `description` 参数,载荷在 `questions[]`,原来只留下 `TOOL ask_user_question` 五个字——问题是什么、用户选了什么全丢。答案在工具结果里(`answers[].selected`,或用户自己打字时的 `answers[].custom`),实测 31 次提问里 10 次是打字回答。
88
+
89
+ 一个 section 就是一次请求、一个 turn。日志会在同一次请求里推进 turn 号(实测一个请求的 7 条助手消息记作 turn 2、另 9 条记作 turn 3),按号码切分会把一个请求拆成「空请求 turn + 无用户消息的回复 turn」,摘要里就出现两个 `### assistant`。用户消息本身不带 turn 字段,这条也曾让两者永远对不上。
90
+
91
+ 一个 section 只提取一次,提取块写给该 section 的第一个 turn——如果每个 turn 都拿到同一份事件,模型会对同一段材料答两遍(实测出现过两个完全相同的 `## Concluded` 块和 `(duplicate of SLOT 4:0)` 占位)。
92
+
85
93
  提取按批调用:每 8 轮一次,一轮输出一个 `=== TURN n ===` 块。早期实现是每轮一次调用,122 轮就是 131 次往返,单轮 400 token 的输出上限乘以 131 就可能超过整个摘要上限。批处理把往返压到约 17 次,并共享 prompt 前缀以复用 provider 的 KV cache。
86
94
 
87
95
  用户原话在布局上**先占额度**,提取块不得挤占。实测那个 122 轮会话:区间内真人原话共 469 字符(117 token),而每轮一块 420 字符的提取共 55020 字符——提取是正文的 117 倍,任何让二者竞争的布局都会把正文挤掉,而正文是「请用pixi管理开发环境」这类永不过期的约束,提取描述的却是已经做完的工作。
package/lib/index.js CHANGED
@@ -159,10 +159,62 @@ function toolCallsOf(event) {
159
159
  const calls = [];
160
160
  for (const block of message.content) {
161
161
  if (block.type === 'tool-call')
162
- calls.push({ name: block.name, arguments: block.arguments });
162
+ calls.push({ id: block.id, name: block.name, arguments: block.arguments });
163
163
  }
164
164
  return calls;
165
165
  }
166
+ /**
167
+ * The answer the user gave to one `ask_user_question` call, or undefined.
168
+ *
169
+ * The answer is the tool's own result — `{"answers":[{"id":"…","selected":[…]}]}`
170
+ * — not an error, so without this the result was skipped and the only record of
171
+ * what the user chose never reached the extractor. The user's next message is
172
+ * often just "1" or "继续", which is unreadable without the question beside it.
173
+ *
174
+ * @param event - any event; non-results and unrelated results yield undefined.
175
+ * @param askedIds - tool-call ids of this turn's questions.
176
+ * @returns the chosen labels, or undefined when this result answers no question.
177
+ */
178
+ function answerOf(event, askedIds) {
179
+ if (askedIds.size === 0)
180
+ return undefined;
181
+ const message = messageOf(event);
182
+ if (message === null)
183
+ return undefined;
184
+ const callId = message.toolCallId;
185
+ if (callId === undefined || !askedIds.has(callId))
186
+ return undefined;
187
+ const text = textOf(event);
188
+ let parsed;
189
+ try {
190
+ parsed = JSON.parse(text);
191
+ }
192
+ catch {
193
+ return undefined;
194
+ }
195
+ if (typeof parsed !== 'object' || parsed === null)
196
+ return undefined;
197
+ const answers = parsed['answers'];
198
+ if (!Array.isArray(answers))
199
+ return undefined;
200
+ const chosen = answers
201
+ .flatMap((answer) => {
202
+ if (typeof answer !== 'object' || answer === null)
203
+ return [];
204
+ const record = answer;
205
+ const selected = record['selected'];
206
+ const picked = Array.isArray(selected) ? selected.map((value) => String(value)) : [];
207
+ // A typed answer arrives with `selected: []` and the text in `custom`. Ten
208
+ // of 31 real questions were answered this way, and those carried the user's
209
+ // actual observations rather than a menu label.
210
+ const typed = typeof record['custom'] === 'string' ? [record['custom']] : [];
211
+ return [...picked, ...typed];
212
+ })
213
+ .filter((value) => value.length > 0);
214
+ if (chosen.length === 0)
215
+ return undefined;
216
+ return chosen.join(' / ').replace(/\s+/g, ' ').slice(0, HINT_CHARS * 2);
217
+ }
166
218
  /**
167
219
  * Whether one tool result is a failure.
168
220
  *
@@ -217,8 +269,13 @@ export function pruneEmptySections(body) {
217
269
  pendingHeading = undefined;
218
270
  pendingBody = [];
219
271
  };
272
+ // A heading is either `## Name` or the bare name on its own line. Models
273
+ // sometimes answer without the `##`; a real run returned bare `Asked` / `Did` /
274
+ // `Concluded` lines, so a `^#{1,6}`-only test left `Concluded\n- (none)` in the
275
+ // digest as body text and the placeholder reached the reader.
276
+ const known = /^(Asked|Did|Concluded|Overturned)$/i;
220
277
  for (const line of lines) {
221
- if (/^#{1,6}\s/.test(line)) {
278
+ if (/^#{1,6}\s/.test(line) || known.test(line.trim())) {
222
279
  flush();
223
280
  pendingHeading = line;
224
281
  continue;
@@ -250,6 +307,11 @@ const EXTRACT_INSTRUCTION = [
250
307
  '- earlier conclusions this turn disproved or replaced',
251
308
  '',
252
309
  'Do not describe the tool calls themselves ("ran bash", "explored the repo"). State what came out of them. Do not repeat a conclusion the previous turn already stated. If the trace is too thin to support a claim, write "(none)".',
310
+ '',
311
+ // Measured on a real 32-slot session: whole batches came back in English while
312
+ // the material was Chinese, so the digest mixed two languages for one
313
+ // conversation.
314
+ 'Write in the same language as the material. A session whose requests are Chinese gets Chinese blocks; do not switch to English.',
253
315
  ].join('\n');
254
316
  /** Turns handed to one extraction call. */
255
317
  const TURNS_PER_CALL = 8;
@@ -279,6 +341,35 @@ function hintOf(argumentsJson) {
279
341
  catch {
280
342
  return '';
281
343
  }
344
+ // `ask_user_question` carries `questions[]`, not a `description`. Without this
345
+ // branch the hint was the bare tool name, so the extractor never saw what was
346
+ // asked and `## Asked` came out empty or wrong on every turn that used it.
347
+ const questions = parsed['questions'];
348
+ if (Array.isArray(questions)) {
349
+ const asked = questions
350
+ .map((question) => {
351
+ if (typeof question !== 'object' || question === null)
352
+ return '';
353
+ const record = question;
354
+ const text = typeof record['question'] === 'string'
355
+ ? record['question']
356
+ : typeof record['header'] === 'string' ? record['header'] : '';
357
+ const options = Array.isArray(record['options'])
358
+ ? record['options']
359
+ .map((option) => (typeof option === 'object' && option !== null
360
+ ? String(option['label'] ?? '')
361
+ : ''))
362
+ .filter((label) => label.length > 0)
363
+ : [];
364
+ if (text.length === 0)
365
+ return '';
366
+ return options.length === 0 ? text : `${text} [options: ${options.join(' / ')}]`;
367
+ })
368
+ .filter((text) => text.length > 0)
369
+ .join(' | ');
370
+ if (asked.length > 0)
371
+ return asked.replace(/\s+/g, ' ').slice(0, HINT_CHARS * 2);
372
+ }
282
373
  for (const key of ['description', 'command', 'query', 'file_path', 'path', 'pattern']) {
283
374
  const candidate = parsed[key];
284
375
  if (typeof candidate === 'string' && candidate.trim().length > 0) {
@@ -305,6 +396,9 @@ function hintOf(argumentsJson) {
305
396
  export function collectHints(events) {
306
397
  const lines = [];
307
398
  let calls = 0;
399
+ // Tool-call ids of this turn's questions, so the matching result can be read as
400
+ // an answer rather than being skipped as a non-error result.
401
+ const askedIds = new Set();
308
402
  for (const event of events) {
309
403
  // Tool calls are blocks inside `assistant/message`, not standalone events:
310
404
  // `digestSource` emits no `tool/call` type at all, so selecting on that type
@@ -316,11 +410,21 @@ export function collectHints(events) {
316
410
  calls += 1;
317
411
  const hint = hintOf(call.arguments);
318
412
  lines.push(hint.length > 0 ? `TOOL ${call.name}: ${hint}` : `TOOL ${call.name}`);
413
+ if (call.name === 'ask_user_question')
414
+ askedIds.add(call.id);
319
415
  }
320
416
  continue;
321
417
  }
322
418
  if (event.type !== 'tool/result')
323
419
  continue;
420
+ // The answer to a question is the tool's own result, not an error. It is the
421
+ // only record of what the user chose, and the next user message is often just
422
+ // "1" — so it has to travel with the question.
423
+ const answered = answerOf(event, askedIds);
424
+ if (answered !== undefined) {
425
+ lines.push(`ANSWER: ${answered}`);
426
+ continue;
427
+ }
324
428
  if (!isErrorResult(event))
325
429
  continue;
326
430
  const firstLine = textOf(event).split('\n')[0] ?? '';
@@ -437,9 +541,19 @@ export function buildSections(events) {
437
541
  currentTurn.user.push(text);
438
542
  continue;
439
543
  }
440
- if (currentTurn === undefined || (eventTurn !== undefined && currentTurn.turn !== eventTurn)) {
441
- currentTurn = openTurn(eventTurn);
442
- }
544
+ // A user message carries no `turn` field while the reply carries one, so a
545
+ // plain turn-number comparison opened a second turn for the same request: every
546
+ // real section ended up with an empty request turn plus a reply turn holding no
547
+ // user text, and the digest printed `## user` and `### assistant` twice.
548
+ //
549
+ // The turn number only separates work when the current turn already holds some,
550
+ // i.e. when the log really moved on to a later turn.
551
+ // A section is one request, so it is one turn. The log keeps advancing the turn
552
+ // number inside a single request (7 assistant messages as turn 2, then 9 more as
553
+ // turn 3), and splitting on the number gave every section a second turn whose
554
+ // block was the tail of the same request's prose.
555
+ if (currentTurn === undefined)
556
+ currentTurn = openTurn(eventTurn ?? lastTurn);
443
557
  const text = textOf(event);
444
558
  if (text.length > 0)
445
559
  currentTurn.assistant.push(text);
@@ -530,6 +644,44 @@ function materialKey(events) {
530
644
  * The tool pointer line stays either way: it is one line, and it is the only
531
645
  * record of what was actually run when the prose and extraction both say little.
532
646
  */
647
+ /**
648
+ * Move the `## Asked` section to the end of one extraction block.
649
+ *
650
+ * The digest reads as a conversation, and the user's next message is often just
651
+ * "8399" or "继续". That reply only makes sense beside the question it answers, so
652
+ * Asked belongs at the bottom of the block. The model puts it first about as often
653
+ * as last, so the order is fixed here rather than requested in the prompt.
654
+ *
655
+ * @param block - one extraction block, possibly malformed.
656
+ * @returns the same block with Asked last; unchanged when Asked is absent or already last.
657
+ */
658
+ export function moveAskedLast(block) {
659
+ const lines = block.split('\n');
660
+ // Three heading forms observed from the same model: `## Asked`, `**Asked**:` and
661
+ // `- Asked:`. Recognising only the first left Asked at the top whenever the model
662
+ // changed style.
663
+ const isAsked = (line) => /^\s*(?:#{0,6}\s*|[-*]\s+)?(?:\*\*)?Asked(?:\*\*)?\s*[::]?\s*$/i.test(line);
664
+ const isAskedInline = (line) => /^\s*(?:[-*]\s+)?(?:\*\*)?Asked(?:\*\*)?\s*[::]/i.test(line);
665
+ const isOther = (line) => /^\s*(?:#{0,6}\s*|[-*]\s+)?(?:\*\*)?(Did|Concluded|Overturned)(?:\*\*)?\s*[::]?/i.test(line);
666
+ const start = lines.findIndex((line) => isAsked(line) || isAskedInline(line));
667
+ if (start < 0)
668
+ return block;
669
+ // A heading form owns the lines until the next heading; an inline `- Asked: x`
670
+ // form owns only its own line.
671
+ const inline = isAskedInline(lines[start] ?? '') && !isAsked(lines[start] ?? '');
672
+ let end = start + 1;
673
+ if (!inline) {
674
+ while (end < lines.length && !isOther(lines[end] ?? ''))
675
+ end += 1;
676
+ }
677
+ const asked = lines.slice(start, end);
678
+ while (asked.length > 0 && (asked.at(-1) ?? '').trim().length === 0)
679
+ asked.pop();
680
+ const rest = [...lines.slice(0, start), ...lines.slice(end)];
681
+ while (rest.length > 0 && (rest.at(-1) ?? '').trim().length === 0)
682
+ rest.pop();
683
+ return [...rest, '', ...asked].join('\n');
684
+ }
533
685
  function renderSection(section, capChars) {
534
686
  const lines = [];
535
687
  for (const turn of section.turns) {
@@ -540,7 +692,18 @@ function renderSection(section, capChars) {
540
692
  if (capChars !== undefined && block.length > capChars) {
541
693
  block = `${block.slice(0, capChars)}\n…(+${block.length - capChars} chars)`;
542
694
  }
543
- lines.push(`### assistant\n${block}`);
695
+ // Errors and writes sit after the block: Asked has to be the last thing in the
696
+ // turn, and the errors line directly under `## user` read as if the user had
697
+ // said it. Asked is inside the block, so the trailer goes before Asked instead
698
+ // — see moveAskedLast being applied after the trailer is joined.
699
+ const trailer = [];
700
+ if (turn.errors.length > 0) {
701
+ trailer.push(` errors: ${turn.errors.length}: ${turn.errors.slice(0, 3).join(' | ')}`);
702
+ }
703
+ if (turn.writes.length > 0)
704
+ trailer.push(` wrote: ${turn.writes.join(', ')}`);
705
+ const body = trailer.length > 0 ? `${block}\n${trailer.join('\n')}` : block;
706
+ lines.push(`### assistant\n${moveAskedLast(body)}`);
544
707
  }
545
708
  else {
546
709
  let body = turn.assistant.join('\n');
@@ -549,12 +712,12 @@ function renderSection(section, capChars) {
549
712
  }
550
713
  if (body.length > 0)
551
714
  lines.push(`### assistant\n${body}`);
715
+ if (turn.errors.length > 0) {
716
+ lines.push(` errors: ${turn.errors.length}: ${turn.errors.slice(0, 3).join(' | ')}`);
717
+ }
718
+ if (turn.writes.length > 0)
719
+ lines.push(` wrote: ${turn.writes.join(', ')}`);
552
720
  }
553
- if (turn.errors.length > 0) {
554
- lines.push(` errors: ${turn.errors.length}: ${turn.errors.slice(0, 3).join(' | ')}`);
555
- }
556
- if (turn.writes.length > 0)
557
- lines.push(` wrote: ${turn.writes.join(', ')}`);
558
721
  }
559
722
  return lines.join('\n');
560
723
  }
@@ -937,35 +1100,52 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
937
1100
  // Walk the same sections the renderer will use, so a key addresses the exact
938
1101
  // slot the block will be written into. Grouping by turn number instead lost
939
1102
  // blocks whenever the log reused a number.
1103
+ // Partition the source into the same sections `buildSections` produced, then
1104
+ // hand each section to its slot. A slot is a section, not a single message:
1105
+ // the earlier version stopped at the first message, so a turn with 69
1106
+ // assistant messages and 112 tool calls contributed 2 events out of 164 and
1107
+ // the extractor reported "no work observed" for a turn that did plenty.
940
1108
  const sections = buildSections(source);
941
- const slots = [];
942
- let lastTurn;
943
- let cursor = 0;
944
- for (const [sectionIndex, section] of sections.entries()) {
945
- for (const [turnIndex, turn] of section.turns.entries()) {
946
- // Collect this turn's events by walking the source in order; the sections
947
- // were built from the same array, so the cursor never rewinds.
948
- const collected = [];
949
- while (cursor < source.length) {
950
- const event = source[cursor];
951
- cursor += 1;
952
- if (event === undefined)
953
- break;
954
- if (event.type === 'turn/start') {
955
- const turnNumber = turnOf(event);
956
- if (turnNumber !== undefined)
957
- lastTurn = turnNumber;
958
- collected.push(event);
959
- continue;
960
- }
961
- collected.push(event);
962
- if (event.type === 'user/message' || event.type === 'assistant/message') {
963
- if (!isInjection(event) && !isCheckpoint(event))
964
- break;
965
- }
1109
+ // Attribute events to sections by replaying the same walk `buildSections`
1110
+ // does, so the two can never disagree about where a section starts. An
1111
+ // independent scan drifted by one section on the fixture: `buildSections`
1112
+ // opens a new section for an unclosed turn without consuming a user message.
1113
+ const grouped = [];
1114
+ let sectionIndex = -1;
1115
+ const openedObjectives = new Set();
1116
+ for (const event of source) {
1117
+ const objective = goalObjective(event);
1118
+ let startsSection = false;
1119
+ if (objective !== undefined) {
1120
+ if (!openedObjectives.has(objective)) {
1121
+ openedObjectives.add(objective);
1122
+ startsSection = true;
966
1123
  }
967
- slots.push({ key: turnKey(sectionIndex, turnIndex), turn: turn.turn, events: collected });
968
1124
  }
1125
+ else if (event.type === 'user/message' && !isInjection(event) && !isCheckpoint(event)) {
1126
+ startsSection = true;
1127
+ }
1128
+ if (startsSection) {
1129
+ sectionIndex += 1;
1130
+ grouped[sectionIndex] = [];
1131
+ }
1132
+ if (sectionIndex >= 0)
1133
+ grouped[sectionIndex]?.push(event);
1134
+ }
1135
+ // One slot per section, addressed to the section's first turn.
1136
+ //
1137
+ // The material is about what the section did as a whole, so handing it to
1138
+ // every turn in the section made the model answer twice with the same block:
1139
+ // a real section holding two turns produced two identical `## Concluded`
1140
+ // bodies plus `(duplicate of SLOT 4:0)` placeholders in the digest. The extra
1141
+ // turns keep their prose and their own headings; only the first carries the
1142
+ // section's extraction.
1143
+ const slots = [];
1144
+ for (const [sectionIndex, section] of sections.entries()) {
1145
+ const first = section.turns[0];
1146
+ if (first === undefined)
1147
+ continue;
1148
+ slots.push({ key: turnKey(sectionIndex, 0), turn: first.turn, events: grouped[sectionIndex] ?? [] });
969
1149
  }
970
1150
  const extracted = new Map();
971
1151
  const missing = [];
@@ -148,6 +148,29 @@ interface Section {
148
148
  * @returns one section per non-injected user message.
149
149
  */
150
150
  export declare function buildSections(events: readonly SessionEvent[]): Section[];
151
+ /**
152
+ * Render one section to digest text, truncating assistant prose to `capChars`.
153
+ *
154
+ * When the turn carries an extraction, that extraction *replaces* the assistant
155
+ * prose. Keeping both was the duplication this design removes: 58.2% of
156
+ * assistant characters are substantive conclusions that the extraction restates,
157
+ * and the doubled copy pushed real history out through the budget.
158
+ *
159
+ * The tool pointer line stays either way: it is one line, and it is the only
160
+ * record of what was actually run when the prose and extraction both say little.
161
+ */
162
+ /**
163
+ * Move the `## Asked` section to the end of one extraction block.
164
+ *
165
+ * The digest reads as a conversation, and the user's next message is often just
166
+ * "8399" or "继续". That reply only makes sense beside the question it answers, so
167
+ * Asked belongs at the bottom of the block. The model puts it first about as often
168
+ * as last, so the order is fixed here rather than requested in the prompt.
169
+ *
170
+ * @param block - one extraction block, possibly malformed.
171
+ * @returns the same block with Asked last; unchanged when Asked is absent or already last.
172
+ */
173
+ export declare function moveAskedLast(block: string): string;
151
174
  /**
152
175
  * Render the digest under a hard character budget.
153
176
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logictan/dsh-verbatim-compaction",
3
- "version": "0.6.0",
3
+ "version": "0.7.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",