@logictan/dsh-verbatim-compaction 0.9.0 → 0.11.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
@@ -82,6 +82,10 @@
82
82
 
83
83
  缓存的键是提取材料的哈希(用户请求 + 助手正文 + 工具轨迹),不是 slot 位置:位置会随历史增长而错位,内容变了哈希就变,不会读到过期块。缓存是进程内的,重启即失效——代价只是重新提取一次,与加缓存前行为一致。
84
84
 
85
+ 提取调用返回 **JSON 字段**(`{"slots":[{"key","did","concluded","overturned"}]}`),标题、项目符号、空行全部由代码拼装。此前是自由 markdown,模型会把标题和正文挤在同一行——真实产出里出现过 `… 重出 4 屏 Concluded Stitch 会回填真实车牌`,事后无法用正则判断句子在哪结束、下一个标题从哪开始。字段化之后这个歧义不存在。
86
+
87
+ `## Asked` 由**代码**从日志直接生成,不使用模型的输出:问题原文、选项、用户的选择(含打字回答)逐字取自 `ask_user_question` 的调用与结果。模型对这一段先后换过四种写法(`## Asked`、`**Asked**:`、`- Asked:`、中文 `问:`),每次换法都会破坏位置或内容,而这两半本来就在日志里,没有可概括的余地。模型写的那段一律丢弃。
88
+
85
89
  `## Asked` 记的是「助手问了什么 + 用户选了什么」。原来指令写「record the question, never the answer」——本意是防模型把用户请求抄进这一节,却被照字面执行:实测材料里两条 `ANSWER` 都在(其中一条把整个设计方向改成「游戏化、赛博朋克、提取 3D 模型」),模型只写了问题。
86
90
 
87
91
  `## Asked` 由代码移到最后(`moveAskedLast`),因为用户的回复常常只有「8399」「继续」,只有紧接在提问后面才读得懂。模型用过三种写法——`## Asked`、`**Asked**:`、`- Asked:`——三种都认。
package/lib/index.js CHANGED
@@ -306,30 +306,102 @@ const EXTRACT_INSTRUCTION = [
306
306
  'You are summarizing a batch of turns from a coding session for a compaction checkpoint.',
307
307
  '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.',
308
308
  '',
309
- 'For EVERY item, emit exactly one block, introduced by `=== SLOT <key> ===` using that same key. Under each heading write at most two terse lines. OMIT a heading entirely when it has no real information — do not write "(none)" and do not invent. An item where nothing substantive happened may be omitted altogether.',
309
+ 'Reply with ONE JSON object and nothing else. No prose, no code fence, no markdown.',
310
+ 'Shape: {"slots":[{"key":"<the slot key>","did":["…"],"concluded":["…"],"overturned":["…"]}]}',
310
311
  '',
311
- '## Asked',
312
- '- what the ASSISTANT asked the USER in this turn, and what the user chose',
313
- '- the trace shows an `ANSWER:` line for a question the user answered, including answers they typed instead of picking an option. Record it: a later turn cannot rebuild which option was chosen, and a typed answer often redirects the whole task',
314
- '- the user may also answer in their next message, which appears in the digest as plain text. Prefer the `ANSWER:` line when both exist',
315
- '- NEVER restate or translate the user request here. It is already in the digest verbatim, directly above this block; copying it is the single most common way this section goes wrong. Recording the answer is not copying the request — the answer is the user replying to your question.',
312
+ 'Rules for the fields:',
313
+ '- `key` must be copied exactly from the `=== SLOT <key> ===` line. One entry per slot.',
314
+ '- `did`: what was actually done, concretely. `concluded`: findings, decisions or measurements a later turn would need. `overturned`: earlier conclusions this turn disproved.',
315
+ '- 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.',
316
+ '- Write only the content of a line. Never write a heading, a bullet, or a field name inside a string.',
317
+ '- Do not describe the tool calls themselves ("ran bash", "explored the repo"). State what came out of them.',
318
+ '- Do not repeat a conclusion an earlier turn already stated.',
319
+ '- Never invent. If the material does not support a claim, leave the field empty.',
316
320
  '',
317
- '## Did',
318
- '- what was actually done, concretely',
319
- '',
320
- '## Concluded',
321
- '- findings, decisions, or measurements that a later turn would need',
322
- '',
323
- '## Overturned',
324
- '- earlier conclusions this turn disproved or replaced',
325
- '',
326
- '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)".',
321
+ 'Do not report questions and answers: those are read from the session log directly and need no summary.',
327
322
  '',
328
323
  // Measured on a real 32-slot session: whole batches came back in English while
329
324
  // the material was Chinese, so the digest mixed two languages for one
330
325
  // conversation.
331
- 'Write in the same language as the material. A session whose requests are Chinese gets Chinese blocks; do not switch to English.',
326
+ 'Write the strings in the same language as the material. A session whose requests are Chinese gets Chinese text; do not switch to English.',
332
327
  ].join('\n');
