dsh-memory-bond 0.3.0-beta.0 → 1.0.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.
Files changed (145) hide show
  1. package/CHANGELOG.md +6 -7
  2. package/README.md +125 -91
  3. package/README.zh-CN.md +122 -92
  4. package/SECURITY.md +29 -0
  5. package/dist/audit.js +155 -80
  6. package/dist/automatic.js +10 -2
  7. package/dist/client.js +2035 -0
  8. package/dist/command-scope.js +4 -4
  9. package/dist/commands.js +15 -9
  10. package/dist/consolidation-store.js +87 -20
  11. package/dist/consolidation.js +2 -6
  12. package/dist/domain.js +8 -4
  13. package/dist/encoder.js +46 -5
  14. package/dist/file-import-store.js +120 -0
  15. package/dist/file-import.js +265 -0
  16. package/dist/foreground-attempts.js +91 -0
  17. package/dist/guidance.js +133 -92
  18. package/dist/host.js +13 -0
  19. package/dist/index-policy.js +91 -48
  20. package/dist/index.js +102 -40
  21. package/dist/knowledge-hooks.js +70 -27
  22. package/dist/knowledge.js +2 -3
  23. package/dist/maintenance-store.js +38 -4
  24. package/dist/maintenance.js +29 -5
  25. package/dist/personal.js +37 -0
  26. package/dist/policy.js +45 -47
  27. package/dist/prompt-copy.js +93 -0
  28. package/dist/proposal-receipts.js +70 -0
  29. package/dist/proposal-review.js +656 -0
  30. package/dist/propose-contract.js +32 -36
  31. package/dist/question-answers.js +86 -29
  32. package/dist/retrieval.js +25 -8
  33. package/dist/scope-narrowing.js +49 -0
  34. package/dist/search-index.js +93 -13
  35. package/dist/semantic.js +69 -207
  36. package/dist/service.js +633 -204
  37. package/dist/sharing.js +7 -13
  38. package/dist/sources.js +28 -3
  39. package/dist/store.js +432 -96
  40. package/dist/tool-experience.js +87 -0
  41. package/dist/turn-review-store.js +83 -16
  42. package/dist/turn-review.js +155 -59
  43. package/dist/ui.js +128 -26
  44. package/dist/vector-index.js +69 -33
  45. package/docs/architecture.zh-CN.md +52 -0
  46. package/docs/benchmark.zh-CN.md +60 -0
  47. package/docs/benchmarks/repository-tasks.json +5355 -0
  48. package/docs/images/bond-memory-principle-en.svg +644 -0
  49. package/docs/images/bond-memory-principle-zh.svg +644 -0
  50. package/docs/images/bond-memory-principle.drawio +644 -0
  51. package/docs/images/memory-settings-en.png +0 -0
  52. package/docs/images/memory-settings-zh.png +0 -0
  53. package/docs/images/memory-turn-recalled-en.png +0 -0
  54. package/docs/images/memory-turn-recalled-zh.png +0 -0
  55. package/docs/images/memory-turn-saved-en.png +0 -0
  56. package/docs/images/memory-turn-saved-zh.png +0 -0
  57. package/docs/media/memory-bond-name-en.gif +0 -0
  58. package/docs/media/memory-bond-name-en.mp4 +0 -0
  59. package/docs/media/memory-bond-name-zh.gif +0 -0
  60. package/docs/media/memory-bond-name-zh.mp4 +0 -0
  61. package/locale/detail.en.md +5 -1
  62. package/locale/detail.zh.md +5 -1
  63. package/locale/en.json +338 -0
  64. package/locale/zh.json +338 -0
  65. package/native/embeddings/NOTICE.md +2 -2
  66. package/package.json +39 -19
  67. package/scripts/benchmark-bond.mjs +72 -0
  68. package/scripts/benchmark-conditions.mjs +144 -0
  69. package/scripts/benchmark-example.mjs +37 -0
  70. package/scripts/benchmark-scale.mjs +119 -0
  71. package/scripts/benchmark-scenarios.mjs +57 -0
  72. package/scripts/benchmark-tasks.mjs +244 -0
  73. package/src/audit.ts +144 -85
  74. package/src/automatic.ts +12 -2
  75. package/src/command-scope.ts +4 -4
  76. package/src/commands.ts +12 -8
  77. package/src/consolidation-store.ts +80 -18
  78. package/src/consolidation.ts +2 -6
  79. package/src/domain.ts +9 -4
  80. package/src/encoder.ts +46 -6
  81. package/src/file-import-store.ts +139 -0
  82. package/src/file-import.ts +256 -0
  83. package/src/foreground-attempts.ts +97 -0
  84. package/src/guidance.ts +138 -102
  85. package/src/host.ts +22 -2
  86. package/src/index-policy.ts +93 -46
  87. package/src/index.ts +87 -43
  88. package/src/knowledge-hooks.ts +71 -29
  89. package/src/knowledge.ts +2 -3
  90. package/src/maintenance-store.ts +37 -4
  91. package/src/maintenance.ts +25 -5
  92. package/src/personal.ts +36 -0
  93. package/src/policy.ts +55 -52
  94. package/src/prompt-copy.ts +99 -0
  95. package/src/proposal-receipts.ts +59 -0
  96. package/src/proposal-review.ts +614 -0
  97. package/src/propose-contract.ts +31 -35
  98. package/src/question-answers.ts +99 -29
  99. package/src/retrieval.ts +26 -9
  100. package/src/scope-narrowing.ts +58 -0
  101. package/src/search-index.ts +94 -14
  102. package/src/semantic.ts +67 -188
  103. package/src/service.ts +595 -210
  104. package/src/sharing.ts +7 -14
  105. package/src/sources.ts +26 -4
  106. package/src/store.ts +434 -97
  107. package/src/tool-experience.ts +93 -0
  108. package/src/turn-review-store.ts +86 -15
  109. package/src/turn-review.ts +142 -60
  110. package/src/ui.ts +122 -27
  111. package/src/vector-index.ts +57 -29
  112. package/client/index.js +0 -1186
  113. package/design/dsh-memory-plugin-design.md +0 -46
  114. package/design/dsh-memory-plugin-evaluation.md +0 -135
  115. package/design/evaluations/locomo-conv-26-2026-12-03.json +0 -252
  116. package/design/evaluations/locomo-conv-26-paired-2026-12-03.json +0 -549
  117. package/design/evaluations/locomo-conv-26-write-replay-2026-12-03.json +0 -289
  118. package/design/evaluations/project-memory-tasks-2026-12-03.json +0 -1059
  119. package/design/memory-lifecycle-consolidation.excalidraw +0 -1212
  120. package/design/memory-lifecycle-consolidation.mobile.excalidraw +0 -1083
  121. package/design/memory-lifecycle-consolidation.mobile.svg +0 -2
  122. package/design/memory-lifecycle-consolidation.mobile.zh-CN.excalidraw +0 -1083
  123. package/design/memory-lifecycle-consolidation.mobile.zh-CN.svg +0 -94
  124. package/design/memory-lifecycle-consolidation.svg +0 -2
  125. package/design/memory-lifecycle-consolidation.zh-CN.excalidraw +0 -1212
  126. package/design/memory-lifecycle-consolidation.zh-CN.svg +0 -94
  127. package/design/memory-lifecycle.excalidraw +0 -2105
  128. package/design/memory-lifecycle.mobile.excalidraw +0 -1896
  129. package/design/memory-lifecycle.mobile.svg +0 -95
  130. package/design/memory-lifecycle.mobile.zh-CN.excalidraw +0 -1896
  131. package/design/memory-lifecycle.mobile.zh-CN.svg +0 -97
  132. package/design/memory-lifecycle.svg +0 -95
  133. package/design/memory-lifecycle.zh-CN.excalidraw +0 -2105
  134. package/design/memory-lifecycle.zh-CN.svg +0 -97
  135. package/native/embeddings/LICENSE +0 -21
  136. package/native/embeddings/en/model.onnx +0 -4
  137. package/native/embeddings/en/vocab.txt +0 -30522
  138. package/native/embeddings/runtime/LICENSE +0 -21
  139. package/native/embeddings/runtime/ThirdPartyNotices.txt +0 -6156
  140. package/native/embeddings/runtime/ort-wasm-simd-threaded.mjs +0 -70
  141. package/native/embeddings/runtime/ort-wasm-simd-threaded.wasm +0 -0
  142. package/native/embeddings/runtime/ort.wasm.min.mjs +0 -7
  143. package/native/embeddings/worker.mjs +0 -97
  144. package/native/embeddings/zh/model.onnx +0 -0
  145. package/native/embeddings/zh/vocab.txt +0 -21128
