@logictan/dsh-verbatim-compaction 0.13.3 → 0.13.4

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/lib/index.js CHANGED
@@ -238,8 +238,27 @@ function toolCallsOf(event) {
238
238
  }
239
239
  return calls;
240
240
  }
241
- /** The `questions[]` payload of an `ask_user_question` call, as `{id → text}`. */
242
- function questionTextsOf(argumentsJson) {
241
+ function optionLabelsOf(raw) {
242
+ if (!Array.isArray(raw))
243
+ return [];
244
+ const labels = [];
245
+ for (const entry of raw) {
246
+ if (typeof entry === 'string') {
247
+ const trimmed = entry.trim();
248
+ if (trimmed.length > 0)
249
+ labels.push(trimmed);
250
+ continue;
251
+ }
252
+ if (typeof entry !== 'object' || entry === null)
253
+ continue;
254
+ const label = entry['label'];
255
+ if (typeof label === 'string' && label.trim().length > 0)
256
+ labels.push(label.trim());
257
+ }
258
+ return labels;
259
+ }
260
+ /** The `questions[]` payload of an `ask_user_question` call, as `{id → {question, options}}`. */
261
+ function questionSpecsOf(argumentsJson) {
243
262
  const out = new Map();
244
263
  let parsed;
245
264
  try {
@@ -259,8 +278,9 @@ function questionTextsOf(argumentsJson) {
259
278
  const record = question;
260
279
  const id = record['id'];
261
280
  const text = typeof record['question'] === 'string' ? record['question'] : undefined;
262
- if (typeof id === 'string' && text !== undefined)
263
- out.set(id, text);
281
+ if (typeof id === 'string' && text !== undefined) {
282
+ out.set(id, { question: text, options: optionLabelsOf(record['options']) });
283
+ }
264
284
  }
265
285
  return out;
266
286
  }
@@ -277,10 +297,10 @@ function questionTextsOf(argumentsJson) {
277
297
  * user's actual observations rather than a menu label.
278
298
  *
279
299
  * @param text - the JSON body.
280
- * @param texts - question id to question text, from the call's arguments.
300
+ * @param specs - question id to question text and option labels, from the call's arguments.
281
301
  * @returns one entry per answered question; empty when the body is not a batch.
282
302
  */
283
- function answersOf(text, texts) {
303
+ function answersOf(text, specs) {
284
304
  let parsed;
285
305
  try {
286
306
  parsed = JSON.parse(text);
@@ -294,15 +314,18 @@ function answersOf(text, texts) {
294
314
  // not depend on the call still being in the same turn's events.
295
315
  const body = parsed;
296
316
  const own = Array.isArray(body['questions']) ? body['questions'] : [];
297
- const merged = new Map(texts);
317
+ const merged = new Map(specs);
298
318
  for (const question of own) {
299
319
  if (typeof question !== 'object' || question === null)
300
320
  continue;
301
321
  const record = question;
302
322
  const id = record['id'];
303
323
  const text = record['question'];
304
- if (typeof id === 'string' && typeof text === 'string')
305
- merged.set(id, text);
324
+ if (typeof id === 'string' && typeof text === 'string') {
325
+ const existing = merged.get(id);
326
+ const options = optionLabelsOf(record['options']);
327
+ merged.set(id, { question: text, options: options.length > 0 ? options : (existing?.options ?? []) });
328
+ }
306
329
  }
307
330
  const answers = body['answers'];
308
331
  if (!Array.isArray(answers))
@@ -313,8 +336,8 @@ function answersOf(text, texts) {
313
336
  continue;
314
337
  const record = answer;
315
338
  const id = typeof record['id'] === 'string' ? record['id'] : '';
316
- const question = merged.get(id);
317
- if (question === undefined)
339
+ const spec = merged.get(id);
340
+ if (spec === undefined)
318
341
  continue;
319
342
  const selected = Array.isArray(record['selected'])
320
343
  ? record['selected'].map((value) => String(value)).filter((value) => value.length > 0)
@@ -322,7 +345,7 @@ function answersOf(text, texts) {
322
345
  const typed = typeof record['custom'] === 'string' ? record['custom'].trim() : '';
323
346
  if (selected.length === 0 && typed.length === 0)
324
347
  continue;
325
- out.push({ question, selected, typed });
348
+ out.push({ question: spec.question, options: spec.options, selected, typed });
326
349
  }
327
350
  return out;
328
351
  }
@@ -359,7 +382,7 @@ const EXTRACT_INSTRUCTION = [
359
382
  '- `options`: what the user could pick from, in order, one short line each, with their own numbering stripped. The list is often a paragraph or two above the question. Use [] when the question offered none.',
360
383
  // The reply is the next turn's `## user` line, already verbatim in the digest.
361
384
  // Asking for it here printed the same sentence twice.
362
- "- Use [] for `asked` when the turn asked nothing or when questions were already answered via `ask_user_question`. Do not report the user's reply.",
385
+ "- Use [] for `asked` when the turn asked nothing, when questions were already answered via `ask_user_question`, or when questions raised earlier were already resolved later in the same turn's prose. Do not report the user's reply.",
363
386
  '',
364
387
  'Write strings in the same language as the material. A session whose requests are Chinese gets Chinese text; do not switch to English.',
365
388
  ].join('\n');
@@ -762,7 +785,7 @@ function buildSectionsWithEvents(events) {
762
785
  return next;
763
786
  };
764
787
  const recordedObjectives = new Set();
765
- const questionTexts = new Map();
788
+ const questionSpecs = new Map();
766
789
  const questionCallIds = new Set();
767
790
  for (const event of events) {
768
791
  if (event.type === 'turn/start') {
@@ -791,13 +814,13 @@ function buildSectionsWithEvents(events) {
791
814
  const callId = messageOf(event)?.toolCallId;
792
815
  if (callId === undefined || !questionCallIds.has(callId) || currentTurn === undefined)
793
816
  continue;
794
- currentTurn.answered.push(...answersOf(textOf(event), questionTexts));
817
+ currentTurn.answered.push(...answersOf(textOf(event), questionSpecs));
795
818
  continue;
796
819
  }
797
820
  if (sourceKind(event) === 'user-question-reply') {
798
821
  currentEvents?.push(event);
799
822
  if (currentTurn !== undefined)
800
- currentTurn.answered.push(...answersOf(textOf(event), questionTexts));
823
+ currentTurn.answered.push(...answersOf(textOf(event), questionSpecs));
801
824
  continue;
802
825
  }
803
826
  if (event.type !== 'user/message' && event.type !== 'assistant/message')
@@ -822,8 +845,8 @@ function buildSectionsWithEvents(events) {
822
845
  currentTurn.assistant.push(text);
823
846
  for (const call of toolCallsOf(event)) {
824
847
  if (call.name === 'ask_user_question') {
825
- for (const [id, question] of questionTextsOf(call.arguments))
826
- questionTexts.set(id, question);
848
+ for (const [id, spec] of questionSpecsOf(call.arguments))
849
+ questionSpecs.set(id, spec);
827
850
  questionCallIds.add(call.id);
828
851
  continue;
829
852
  }
@@ -930,23 +953,136 @@ function materialKey(events, options) {
930
953
  * The tool pointer line stays either way: it is one line, and it is the only
931
954
  * record of what was actually run when the prose and extraction both say little.
932
955
  */
933
- /** Normalize a question string for fuzzy duplicate comparison between Answers and Asked. */
956
+ /** Generic Chinese/English question boilerplate excluded from token-overlap dedupe. */
957
+ const QUESTION_STOP_TOKENS = new Set([
958
+ '是否', '要不要', '怎么', '如何', '哪个', '哪种', '哪一', '哪些', '什么', '还是', '或者', '以及',
959
+ '一下', '一起', '一并', '继续', '现在', '需要', '可以', '应该', '确认', '决定', '选择', '处理',
960
+ '修改', '改动', '保留', '不动', '直接', '如果', '那么', '这个', '那个', '这两', '两项', '两处',
961
+ '三处', '四处', '用户', '拍板', '我们', '你们', '他们', '已经', '不要', '不行',
962
+ 'the', 'and', 'for', 'with', 'this', 'that', 'from', 'should', 'would', 'which', 'what', 'how',
963
+ 'are', 'you', 'can', 'not', 'use', 'into', 'about', 'want', 'keep', 'change', 'yes', 'no',
964
+ ]);
965
+ function stripRecommendationTag(text) {
966
+ return text.replace(/[((]\s*(?:推荐|recommended)\s*[))]/gi, '');
967
+ }
968
+ /** Normalize a question or option string for fuzzy duplicate comparison between Answers and Asked. */
934
969
  function normalizeQuestionText(text) {
935
- return text.toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, '');
970
+ return stripRecommendationTag(text).toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, '');
971
+ }
972
+ /** Extract substantive ASCII words and CJK bigrams for cross-question paraphrase matching. */
973
+ function extractQuestionTokens(text) {
974
+ const lower = stripRecommendationTag(text).toLowerCase();
975
+ const tokens = new Set();
976
+ for (const match of lower.matchAll(/[a-z0-9_]{2,}/g)) {
977
+ const token = match[0];
978
+ if (!QUESTION_STOP_TOKENS.has(token))
979
+ tokens.add(token);
980
+ }
981
+ for (const match of lower.matchAll(/[\p{Script=Han}]{2,}/gu)) {
982
+ const run = match[0];
983
+ for (let i = 0; i < run.length - 1; i += 1) {
984
+ const bigram = run.slice(i, i + 2);
985
+ if (!QUESTION_STOP_TOKENS.has(bigram))
986
+ tokens.add(bigram);
987
+ }
988
+ }
989
+ return tokens;
990
+ }
991
+ function tokenOverlapCount(source, target) {
992
+ let hits = 0;
993
+ for (const token of source) {
994
+ if (target.has(token))
995
+ hits += 1;
996
+ }
997
+ return hits;
998
+ }
999
+ function toOptionMatchTarget(text) {
1000
+ return {
1001
+ norm: normalizeQuestionText(text),
1002
+ tokens: extractQuestionTokens(text),
1003
+ };
936
1004
  }
937
- /** Drop `asked` entries that duplicate questions already answered via `ask_user_question` in the same turn. */
1005
+ function optionMatchesTarget(candidate, target) {
1006
+ if (candidate.norm.length >= 5
1007
+ && target.norm.length >= 5
1008
+ && (target.norm.includes(candidate.norm) || candidate.norm.includes(target.norm))) {
1009
+ return true;
1010
+ }
1011
+ if (candidate.tokens.size >= 3 && target.tokens.size >= 3) {
1012
+ const hits = tokenOverlapCount(candidate.tokens, target.tokens);
1013
+ if (hits >= 3 && hits / candidate.tokens.size >= 0.6)
1014
+ return true;
1015
+ }
1016
+ return false;
1017
+ }
1018
+ /** Drop `asked` entries that duplicate or paraphrase questions already answered via `ask_user_question` in the same turn. */
938
1019
  function dedupeAskedAgainstAnswers(extraction, answered) {
939
1020
  if (answered.length === 0 || extraction.asked.length === 0)
940
1021
  return extraction;
941
1022
  const answeredNorms = answered.map((item) => normalizeQuestionText(item.question)).filter((q) => q.length > 0);
942
1023
  if (answeredNorms.length === 0)
943
1024
  return extraction;
1025
+ // Combined question + answer token corpus catches merged paraphrases across multiple
1026
+ // answered questions; unselected options stay out of this corpus so a later follow-up
1027
+ // prose question sharing a domain noun does not cross-bleed.
1028
+ const corpusTokens = new Set();
1029
+ const answerTargets = [];
1030
+ const offeredTargets = [];
1031
+ for (const item of answered) {
1032
+ for (const token of extractQuestionTokens(item.question))
1033
+ corpusTokens.add(token);
1034
+ for (const selected of item.selected) {
1035
+ for (const token of extractQuestionTokens(selected))
1036
+ corpusTokens.add(token);
1037
+ const target = toOptionMatchTarget(selected);
1038
+ if (target.norm.length >= 5 || target.tokens.size >= 3)
1039
+ answerTargets.push(target);
1040
+ }
1041
+ if (item.typed.length > 0) {
1042
+ for (const token of extractQuestionTokens(item.typed))
1043
+ corpusTokens.add(token);
1044
+ const target = toOptionMatchTarget(item.typed);
1045
+ if (target.norm.length >= 5 || target.tokens.size >= 3)
1046
+ answerTargets.push(target);
1047
+ }
1048
+ for (const opt of item.options) {
1049
+ const target = toOptionMatchTarget(opt);
1050
+ if (target.norm.length >= 5 || target.tokens.size >= 3)
1051
+ offeredTargets.push(target);
1052
+ }
1053
+ }
944
1054
  const filtered = extraction.asked.filter((pair) => {
945
1055
  const q = normalizeQuestionText(pair.question);
946
1056
  if (q.length === 0)
947
1057
  return true;
948
- return !answeredNorms.some((ans) => (ans === q
949
- || (q.length >= 4 && ans.length >= 4 && (ans.includes(q) || q.includes(ans)))));
1058
+ if (answeredNorms.some((ans) => (ans === q
1059
+ || (q.length >= 4 && ans.length >= 4 && (ans.includes(q) || q.includes(ans)))))) {
1060
+ return false;
1061
+ }
1062
+ const qTokens = extractQuestionTokens(pair.question);
1063
+ if (qTokens.size > 0 && corpusTokens.size > 0) {
1064
+ const hits = tokenOverlapCount(qTokens, corpusTokens);
1065
+ const ratio = hits / qTokens.size;
1066
+ if ((hits >= 3 && ratio >= 0.4) || (hits >= 5 && ratio >= 0.35))
1067
+ return false;
1068
+ }
1069
+ if (pair.options.length > 0 && (answerTargets.length > 0 || offeredTargets.length > 0)) {
1070
+ const matchedOfferedIndices = new Set();
1071
+ for (const opt of pair.options) {
1072
+ const candidate = toOptionMatchTarget(opt);
1073
+ if (answerTargets.some((target) => optionMatchesTarget(candidate, target)))
1074
+ return false;
1075
+ for (let i = 0; i < offeredTargets.length; i += 1) {
1076
+ if (optionMatchesTarget(candidate, offeredTargets[i])) {
1077
+ matchedOfferedIndices.add(i);
1078
+ break;
1079
+ }
1080
+ }
1081
+ }
1082
+ if (matchedOfferedIndices.size >= 2)
1083
+ return false;
1084
+ }
1085
+ return true;
950
1086
  });
951
1087
  return filtered.length === extraction.asked.length ? extraction : { ...extraction, asked: filtered };
952
1088
  }
@@ -50,6 +50,8 @@ export interface SummaryResult {
50
50
  /** One question the user answered through the question tool, with its answer. */
51
51
  interface AnsweredQuestion {
52
52
  question: string;
53
+ /** Option labels offered by `ask_user_question`, used to dedupe paraphrased `## Asked`. */
54
+ options: string[];
53
55
  /** The labels the user picked, in the order they were offered. */
54
56
  selected: string[];
55
57
  /** What the user typed instead of picking, when they did. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logictan/dsh-verbatim-compaction",
3
- "version": "0.13.3",
3
+ "version": "0.13.4",
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",