328
+ /**
329
+ * Parse the model's JSON reply into per-slot extractions.
330
+ *
331
+ * The reply used to be free-form markdown, which let a heading share a line with
332
+ * its body — a real block read `… 重出 4 屏 Concluded Stitch 会回填真实车牌`, and no
333
+ * post-hoc regex can decide where that sentence ends and the next heading begins.
334
+ * Fields remove the ambiguity: the renderer owns every heading and bullet.
335
+ *
336
+ * @param answer - the model's raw reply.
337
+ * @returns extractions by slot key; empty when the reply is not usable JSON.
338
+ */
339
+ export function parseExtraction(answer) {
340
+ const out = new Map();
341
+ // Models wrap JSON in a fence often enough that stripping it is not defensive
342
+ // programming but the common case.
343
+ const body = answer.trim().replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '');
344
+ const start = body.indexOf('{');
345
+ const end = body.lastIndexOf('}');
346
+ if (start < 0 || end <= start)
347
+ return out;
348
+ let parsed;
349
+ try {
350
+ parsed = JSON.parse(body.slice(start, end + 1));
351
+ }
352
+ catch {
353
+ return out;
354
+ }
355
+ if (typeof parsed !== 'object' || parsed === null)
356
+ return out;
357
+ const slots = parsed['slots'];
358
+ if (!Array.isArray(slots))
359
+ return out;
360
+ const strings = (value) => (Array.isArray(value)
361
+ ? value.filter((item) => typeof item === 'string')
362
+ .map((item) => item.replace(/\s+/g, ' ').trim())
363
+ .filter((item) => item.length > 0)
364
+ // A field is a list, so "nothing here" is an empty list. Models still write a
365
+ // placeholder often enough that dropping it is worth one test.
366
+ .filter((item) => !/^(?:\(?none\)?|n\/a|na|-{1,2}|无|沒有|没有)$/i.test(item))
367
+ .filter((item) => !/^(?:未提问|无提问|没有提问|no questions? (?:were |was )?asked|none asked)[。.!!]*$/i.test(item))
368
+ : []);
369
+ for (const slot of slots) {
370
+ if (typeof slot !== 'object' || slot === null)
371
+ continue;
372
+ const record = slot;
373
+ const key = record['key'];
374
+ if (typeof key !== 'string' || key.length === 0)
375
+ continue;
376
+ out.set(key, {
377
+ did: strings(record['did']),
378
+ concluded: strings(record['concluded']),
379
+ overturned: strings(record['overturned']),
380
+ });
381
+ }
382
+ return out;
383
+ }
384
+ /**
385
+ * Render one extraction as the digest block, headings included.
386
+ *
387
+ * @param extraction - the fields for one slot.
388
+ * @returns markdown with a heading per non-empty field; empty string when every
389
+ * field is empty.
390
+ */
391
+ export function renderExtractionBlock(extraction) {
392
+ if (extraction === undefined)
393
+ return '';
394
+ const lines = [];
395
+ const section = (heading, items) => {
396
+ if (items === undefined || items.length === 0)
397
+ return;
398
+ lines.push(`## ${heading}`, ...items.map((item) => `- ${item}`));
399
+ };
400
+ section('Did', extraction.did);
401
+ section('Concluded', extraction.concluded);
402
+ section('Overturned', extraction.overturned);
403
+ return lines.join('\n');
404
+ }
333
405
  /** Turns handed to one extraction call. */
