@logictan/dsh-verbatim-compaction 0.10.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,8 @@
82
82
 
83
83
  缓存的键是提取材料的哈希(用户请求 + 助手正文 + 工具轨迹),不是 slot 位置:位置会随历史增长而错位,内容变了哈希就变,不会读到过期块。缓存是进程内的,重启即失效——代价只是重新提取一次,与加缓存前行为一致。
84
84
 
85
+ 提取调用返回 **JSON 字段**(`{"slots":[{"key","did","concluded","overturned"}]}`),标题、项目符号、空行全部由代码拼装。此前是自由 markdown,模型会把标题和正文挤在同一行——真实产出里出现过 `… 重出 4 屏 Concluded Stitch 会回填真实车牌`,事后无法用正则判断句子在哪结束、下一个标题从哪开始。字段化之后这个歧义不存在。
86
+
85
87
  `## Asked` 由**代码**从日志直接生成,不使用模型的输出:问题原文、选项、用户的选择(含打字回答)逐字取自 `ask_user_question` 的调用与结果。模型对这一段先后换过四种写法(`## Asked`、`**Asked**:`、`- Asked:`、中文 `问:`),每次换法都会破坏位置或内容,而这两半本来就在日志里,没有可概括的余地。模型写的那段一律丢弃。
86
88
 
87
89
  `## Asked` 记的是「助手问了什么 + 用户选了什么」。原来指令写「record the question, never the answer」——本意是防模型把用户请求抄进这一节,却被照字面执行:实测材料里两条 `ANSWER` 都在(其中一条把整个设计方向改成「游戏化、赛博朋克、提取 3D 模型」),模型只写了问题。
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. */
@@ -807,8 +879,10 @@ function renderSection(section, capChars) {
807
879
  for (const turn of section.turns) {
808
880
  if (turn.user.length > 0)
809
881
  lines.push(`\n## user\n${turn.user.join('\n')}`);
810
- if (turn.extracted !== undefined) {
811
- 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);
812
886
  if (capChars !== undefined && block.length > capChars) {
813
887
  block = `${block.slice(0, capChars)}\n…(+${block.length - capChars} chars)`;
814
888
  }
@@ -855,7 +929,9 @@ function assistantChars(sections) {
855
929
  let total = 0;
856
930
  for (const section of sections) {
857
931
  for (const turn of section.turns) {
858
- 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;
859
935
  }
860
936
  }
861
937
  return total;
@@ -1120,14 +1196,7 @@ async function extractBatch(ctx, agent, batch, signal) {
1120
1196
  const answer = chunks.join('').trim();
1121
1197
  if (answer.length === 0)
1122
1198
  return out;
1123
- const blocks = answer.split(/^=== SLOT ([^\s(]+)[^=]*===$/m);
1124
- for (let index = 1; index < blocks.length; index += 2) {
1125
- const key = blocks[index];
1126
- const body = pruneEmptySections((blocks[index + 1] ?? '').trim());
1127
- if (key !== undefined && body.length > 0)
1128
- out.set(key, body);
1129
- }
1130
- return out;
1199
+ return parseExtraction(answer);
1131
1200
  }
1132
1201
  /**
1133
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
  *
@@ -140,7 +166,7 @@ interface Turn {
140
166
  * the assistant prose's place in the digest: keeping both duplicated the same
141
167
  * content and pushed the prose out through the budget.
142
168
  */
143
- extracted?: string;
169
+ extracted?: Extraction;
144
170
  }
145
171
  /** One digest section: everything from one non-injected user message to the next. */
146
172
  interface Section {
@@ -210,7 +236,7 @@ export declare function moveAskedLast(block: string, asked?: readonly {
210
236
  * ceiling; the tiers exist for the turns where extraction was unavailable and
211
237
  * the prose is all that remains.
212
238
  */
213
- 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;
214
240
  /**
215
241
  * The surface seqs this compaction shadows, recovered from the summarization
216
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.10.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",