@@ -1,42 +1,38 @@
1
- export const memoryInstructions = [
2
- '判断用户亲口陈述的内容是否值得跨轮复用,以及应该怎样使用。稳定事实、长期偏好或约定可以保存。保留主语、取值、否定、适用条件和例外。无法判断时跳过。',
3
- '长消息里先把已核实的一到三项写入,再继续提取。首次提议可直接提交,由工具核对重复项。需要定位更正对象时先查旧版本。同事的偏好不归给用户,当前项目的约定限于 project,“仅在 CI”要保留条件,“仅这一次”不作长期约定。',
4
- 'scope 选 global(用户跨项目适用)或 project(当前工程)。subject 和 topic 使用简短且不含取值的开放名称,与已有记录表示同一主体和主题时沿用其名称。keywords 可给出少量检索别名。',
5
- '希望助手在相关任务中主动遵守的约定标 usage:proactive。以后在需要时才查的事实或资料标 on_demand,这是默认值。按语境判断用途,不依赖主题。敏感资料标 sensitive:true,按需读取。',
6
- '重复陈述沿用已有主题、动作和适用条件。只有原话明确更正时标 correction:true,引用包含更正意图和新值的短句。先查同一主体和条件的现行记录,找到时带上 replaces:{id,rev}。action 只写今后应使用的结论或命令,优先逐字取用新值。归属或替换关系不清时保留原记录。涉及他人的私人资料,只有用户明确要求长期留存且主体清楚时才考虑提议。一次性要求、举例、猜测、凭据和禁止留存的内容跳过。',
7
- 'user_quote 逐字引用同一条用户输入中连续且足以支持结论的原话。ask_user_question 的 question 仅用来理解手填回答,引用必须来自回答 text。预设选项和助手的话不作为依据。',
8
- ].join(' ');
9
- export const proposeTool = {
10
- description: memoryInstructions + ' 遇到 unsupported_correction,可以从引文中逐字提取明确的新值重试一次。仍无法核对时保留原记录。保存状态由聊天回执展示。日常对话直接回应用户的话。用户询问记忆状态或明确要求保存时,按 results 的输入序号逐项回答,只有 saved 或 duplicate 表示该项已记住;partial 表示本批仅部分成功。',
11
- parameters: {
12
- type: 'object', additionalProperties: false, required: ['items'],
13
- properties: {
14
- items: {
15
- type: 'array', minItems: 1, maxItems: 32,
1
+ import { prompts } from "./prompt-copy.js";
2
+ export function proposalContract(language) {
3
+ const copy = prompts[language];
4
+ return {
5
+ description: copy.write + ' ' + copy.propose,
6
+ parameters: {
7
+ type: 'object', additionalProperties: false, required: ['items'],
8
+ properties: {
16
9
  items: {
17
- type: 'object', additionalProperties: false, required: ['scope', 'kind', 'topic', 'user_quote', 'action'],
18
- properties: {
19
- user_quote: { type: 'string', minLength: 1, maxLength: 480, description: '逐字引用本轮用户原话并保留限定语。对于 ask_user_question,仅引用用户手填的回答。题干帮助理解回答,预设选项不能充当引文。' },
20
- action: { type: 'string', minLength: 1, maxLength: 480, description: '原话陈述的现行事实、偏好或长期指令。更正时仅保留新值,旧值和变更说明属于版本历史。' },
21
- scope: { type: 'string', enum: ['global', 'project'] },
22
- kind: { type: 'string', enum: ['fact', 'preference', 'rule'] },
23
- topic: { type: 'string', minLength: 1, maxLength: 80, description: '简短稳定的主题名。相同主题沿用已有名称。' },
24
- subject: { type: 'string', minLength: 1, maxLength: 80, description: '这条记忆属于谁或什么对象。同一主体沿用一致名称。' },
25
- usage: { type: 'string', enum: ['proactive', 'on_demand'] },
26
- keywords: { type: 'array', maxItems: 8, items: { type: 'string', minLength: 1, maxLength: 40 }, description: '简短检索别称。' },
27
- sensitive: { type: 'boolean', description: '需保护的内容标记为 true,仅按需使用。' },
28
- correction: { type: 'boolean', description: '原话明确将先前的事实或长期约定改为新值时为 true。' },
29
- replaces: {
30
- type: 'object', additionalProperties: false, required: ['id', 'rev'],
31
- properties: { id: { type: 'string' }, rev: { type: 'integer', minimum: 1 } },
10
+ type: 'array', minItems: 1, maxItems: 32,
11
+ items: {
12
+ type: 'object', additionalProperties: false, required: ['scope', 'action'],
13
+ anyOf: [{ required: ['replaces'] }, { required: ['kind', 'topic'] }],
14
+ properties: {
15
+ user_quote: { type: 'string', minLength: 1, maxLength: 480, description: copy.user_quote },
16
+ action: { type: 'string', minLength: 1, maxLength: 480, description: copy.action },
17
+ scope: { type: 'string', enum: ['global', 'project'], description: copy.scope },
18
+ kind: { type: 'string', enum: ['fact', 'preference', 'rule'] },
19
+ topic: { type: 'string', minLength: 1, maxLength: 80, description: copy.topic },
20
+ subject: { type: 'string', minLength: 1, maxLength: 80, description: copy.subject },
21
+ usage: { type: 'string', enum: ['proactive', 'on_demand'], description: copy.usage },
22
+ keywords: { type: 'array', maxItems: 8, items: { type: 'string', minLength: 1, maxLength: 40 }, description: copy.keywords },
23
+ sensitive: { type: 'boolean', description: copy.sensitive },
24
+ replaces: {
25
+ type: 'object', additionalProperties: false, required: ['id', 'rev'],
26
+ description: copy.replaces,
27
+ properties: { id: { type: 'string' }, rev: { type: 'integer', minimum: 1 } },
28
+ },
29
+ when: { type: 'string', maxLength: 480, description: copy.when },
30
+ exceptions: { type: 'string', maxLength: 480, description: copy.exceptions },
31
+ paths: { type: 'array', maxItems: 64, items: { type: 'string', maxLength: 1024 }, description: copy.paths },
32
32
  },
33
- when: { type: 'string', maxLength: 480, description: '原话中的适用条件。' },
34
- exceptions: { type: 'string', maxLength: 480, description: '原话中的例外。' },
35
- paths: { type: 'array', maxItems: 64, items: { type: 'string', maxLength: 1024 }, description: '原话中的项目相对路径。' },
36
- conflicts_with_repo_guidance: { type: 'boolean' },
37
33
  },
38
34
  },
39
35
  },
40
36
  },
41
- },
42
- };
37
+ };
38
+ }
@@ -1,100 +1,157 @@
1
1
  import { refusesAutomaticMemory, skipsAutomaticMemory } from "./automatic.js";
2
2
  import { messageText } from "./host.js";
3
+ /** Keep the user's directive and the submitted format intact. Strip only the
4
+ * recommendation marker that DSH forms display as part of an option label. */
5
+ export function selectedAction(directive, label) {
6
+ return directive + '\n' + label.replace(/\s*(?:\((?:recommended|推荐)\)|((?:recommended|推荐)))\s*$/iu, '').trim();
7
+ }
8
+ // A submitted choice can supply the implementation of a standing request. The
9
+ // user must express its continuing applicability in their own cited words.
10
+ export function standingRequest(text) {
11
+ return /以后|今后|往后|后续|每次|每当|一律|始终|总是|长期|默认|记住|记下|之[后後]都|\b(?:always|each|every|whenever|henceforth|remember|by default|from now on|in future|in the future|going forward)\b/iu.test(text);
12
+ }
13
+ const sentences = new Intl.Segmenter(undefined, { granularity: 'sentence' });
14
+ /** Include submitted formats only for claims in a standing-request sentence.
15
+ * A cropped quote must not turn that same instruction back into a bare rule. */
16
+ export function choicesForQuote(text, quote, choices) {
17
+ if (!choices?.length)
18
+ return;
19
+ const start = text.indexOf(quote);
20
+ if (start < 0)
21
+ return;
22
+ const end = start + quote.length;
23
+ for (const sentence of sentences.segment(text)) {
24
+ if (sentence.index < end && sentence.index + sentence.segment.length > start && standingRequest(sentence.segment))
25
+ return choices;
26
+ }
27
+ }
28
+ /** Both reviewers use the same reference into the native form. Unrelated
29
+ * options require an explicit null decision before saving a standing rule. */
30
+ export function resolveSelectedDirective(action, index, choices, canSelect) {
31
+ if (index == null) {
32
+ if (choices?.length && canSelect && index !== null)
33
+ return;
34
+ return { action };
35
+ }
36
+ if (!canSelect || !Number.isSafeInteger(index) || !standingRequest(action))
37
+ return;
38
+ const option = choices?.[Number(index)];
39
+ if (!option)
40
+ return;
41
+ const combined = selectedAction(action, option.label);
42
+ if (combined.length > 480)
43
+ return;
44
+ return { action: combined, selection: { directive: action, option } };
45
+ }
3
46
  const record = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
4
47
  function eligiblePrompt(text) {
5
48
  // Unlabelled answers like "123456" cannot identify an OTP by themselves.
6
- return !skipsAutomaticMemory(text) && !/\b(?:otp|pin|one[- ]time (?:code|password)|token)\b|令牌/iu.test(text);
49
+ return !skipsAutomaticMemory(text) && !/\b(?:otp|pin|one[- ]time (?:code|password)|token)\b|令牌|密码/iu.test(text);
7
50
  }
8
- /** Read the submitted free-text fields. DSH can preselect model-suggested labels. */
9
- function customAnswers(args, result, userSeq) {
51
+ /** Keep user-typed text and submitted option labels distinct. */
52
+ function submittedForm(args, result, userSeq, callSeq, resultSeq) {
10
53
  if (!record(args) || !Array.isArray(args.questions) || !record(result) ||
11
54
  Object.keys(result).some(key => key !== 'answers') || !Array.isArray(result.answers) ||
12
55
  !args.questions.length || result.answers.length !== args.questions.length)
13
- return [];
56
+ return undefined;
14
57
  const questions = new Map();
15
58
  for (const field of args.questions) {
16
59
  if (!record(field) || typeof field.id !== 'string' || !field.id.trim() || questions.has(field.id) ||
17
60
  typeof field.question !== 'string' || !field.question.trim() ||
18
61
  (field.header !== undefined && typeof field.header !== 'string'))
19
- return [];
62
+ return undefined;
20
63
  const fieldName = field.id.replace(/([a-z])([A-Z])/gu, '$1 $2').replace(/[_-]/gu, ' ');
21
64
  questions.set(field.id, {
22
- text: field.question,
65
+ text: field.question, options: field.options,
23
66
  eligible: field.question.length <= 1024 && eligiblePrompt([fieldName, field.header, field.question].join(' ')),
24
67
  });
25
68
  }
26
69
  let offset = 0;
27
70
  const answers = [];
71
+ const selected = [];
72
+ let refusedBy;
28
73
  for (const [block, answer] of result.answers.entries()) {
29
74
  if (!record(answer) || typeof answer.id !== 'string' || !Array.isArray(answer.selected) ||
30
75
  !answer.selected.every(label => typeof label === 'string') ||
31
76
  (answer.custom !== undefined && typeof answer.custom !== 'string') ||
32
77
  Object.keys(answer).some(key => !['id', 'selected', 'custom'].includes(key)))
33
- return [];
78
+ return undefined;
34
79
  const question = questions.get(answer.id);
35
80
  if (!question)
36
- return [];
81
+ return undefined;
37
82
  questions.delete(answer.id);
38
- if (typeof answer.custom !== 'string' || !answer.custom.trim())
83
+ if (typeof answer.custom !== 'string' || !answer.custom.trim()) {
84
+ const label = answer.selected.length === 1 ? answer.selected[0] : undefined;
85
+ if (typeof label === 'string' && label.trim() && label.length <= 480 && Array.isArray(question.options) &&
86
+ question.options.filter(option => record(option) && option.label === label).length === 1) {
87
+ if (refusesAutomaticMemory(label))
88
+ refusedBy = userSeq;
89
+ else if (question.eligible && !skipsAutomaticMemory(label))
90
+ selected.push({ userSeq, callSeq, resultSeq, questionId: answer.id, question: question.text, label });
91
+ }
39
92
  continue;
93
+ }
40
94
  // Offsets refer to the decoded custom answers joined by newlines, so escaped
41
95
  // characters and surrogate pairs have the same UTF-16 positions during rechecking.
42
96
  if (question.eligible || refusesAutomaticMemory(answer.custom))
43
97
  answers.push({ question: question.text, text: answer.custom, block, offset, userSeq });
44
98
  offset += answer.custom.length + 1;
45
99
  }
46
- return answers;
100
+ return { custom: answers, selected, refusedBy };
47
101
  }
48
- /** Original, in-time results of the native ask_user_question tool. */
49
- export function questionAnswers(session, published) {
102
+ /** Only a native submitted result can supply a custom answer or an option selection. */
103
+ export function questionForm(session, published) {
50
104
  if (session.header.origin === 'subagent')
51
- return [];
52
- return verifiedQuestionAnswers(session.snapshotEvents(), session.inheritedEventCount, published);
105
+ return;
106
+ return verifiedQuestionForm(session.snapshotEvents(), session.inheritedEventCount, published);
107
+ }
108
+ export function questionAnswers(session, published) {
109
+ return questionForm(session, published)?.custom ?? [];
53
110
  }
54
- /** Accepts either a full session snapshot or a contiguous slice of its original event sequence. */
55
- export function verifiedQuestionAnswers(events, cut, published) {
111
+ /** Accepts a full session snapshot or a contiguous slice of its original event sequence. */
112
+ export function verifiedQuestionForm(events, cut, published) {
56
113
  if (published.type !== 'tool/result')
57
- return [];
114
+ return undefined;
58
115
  const offset = events[0]?.seq ?? 0;
59
116
  const at = (seq) => events[seq - offset];
60
117
  const event = at(published.seq);
61
118
  if (event?.type !== 'tool/result' || event.surfaceOp !== 'append' ||
62
119
  event.sourceEventSeqs?.length !== 1 || event.data.error !== undefined)
63
- return [];
120
+ return undefined;
64
121
  const { message, step, turn } = event.data;
65
122
  const callId = message?.toolCallId;
66
123
  if (!callId || message.role !== 'tool' || message.isError || message.source?.kind !== 'tool' ||
67
124
  message.source.callId !== callId || !Number.isSafeInteger(step) || !Number.isSafeInteger(turn))
68
- return [];
125
+ return undefined;
69
126
  const [callSeq] = event.sourceEventSeqs;
70
127
  const call = at(callSeq);
71
128
  if (callSeq < cut || callSeq >= event.seq || call?.seq !== callSeq ||
72
129
  call.type !== 'tool/call' || call.data.name !== 'ask_user_question' || call.data.callId !== callId ||
73
130
  call.data.turn !== turn || call.data.step !== step)
74
- return [];
131
+ return undefined;
75
132
  // Replay only the local turn. A call or an opening user prompt inherited at
76
133
  // a fork, or a change of project between prompt, question and answer, breaks attribution.
77
134
  let start = callSeq;
78
135
  while (start >= cut && at(start).type !== 'turn/start')
79
136
  start--;
80
137
  if (start < cut || at(start).data.turn !== turn)
81
- return [];
138
+ return undefined;
82
139
  let userSeq;
83
140
  let calls = 0, results = 0;
84
141
  for (let index = start + 1; index < offset + events.length; index++) {
85
142
  const e = at(index);
86
143
  if (e.type === 'turn/start' || e.type === 'turn/end') {
87
144
  if (e.seq < event.seq)
88
- return [];
145
+ return undefined;
89
146
  break;
90
147
  }
91
148
  if (e.seq <= event.seq && e.type === 'working-directory/change' && userSeq !== undefined)
92
- return [];
149
+ return undefined;
93
150
  if (e.seq > callSeq && e.seq < event.seq && (e.type === 'step/start' || e.type === 'step/end'))
94
- return [];
151
+ return undefined;
95
152
  if (e.seq < event.seq && e.type === 'user/message' && e.data.source?.kind === 'user') {
96
153
  if ((e.surfaceOp && e.surfaceOp !== 'append') || !eligiblePrompt(messageText(e.data)))
97
- return [];
154
+ return undefined;
98
155
  if (e.seq < callSeq)
99
156
  userSeq = e.seq;
100
157
  }
@@ -106,14 +163,14 @@ export function verifiedQuestionAnswers(events, cut, published) {
106
163
  results++;
107
164
  }
108
165
  if (userSeq === undefined || calls !== 1 || results !== 1 || message.content?.length !== 1)
109
- return [];
166
+ return undefined;
110
167
  const [part] = message.content;
111
168
  if (part.type !== 'text' || typeof part.text !== 'string' || typeof call.data.arguments !== 'string')
112
- return [];
169
+ return undefined;
113
170
  try {
114
- return customAnswers(JSON.parse(call.data.arguments), JSON.parse(part.text), userSeq);
171
+ return submittedForm(JSON.parse(call.data.arguments), JSON.parse(part.text), userSeq, callSeq, event.seq);
115
172
  }
116
173
  catch {
117
- return [];
174
+ return undefined;
118
175
  }
119
176
  }
package/dist/retrieval.js CHANGED
@@ -1,13 +1,14 @@
1
1
  // Rank only the heads that have already passed the caller's scope and validity checks.
2
2
  import { normalizeLabel } from "./personal.js";
3
+ import { encoderId, queryLanguages } from "./encoder.js";
3
4
  import { document, language, newSearchTrace, VectorIndex } from "./vector-index.js";
4
5
  export { newSearchTrace } from "./vector-index.js";
5
- // Both bundled encoders are monolingual. Rank each wording in its own language
6
- // and only combine scores belonging to the same eligible revision.
6
+ // Rank each distinct wording in its own language and retain the strongest
7
+ // match per revision. This also admits paraphrases in a single language.
7
8
  function queryVariants(query, options) {
8
9
  const primary = normalizeLabel(query || options.topic || '');
9
10
  const alternate = normalizeLabel(options.alternateQuery ?? '');
10
- return primary && alternate && language(primary) !== language(alternate) ? [primary, alternate] : [primary];
11
+ return primary && alternate && primary !== alternate ? [primary, alternate] : [primary];
11
12
  }
12
13
  export function matchingTopics(rows, options) {
13
14
  const subject = normalizeLabel(options.subject ?? '');
@@ -40,6 +41,15 @@ export class Retrieval {
40
41
  }
41
42
  return [...hits.values()];
42
43
  }
44
+ // A foreground save only consumes matched candidates, not corpus coverage statistics.
45
+ // A revision with neither a lexical hit nor any passage of a requested model cannot
46
+ // score. Include every indexed passage, even when it shares no words with the proposal.
47
+ reviewRefs(domains, query, options, lexical) {
48
+ const langs = new Set(queryVariants(query, options).flatMap(queryLanguages));
49
+ const models = this.vectors.languages.filter(lang => langs.has(lang)).flatMap(lang => Array.from({ length: 8 }, (_, i) => encoderId(lang) + '/passage-' + i));
50
+ const refs = domains.flatMap(domain => this.store.vectorRefs(domain, models));
51
+ return [...new Map([...refs, ...lexical].map(row => [JSON.stringify([row.domain, row.id, row.rev]), row])).values()];
52
+ }
43
53
  async search(rows, query, mode, options = {}, trace = newSearchTrace(), keywordHits) {
44
54
  const q = normalizeLabel(query);
45
55
  const subject = normalizeLabel(options.subject ?? '');
@@ -70,16 +80,23 @@ export class Retrieval {
70
80
  trace.sqliteMs += performance.now() - started;
71
81
  const semantic = new Map();
72
82
  if (mode !== 'keyword') {
73
- const docs = rows.map(row => ({ ...row, text: document(row.rule) }));
83
+ const languages = this.vectors.languages;
84
+ const docs = languages.length ? rows.map(row => ({ ...row, text: document(row.rule) })) : [];
74
85
  const coverage = new Set();
75
- for (const wording of queryVariants(q, options)) {
76
- const lang = language(wording);
86
+ const queries = queryVariants(q, options).flatMap(wording => queryLanguages(wording).map(lang => ({ wording, lang })));
87
+ if (!queries.length)
88
+ coverage.add('unavailable');
89
+ for (const { wording, lang } of queries) {
90
+ if (!languages.includes(lang)) {
91
+ coverage.add('unavailable');
92
+ continue;
93
+ }
77
94
  if (!docs.some(doc => language(doc.text) === lang))
78
95
  continue;
79
96
  try {
80
- const scores = await this.vectors.scores(wording, docs, trace);
97
+ const scores = await this.vectors.scores(wording, docs, trace, lang);
81
98
  for (const [id, score] of scores)
82
- semantic.set(id, score);
99
+ semantic.set(id, Math.max(score, semantic.get(id) ?? -Infinity));
83
100
  coverage.add(trace.coverage);
84
101
  }
85
102
  catch {
@@ -0,0 +1,49 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { skipsAutomaticMemory } from "./automatic.js";
3
+ import { isPersonalSlot } from "./personal.js";
4
+ import { StoreError } from "./store.js";
5
+ function isAgreement(rule) {
6
+ return Boolean(rule.semanticTopic) && (rule.kind === 'rule' || rule.kind === 'preference');
7
+ }
8
+ /** Bind a follow-up such as "I meant this project" to the actual agreement from
9
+ * the preceding turn. An assistant-supplied ID alone cannot authorize moving it. */
10
+ export function previousScopeAgreement(memory, agent, project, ref, generation, turn) {
11
+ const old = memory.current(memory.personal, ref.id);
12
+ if (!old || old.source.sessionId !== agent.id || old.source.storeId !== memory.storeId(agent.session))
13
+ throw new StoreError('target_not_found');
14
+ if (old.rev !== ref.rev)
15
+ throw new StoreError('stale_revision');
16
+ if (!isPersonalSlot(old.slot) || !isAgreement(old) ||
17
+ old.channel !== 'automatic' || old.pinned || old.usageOverride || old.sensitive || old.localException ||
18
+ old.quoteType !== 'user_quote' || !old.evidence ||
19
+ skipsAutomaticMemory([old.action, old.user_quote, old.when, old.exceptions, old.semanticTopic,
20
+ old.subject, ...(old.keywords ?? [])].join('\n')))
21
+ throw new StoreError('protected_revision');
22
+ const starts = agent.session.snapshotEvents().slice(agent.session.inheritedEventCount)
23
+ .filter(event => event.type === 'turn/start').slice(-2);
24
+ if (starts.length !== 2 || String(starts[1].data.turn) !== turn || String(starts[0].data.turn) !== old.source.turnId)
25
+ throw new StoreError('invalid_source');
26
+ const prior = memory.proposalSources(agent, agent, project, old.source.turnId, generation);
27
+ const span = old.evidence;
28
+ const block = prior.events.find(event => {
29
+ const start = span.start - (event.offset ?? 0);
30
+ return event.seq === old.source.seq && event.seq === span.seq && start >= 0 &&
31
+ event.text.slice(start, start + span.end - span.start) === old.user_quote &&
32
+ (!old.source.formSelection || event.formSelections?.some(option => isDeepStrictEqual(option, old.source.formSelection)));
33
+ });
34
+ if (prior.reason || !block)
35
+ throw new StoreError(prior.reason ?? 'invalid_source');
36
+ if (!memory.store.soleTurnAgreement([project.id, memory.personal.id], old.source, ref))
37
+ throw new StoreError('ambiguous_topic');
38
+ return old;
39
+ }
40
+ /** Project the saved agreement. The second proposal supplies only a clarification,
41
+ * never a new body, a new subject, or model-invented path restrictions. */
42
+ export function projectAgreement(old) {
43
+ return {
44
+ scope: 'project', kind: old.kind, topic: old.semanticTopic,
45
+ action: old.action, user_quote: old.user_quote, subject: old.subject, when: old.when,
46
+ exceptions: old.exceptions, paths: old.paths, keywords: old.keywords ?? [],
47
+ usage: old.usage ?? 'on_demand', sensitive: false, conflicts_with_repo_guidance: false,
48
+ };
49
+ }
@@ -1,4 +1,4 @@
1
- import { encoderId } from "./encoder.js";
1
+ import { encoderId, language } from "./encoder.js";
2
2
  import { isKnowledge } from "./knowledge.js";
3
3
  import { normalizeLabel } from "./personal.js";
4
4
  import { searchWords } from "./search-words.js";
@@ -13,12 +13,27 @@ export function document(rule) {
13
13
  // The second column indexes codepoint positions and supports literal substring phrases of any length.
14
14
  export const indexWords = (text) => searchWords(text).map(word => Buffer.from(word).toString('hex'));
15
15
  const characters = (text) => Array.from(text, char => char.codePointAt(0).toString(16)).join(' ');
16
- // Each FTS row and vector job uses the stable primary key of its source revision.
17
- export function indexRevision(db, rid, rule) {
18
- const text = normalizeLabel(document(rule));
19
- db.prepare('INSERT INTO memory_fts(rowid,words,chars) VALUES(?,?,?)')
20
- .run(rid, indexWords(text).join(' '), characters(text));
21
- db.prepare('INSERT INTO memory_vector_jobs(rid) VALUES(?)').run(rid);
16
+ function indexLabels(db, domain, rid, rule) {
17
+ const canonical = normalizeLabel(rule.semanticTopic ?? '');
18
+ const aliases = new Set([canonical, ...(rule.keywords ?? []).map(normalizeLabel)]);
19
+ aliases.delete('');
20
+ if (!aliases.size)
21
+ return;
22
+ const subject = normalizeLabel(rule.subject ?? '');
23
+ const insert = db.prepare('INSERT INTO memory_topic_labels(domain,label,subject,rid,canonical) VALUES(?,?,?,?,?)');
24
+ for (const label of aliases)
25
+ insert.run(domain, label, subject, rid, Number(label === canonical));
26
+ }
27
+ // Each derived row belongs to the stable primary key of its source revision.
28
+ export function indexRevision(db, domain, rid, rule) {
29
+ indexLabels(db, domain, rid, rule);
30
+ const content = document(rule);
31
+ const text = normalizeLabel(content);
32
+ const labels = rule.sensitive || rule.usage !== 'on_demand' ? '' :
33
+ normalizeLabel([rule.semanticTopic, ...(rule.keywords ?? [])].filter(Boolean).join(' '));
34
+ db.prepare('INSERT INTO memory_fts(rowid,words,chars,labels) VALUES(?,?,?,?)')
35
+ .run(rid, indexWords(text).join(' '), characters(text), indexWords(labels).join(' '));
36
+ db.prepare('INSERT INTO memory_vector_jobs(rid,language) VALUES(?,?)').run(rid, language(content));
22
37
  }
23
38
  export function promptRole(rule) {
24
39
  return isKnowledge(rule) ? null : Number(rule.usage === 'proactive' && !rule.sensitive);
@@ -33,10 +48,11 @@ export class SearchIndex {
33
48
  CREATE INDEX revision_current_slot ON revisions(domain,slot)
34
49
  WHERE state='confirmed' AND slot IS NOT NULL;
35
50
  CREATE INDEX revision_prompt_role ON revisions(domain,proactive) WHERE state='confirmed';
36
- CREATE VIRTUAL TABLE memory_fts USING fts5(words,chars,content='',contentless_delete=1);
51
+ CREATE VIRTUAL TABLE memory_fts USING fts5(words,chars,labels,content='',contentless_delete=1);
37
52
  INSERT INTO memory_fts(memory_fts,rank) VALUES('secure-delete',1);
38
- CREATE TABLE memory_vector_jobs (rid INTEGER PRIMARY KEY, available INTEGER NOT NULL DEFAULT 0);
53
+ CREATE TABLE memory_vector_jobs (rid INTEGER PRIMARY KEY, available INTEGER NOT NULL DEFAULT 0, language TEXT NOT NULL);
39
54
  CREATE INDEX memory_vector_ready ON memory_vector_jobs(available,rid);
55
+ CREATE INDEX memory_vector_language_ready ON memory_vector_jobs(language,available,rid);
40
56
  CREATE TABLE memory_vector_format (version TEXT PRIMARY KEY);
41
57
  CREATE TRIGGER remove_retired_search AFTER UPDATE OF state ON revisions WHEN OLD.state='confirmed' AND NEW.state<>'confirmed' BEGIN
42
58
  DELETE FROM memory_fts WHERE rowid=NEW.rid;
@@ -44,13 +60,77 @@ export class SearchIndex {
44
60
  END;
45
61
  `);
46
62
  }
63
+ ensureTopicLabels() {
64
+ if (this.db.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name='memory_topic_labels'").get()) {
65
+ const pending = this.db.prepare(`SELECT r.rid,r.domain,r.payload FROM memory_unindexed_topics u
66
+ CROSS JOIN revisions r ON u.rid=r.rid AND r.state='confirmed'`);
67
+ for (const row of pending.iterate())
68
+ indexLabels(this.db, String(row.domain), Number(row.rid), JSON.parse(String(row.payload)));
69
+ this.db.exec('DELETE FROM memory_unindexed_topics');
70
+ return;
71
+ }
72
+ // Backfill once, under the same write transaction as initialization. Retired revisions
73
+ // never contribute aliases and consent cleanup removes their derived labels atomically.
74
+ // An older CLI sharing the same database can write FTS without knowing this index.
75
+ // The heads trigger marks just those revisions. New writers have already indexed
76
+ // their labels before they publish a head. A reader includes pending rows immediately.
77
+ const queueUnindexed = `INSERT OR IGNORE INTO memory_unindexed_topics(domain,rid)
78
+ SELECT r.domain,r.rid FROM revisions r WHERE r.domain=NEW.domain AND r.id=NEW.id AND r.rev=NEW.rev AND r.state='confirmed'
79
+ AND (json_type(r.payload,'$.semanticTopic')='text' OR json_array_length(r.payload,'$.keywords')>0)
80
+ AND NOT EXISTS(SELECT 1 FROM memory_topic_labels l WHERE l.rid=r.rid);`;
81
+ this.db.exec(`CREATE TABLE memory_topic_labels (
82
+ domain TEXT NOT NULL, label TEXT NOT NULL, subject TEXT NOT NULL, rid INTEGER NOT NULL,
83
+ canonical INTEGER NOT NULL, PRIMARY KEY(domain,label,subject,rid)
84
+ ) WITHOUT ROWID;
85
+ CREATE INDEX memory_topic_revision ON memory_topic_labels(rid);
86
+ CREATE TABLE memory_unindexed_topics(domain TEXT NOT NULL,rid INTEGER NOT NULL,PRIMARY KEY(domain,rid)) WITHOUT ROWID;
87
+ CREATE TRIGGER queue_legacy_topic_insert AFTER INSERT ON heads BEGIN ${queueUnindexed} END;
88
+ CREATE TRIGGER queue_legacy_topic_update AFTER UPDATE OF rev ON heads BEGIN ${queueUnindexed} END;
89
+ CREATE INDEX memory_scope_vector_models ON memory_vectors(domain,model,id,rev);
90
+ CREATE TRIGGER retire_topic_labels AFTER UPDATE OF state ON revisions
91
+ WHEN OLD.state='confirmed' AND NEW.state<>'confirmed'
92
+ BEGIN DELETE FROM memory_topic_labels WHERE rid=OLD.rid;
93
+ DELETE FROM memory_unindexed_topics WHERE domain=OLD.domain AND rid=OLD.rid; END;`);
94
+ const heads = this.db.prepare(`SELECT r.domain,r.rid,r.payload FROM heads h
95
+ CROSS JOIN revisions r USING(domain,id,rev) WHERE r.state='confirmed'`);
96
+ for (const row of heads.iterate())
97
+ indexLabels(this.db, String(row.domain), Number(row.rid), JSON.parse(String(row.payload)));
98
+ }
99
+ topicRefs(domain, topic, subject, canonicalScope) {
100
+ const hasSubject = canonicalScope !== undefined || subject !== undefined;
101
+ const slot = canonicalScope === 'global' ? " AND r.slot GLOB 'profile.topic.*'" :
102
+ canonicalScope === 'project' ? " AND r.slot GLOB 'project.topic.*'" : '';
103
+ const normalized = normalizeLabel(topic);
104
+ const owner = normalizeLabel(subject ?? '');
105
+ const rows = this.db.prepare(`SELECT r.id,r.rev,r.confirmed,NULL AS pending FROM memory_topic_labels l
106
+ CROSS JOIN revisions r ON r.rid=l.rid CROSS JOIN heads h ON h.domain=r.domain AND h.id=r.id AND h.rev=r.rev
107
+ WHERE l.domain=? AND l.label=? ${hasSubject ? 'AND l.subject=?' : ''}${canonicalScope ? ' AND l.canonical=1' : ''}${slot}
108
+ AND r.state='confirmed'
109
+ UNION ALL SELECT r.id,r.rev,r.confirmed,r.payload AS pending FROM memory_unindexed_topics u
110
+ CROSS JOIN revisions r ON r.rid=u.rid CROSS JOIN heads h ON h.domain=r.domain AND h.id=r.id AND h.rev=r.rev
111
+ WHERE u.domain=? AND r.state='confirmed'${slot} ORDER BY 3 DESC,1`)
112
+ .all(domain, normalized, ...(hasSubject ? [owner] : []), domain);
113
+ return rows.flatMap(row => {
114
+ if (row.pending) {
115
+ const rule = JSON.parse(String(row.pending));
116
+ if (hasSubject && normalizeLabel(rule.subject ?? '') !== owner)
117
+ return [];
118
+ const labels = canonicalScope ? [rule.semanticTopic] : [rule.semanticTopic, ...(rule.keywords ?? [])];
119
+ if (!labels.some(label => label && normalizeLabel(label) === normalized))
120
+ return [];
121
+ }
122
+ return [{ domain, id: String(row.id), rev: Number(row.rev) }];
123
+ });
124
+ }
47
125
  syncVectorFormat() {
48
126
  // Changing the encoder or passage layout requeues current revisions, including completed jobs.
49
127
  const version = [encoderId('en'), encoderId('zh'), 'passages-v1'].join('|');
50
128
  if (!this.db.prepare('SELECT 1 FROM memory_vector_format WHERE version=?').get(version)) {
51
- this.db.exec(`DELETE FROM memory_vector_format;
52
- INSERT OR IGNORE INTO memory_vector_jobs(rid)
53
- SELECT r.rid FROM heads h CROSS JOIN revisions r USING(domain,id,rev) WHERE r.state='confirmed'`);
129
+ this.db.exec('DELETE FROM memory_vector_format');
130
+ const heads = this.db.prepare("SELECT r.rid,r.payload FROM heads h JOIN revisions r USING(domain,id,rev) WHERE r.state='confirmed'");
131
+ const enqueue = this.db.prepare('INSERT OR IGNORE INTO memory_vector_jobs(rid,language) VALUES(?,?)');
132
+ for (const row of heads.iterate())
133
+ enqueue.run(row.rid, language(document(JSON.parse(String(row.payload)))));
54
134
  this.db.prepare('INSERT INTO memory_vector_format VALUES(?)').run(version);
55
135
  }
56
136
  }
@@ -76,7 +156,7 @@ export class SearchIndex {
76
156
  }
77
157
  };
78
158
  if (terms.length)
79
- collect('words:(' + terms.join(' OR ') + ')', '-bm25(memory_fts,1,0)');
159
+ collect('words:(' + terms.join(' OR ') + ')', '-bm25(memory_fts,1,0,0)');
80
160
  if (q)
81
161
  collect('chars:"' + characters(q) + '"', '3');
82
162
  return [...hits.values()];