334
406
  const TURNS_PER_CALL = 8;
335
407
  /** Output tokens allowed per turn in an extraction call. */
@@ -472,6 +544,81 @@ function pathArgumentOf(argumentsJson) {
472
544
  return undefined;
473
545
  }
474
546
  }
547
+ /**
548
+ * The question an `ask_user_question` call put, with its options, or undefined.
549
+ *
550
+ * @param argumentsJson - the call's raw arguments.
551
+ * @returns one line per question, options appended in brackets.
552
+ */
553
+ function questionTextOf(argumentsJson) {
554
+ let parsed;
555
+ try {
556
+ parsed = JSON.parse(argumentsJson);
557
+ }
558
+ catch {
559
+ return undefined;
560
+ }
561
+ if (typeof parsed !== 'object' || parsed === null)
562
+ return undefined;
563
+ const questions = parsed['questions'];
564
+ if (!Array.isArray(questions))
565
+ return undefined;
566
+ const lines = questions
567
+ .map((question) => {
568
+ if (typeof question !== 'object' || question === null)
569
+ return '';
570
+ const record = question;
571
+ const text = typeof record['question'] === 'string'
572
+ ? record['question']
573
+ : typeof record['header'] === 'string' ? record['header'] : '';
574
+ if (text.trim().length === 0)
575
+ return '';
576
+ const options = Array.isArray(record['options'])
577
+ ? record['options']
578
+ .map((option) => (typeof option === 'object' && option !== null
579
+ ? String(option['label'] ?? '')
580
+ : ''))
581
+ .filter((label) => label.length > 0)
582
+ : [];
583
+ return options.length === 0 ? text.trim() : `${text.trim()} [${options.join(' / ')}]`;
584
+ })
585
+ .filter((line) => line.length > 0);
586
+ return lines.length > 0 ? lines.join('\n') : undefined;
587
+ }
588
+ /**
589
+ * The answer carried by an `ask_user_question` result, or undefined.
590
+ *
591
+ * @param text - the result body.
592
+ * @returns the chosen labels, or the typed reply when nothing was chosen.
593
+ */
594
+ function answerTextOf(text) {
595
+ let parsed;
596
+ try {
597
+ parsed = JSON.parse(text);
598
+ }
599
+ catch {
600
+ return undefined;
601
+ }
602
+ if (typeof parsed !== 'object' || parsed === null)
603
+ return undefined;
604
+ const answers = parsed['answers'];
605
+ if (!Array.isArray(answers))
606
+ return undefined;
607
+ const chosen = answers
608
+ .flatMap((answer) => {
609
+ if (typeof answer !== 'object' || answer === null)
610
+ return [];
611
+ const record = answer;
612
+ const selected = record['selected'];
613
+ const picked = Array.isArray(selected) ? selected.map((value) => String(value)) : [];
614
+ // A typed answer arrives with `selected: []` and the text in `custom`.
615
+ const typed = typeof record['custom'] === 'string' && record['custom'].trim().length > 0
616
+ ? [record['custom'].trim()] : [];
617
+ return [...picked, ...typed];
618
+ })
619
+ .filter((value) => value.length > 0);
620
+ return chosen.length > 0 ? chosen.join(' / ') : undefined;
621
+ }
475
622
  /** The turn number an event belongs to, when the log records one. */
476
623
  function turnOf(event) {
477
624
  const turn = event.data.turn;
@@ -479,7 +626,7 @@ function turnOf(event) {
479
626
  }
480
627
  /** A fresh, empty turn accumulator. */
481
628
  function emptyTurn(turn) {
482
- return { turn, user: [], assistant: [], tools: new Map(), resultBytes: 0, errors: [], writes: [] };
629
+ return { turn, user: [], assistant: [], tools: new Map(), resultBytes: 0, errors: [], writes: [], asked: [] };
483
630
  }
484
631
  /**
485
632
  * Group append-origin surface events into per-turn digest material.
@@ -513,6 +660,8 @@ export function buildSections(events) {
513
660
  // objective on every round, so recording each copy would repeat it dozens of
514
661
  // times across a long autonomous run.
515
662
  const recordedObjectives = new Set();
663
+ // Question text by tool-call id, so the matching result can be read as its answer.
664
+ const pendingQuestions = new Map();
516
665
  for (const event of events) {
517
666
  if (event.type === 'turn/start') {
518
667
  const turn = turnOf(event);
@@ -543,6 +692,16 @@ export function buildSections(events) {
543
692
  const text = textOf(event);
544
693
  currentTurn.resultBytes += text.length;
545
694
  const message = messageOf(event);
695
+ // A question's own result is its answer. Recorded here rather than left to the
696
+ // model, which dropped or reworded it depending on its heading style.
697
+ const callId = message?.toolCallId;
698
+ if (callId !== undefined) {
699
+ const question = pendingQuestions.get(callId);
700
+ if (question !== undefined) {
701
+ pendingQuestions.delete(callId);
702
+ currentTurn.asked.push({ question, answer: answerTextOf(text) ?? '(no answer recorded)' });
703
+ }
704
+ }
546
705
  if (message?.isError === true) {
547
706
  const firstLine = text.split('\n')[0] ?? '';
548
707
  currentTurn.errors.push(firstLine.slice(0, 100));
@@ -583,6 +742,11 @@ export function buildSections(events) {
583
742
  if (text.length > 0)
584
743
  currentTurn.assistant.push(text);
585
744
  for (const call of toolCallsOf(event)) {
745
+ if (call.name === 'ask_user_question') {
746
+ const question = questionTextOf(call.arguments);
747
+ if (question !== undefined)
748
+ pendingQuestions.set(call.id, question);
749
+ }
586
750
  currentTurn.tools.set(call.name, (currentTurn.tools.get(call.name) ?? 0) + 1);
587
751
  if (!WRITE_TOOLS.has(call.name))
588
752
  continue;
@@ -680,40 +844,45 @@ function materialKey(events) {
680
844
  * @param block - one extraction block, possibly malformed.
681
845
  * @returns the same block with Asked last; unchanged when Asked is absent or already last.
682
846
  */
683
- export function moveAskedLast(block) {
847
+ export function moveAskedLast(block, asked = []) {
684
848
  const lines = block.split('\n');
685
- // Three heading forms observed from the same model: `## Asked`, `**Asked**:` and
686
- // `- Asked:`. Recognising only the first left Asked at the top whenever the model
687
- // changed style.
849
+ // Recognise every form the model has used for this section, in both languages, so
850
+ // it can be dropped. The content is regenerated from the log instead: four format
851
+ // changes across runs each broke either the position or the wording, and the log
852
+ // already holds both halves verbatim.
688
853
  const isAsked = (line) => /^\s*(?:#{0,6}\s*|[-*]\s+)?(?:\*\*)?(?:Asked|问)(?:\*\*)?\s*[::]?\s*$/i.test(line);
689
854
  const isAskedInline = (line) => /^\s*(?:[-*]\s+)?(?:\*\*)?(?:Asked|问)(?:\*\*)?\s*[::]/i.test(line);
690
- const isOther = (line) => /^\s*(?:#{0,6}\s*|[-*]\s+)?(?:\*\*)?(Did|Concluded|Overturned|做|结论|推翻)(?:\*\*)?\s*[::]?/i.test(line);
855
+ const isOther = (line) => /^\s*(?:#{0,6}\s*|[-*]\s+)?(?:\*\*)?(?:Did|Concluded|Overturned|做|结论|推翻)(?:\*\*)?\s*[::]?/i.test(line);
691
856
  const start = lines.findIndex((line) => isAsked(line) || isAskedInline(line));
692
- if (start < 0)
693
- return block;
694
- // A heading form owns the lines until the next heading; an inline `- Asked: x`
695
- // form owns only its own line.
696
- const inline = isAskedInline(lines[start] ?? '') && !isAsked(lines[start] ?? '');
697
- let end = start + 1;
698
- if (!inline) {
699
- while (end < lines.length && !isOther(lines[end] ?? ''))
700
- end += 1;
857
+ const kept = [...lines];
858
+ if (start >= 0) {
859
+ const inline = isAskedInline(kept[start] ?? '') && !isAsked(kept[start] ?? '');
860
+ let end = start + 1;
861
+ if (!inline) {
862
+ while (end < kept.length && !isOther(kept[end] ?? ''))
863
+ end += 1;
864
+ }
865
+ kept.splice(start, end - start);
701
866
  }
702
- const asked = lines.slice(start, end);
703
- while (asked.length > 0 && (asked.at(-1) ?? '').trim().length === 0)
704
- asked.pop();
705
- const rest = [...lines.slice(0, start), ...lines.slice(end)];
706
- while (rest.length > 0 && (rest.at(-1) ?? '').trim().length === 0)
707
- rest.pop();
708
- return [...rest, '', ...asked].join('\n');
867
+ while (kept.length > 0 && (kept.at(-1) ?? '').trim().length === 0)
868
+ kept.pop();
869
+ if (asked.length === 0)
870
+ return kept.join('\n');
871
+ const block_lines = asked.map(({ question, answer }) => {
872
+ const q = question.split('\n').join(' ');
873
+ return `- ${q} → ${answer}`;
874
+ });
875
+ return [...kept, '', '## Asked', ...block_lines].join('\n');
709
876
  }
710
877
  function renderSection(section, capChars) {
711
878
  const lines = [];
712
879
  for (const turn of section.turns) {
713
880
  if (turn.user.length > 0)
714
881
  lines.push(`\n## user\n${turn.user.join('\n')}`);
715
- if (turn.extracted !== undefined) {
716
- let block = turn.extracted;
882
+ // An extraction whose every field is empty renders nothing: a heading followed by
883
+ // no body reads as a turn that did something but says nothing.
884
+ if (turn.extracted !== undefined && renderExtractionBlock(turn.extracted).length > 0) {
885
+ let block = renderExtractionBlock(turn.extracted);
717
886
  if (capChars !== undefined && block.length > capChars) {
718
887
  block = `${block.slice(0, capChars)}\n…(+${block.length - capChars} chars)`;
719
888
  }
@@ -728,7 +897,7 @@ function renderSection(section, capChars) {
728
897
  if (turn.writes.length > 0)
729
898
  trailer.push(` wrote: ${turn.writes.join(', ')}`);
730
899
  const body = trailer.length > 0 ? `${block}\n${trailer.join('\n')}` : block;
731
- lines.push(`### assistant\n${moveAskedLast(body)}`);
900
+ lines.push(`### assistant\n${moveAskedLast(body, turn.asked)}`);
732
901
  }
733
902
  else {
734
903
  let body = turn.assistant.join('\n');
@@ -760,7 +929,9 @@ function assistantChars(sections) {
760
929
  let total = 0;
761
930
  for (const section of sections) {
762
931
  for (const turn of section.turns) {
763
- total += turn.extracted !== undefined ? turn.extracted.length : turn.assistant.join('\n').length;
932
+ total += turn.extracted !== undefined
933
+ ? renderExtractionBlock(turn.extracted).length
934
+ : turn.assistant.join('\n').length;
764
935
  }
765
936
  }
766
937
  return total;
@@ -1025,14 +1196,7 @@ async function extractBatch(ctx, agent, batch, signal) {
1025
1196
  const answer = chunks.join('').trim();
1026
1197
  if (answer.length === 0)
1027
1198
  return out;
1028
- const blocks = answer.split(/^=== SLOT ([^\s(]+)[^=]*===$/m);
1029
- for (let index = 1; index < blocks.length; index += 2) {
1030
- const key = blocks[index];
1031
- const body = pruneEmptySections((blocks[index + 1] ?? '').trim());
1032
- if (key !== undefined && body.length > 0)
1033
- out.set(key, body);
1034
- }
1035
- return out;
1199
+ return parseExtraction(answer);
1036
1200
  }
1037
1201
  /**
1038
1202
  * Deterministic compaction backend: verbatim prose, pointerized tools, no model
@@ -97,6 +97,32 @@ export declare function isErrorResult(event: SessionEvent): boolean;
97
97
  * nothing substantive remains.
98
98
  */
99
99
  export declare function pruneEmptySections(block: string): string;
100
+ /** One slot's extraction, as the model returns it. */
101
+ export interface Extraction {
102
+ did: string[];
103
+ concluded: string[];
104
+ overturned: string[];
105
+ }
106
+ /**
107
+ * Parse the model's JSON reply into per-slot extractions.
108
+ *
109
+ * The reply used to be free-form markdown, which let a heading share a line with
110
+ * its body — a real block read `… 重出 4 屏 Concluded Stitch 会回填真实车牌`, and no
111
+ * post-hoc regex can decide where that sentence ends and the next heading begins.
112
+ * Fields remove the ambiguity: the renderer owns every heading and bullet.
113
+ *
114
+ * @param answer - the model's raw reply.
115
+ * @returns extractions by slot key; empty when the reply is not usable JSON.
116
+ */
117
+ export declare function parseExtraction(answer: string): Map<string, Extraction>;
118
+ /**
119
+ * Render one extraction as the digest block, headings included.
120
+ *
121
+ * @param extraction - the fields for one slot.
122
+ * @returns markdown with a heading per non-empty field; empty string when every
123
+ * field is empty.
124
+ */
125
+ export declare function renderExtractionBlock(extraction: Extraction | undefined): string;
100
126
  /**
101
127
  * Build the compact per-turn trace fed to the summarizer.
102
128
  *
@@ -122,6 +148,17 @@ interface Turn {
122
148
  resultBytes: number;
123
149
  errors: string[];
124
150
  writes: string[];
151
+ /**
152
+ * Question/answer pairs the assistant put to the user in this turn.
153
+ *
154
+ * Rendered by code rather than by the model: the model changed its Asked format
155
+ * four times across runs, and each change silently broke the position or the
156
+ * content. Both halves are in the log, so there is nothing to summarise.
157
+ */
158
+ asked: {
159
+ question: string;
160
+ answer: string;
161
+ }[];
125
162
  /**
126
163
  * The extracted summary for this turn, when extraction succeeded.
127
164
  *
@@ -129,7 +166,7 @@ interface Turn {
129
166
  * the assistant prose's place in the digest: keeping both duplicated the same
130
167
  * content and pushed the prose out through the budget.
131
168
  */
132
- extracted?: string;
169
+ extracted?: Extraction;
133
170
  }
134
171
  /** One digest section: everything from one non-injected user message to the next. */
135
172
  interface Section {
@@ -170,7 +207,10 @@ export declare function buildSections(events: readonly SessionEvent[]): Section[
170
207
  * @param block - one extraction block, possibly malformed.
171
208
  * @returns the same block with Asked last; unchanged when Asked is absent or already last.
172
209
  */
173
- export declare function moveAskedLast(block: string): string;
210
+ export declare function moveAskedLast(block: string, asked?: readonly {
211
+ question: string;
212
+ answer: string;
213
+ }[]): string;
174
214
  /**
175
215
  * Render the digest under a hard character budget.
176
216
  *
@@ -196,7 +236,7 @@ export declare function moveAskedLast(block: string): string;
196
236
  * ceiling; the tiers exist for the turns where extraction was unavailable and
197
237
  * the prose is all that remains.
198
238
  */
199
- export declare function renderDigest(events: readonly SessionEvent[], budgetTokens: number, extracted?: ReadonlyMap<string, string>): string;
239
+ export declare function renderDigest(events: readonly SessionEvent[], budgetTokens: number, extracted?: ReadonlyMap<string, Extraction>): string;
200
240
  /**
201
241
  * The surface seqs this compaction shadows, recovered from the summarization
202
242
  * input's message count.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logictan/dsh-verbatim-compaction",
3
- "version": "0.9.0",
3
+ "version": "0.11.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",