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,43 +1,39 @@
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(' ')
1
+ import { prompts, type PromptLanguage } from './prompt-copy.ts'
9
2
 
10
- export const proposeTool = {
11
- description: memoryInstructions + ' 遇到 unsupported_correction,可以从引文中逐字提取明确的新值重试一次。仍无法核对时保留原记录。保存状态由聊天回执展示。日常对话直接回应用户的话。用户询问记忆状态或明确要求保存时,按 results 的输入序号逐项回答,只有 saved 或 duplicate 表示该项已记住;partial 表示本批仅部分成功。',
12
- parameters: {
13
- type: 'object', additionalProperties: false, required: ['items'],
14
- properties: {
15
- items: {
16
- type: 'array', minItems: 1, maxItems: 32,
3
+ export function proposalContract(language: PromptLanguage) {
4
+ const copy = prompts[language]
5
+ return {
6
+ description: copy.write + ' ' + copy.propose,
7
+ parameters: {
8
+ type: 'object', additionalProperties: false, required: ['items'],
9
+ properties: {
17
10
  items: {
18
- type: 'object', additionalProperties: false, required: ['scope', 'kind', 'topic', 'user_quote', 'action'],
19
- properties: {
20
- user_quote: { type: 'string', minLength: 1, maxLength: 480, description: '逐字引用本轮用户原话并保留限定语。对于 ask_user_question,仅引用用户手填的回答。题干帮助理解回答,预设选项不能充当引文。' },
21
- action: { type: 'string', minLength: 1, maxLength: 480, description: '原话陈述的现行事实、偏好或长期指令。更正时仅保留新值,旧值和变更说明属于版本历史。' },
22
- scope: { type: 'string', enum: ['global', 'project'] },
23
- kind: { type: 'string', enum: ['fact', 'preference', 'rule'] },
24
- topic: { type: 'string', minLength: 1, maxLength: 80, description: '简短稳定的主题名。相同主题沿用已有名称。' },
25
- subject: { type: 'string', minLength: 1, maxLength: 80, description: '这条记忆属于谁或什么对象。同一主体沿用一致名称。' },
26
- usage: { type: 'string', enum: ['proactive', 'on_demand'] },
27
- keywords: { type: 'array', maxItems: 8, items: { type: 'string', minLength: 1, maxLength: 40 }, description: '简短检索别称。' },
28
- sensitive: { type: 'boolean', description: '需保护的内容标记为 true,仅按需使用。' },
29
- correction: { type: 'boolean', description: '原话明确将先前的事实或长期约定改为新值时为 true。' },
30
- replaces: {
31
- type: 'object', additionalProperties: false, required: ['id', 'rev'],
32
- properties: { id: { type: 'string' }, rev: { type: 'integer', minimum: 1 } },
11
+ type: 'array', minItems: 1, maxItems: 32,
12
+ items: {
13
+ type: 'object', additionalProperties: false, required: ['scope', 'action'],
14
+ anyOf: [{ required: ['replaces'] }, { required: ['kind', 'topic'] }],
15
+ properties: {
16
+ user_quote: { type: 'string', minLength: 1, maxLength: 480, description: copy.user_quote },
17
+ action: { type: 'string', minLength: 1, maxLength: 480, description: copy.action },
18
+ scope: { type: 'string', enum: ['global', 'project'], description: copy.scope },
19
+ kind: { type: 'string', enum: ['fact', 'preference', 'rule'] },
20
+ topic: { type: 'string', minLength: 1, maxLength: 80, description: copy.topic },
21
+ subject: { type: 'string', minLength: 1, maxLength: 80, description: copy.subject },
22
+ usage: { type: 'string', enum: ['proactive', 'on_demand'], description: copy.usage },
23
+ keywords: { type: 'array', maxItems: 8, items: { type: 'string', minLength: 1, maxLength: 40 }, description: copy.keywords },
24
+ sensitive: { type: 'boolean', description: copy.sensitive },
25
+ replaces: {
26
+ type: 'object', additionalProperties: false, required: ['id', 'rev'],
27
+ description: copy.replaces,
28
+ properties: { id: { type: 'string' }, rev: { type: 'integer', minimum: 1 } },
29
+ },
30
+ when: { type: 'string', maxLength: 480, description: copy.when },
31
+ exceptions: { type: 'string', maxLength: 480, description: copy.exceptions },
32
+ paths: { type: 'array', maxItems: 64, items: { type: 'string', maxLength: 1024 }, description: copy.paths },
33
33
  },
34
- when: { type: 'string', maxLength: 480, description: '原话中的适用条件。' },
35
- exceptions: { type: 'string', maxLength: 480, description: '原话中的例外。' },
36
- paths: { type: 'array', maxItems: 64, items: { type: 'string', maxLength: 1024 }, description: '原话中的项目相对路径。' },
37
- conflicts_with_repo_guidance: { type: 'boolean' },
38
34
  },
39
35
  },
40
36
  },
41
37
  },
42
- },
38
+ }
43
39
  }
@@ -9,103 +9,173 @@ interface QuestionAnswer {
9
9
  userSeq: number
10
10
  }
11
11
 
12
+ export interface SubmittedOption {
13
+ userSeq: number
14
+ callSeq: number
15
+ resultSeq: number
16
+ questionId: string
17
+ question: string
18
+ label: string
19
+ }
20
+ export interface SelectionEvidence { option: SubmittedOption; directive: string }
21
+
22
+ /** Keep the user's directive and the submitted format intact. Strip only the
23
+ * recommendation marker that DSH forms display as part of an option label. */
24
+ export function selectedAction(directive: string, label: string) {
25
+ return directive + '\n' + label.replace(/\s*(?:\((?:recommended|推荐)\)|((?:recommended|推荐)))\s*$/iu, '').trim()
26
+ }
27
+
28
+ interface QuestionForm { custom: QuestionAnswer[]; selected: SubmittedOption[]; refusedBy?: number }
29
+
30
+ // A submitted choice can supply the implementation of a standing request. The
31
+ // user must express its continuing applicability in their own cited words.
32
+ export function standingRequest(text: string) {
33
+ return /以后|今后|往后|后续|每次|每当|一律|始终|总是|长期|默认|记住|记下|之[后後]都|\b(?:always|each|every|whenever|henceforth|remember|by default|from now on|in future|in the future|going forward)\b/iu.test(text)
34
+ }
35
+
36
+ const sentences = new Intl.Segmenter(undefined, { granularity: 'sentence' })
37
+
38
+ /** Include submitted formats only for claims in a standing-request sentence.
39
+ * A cropped quote must not turn that same instruction back into a bare rule. */
40
+ export function choicesForQuote(text: string, quote: string, choices?: SubmittedOption[]) {
41
+ if (!choices?.length) return
42
+ const start = text.indexOf(quote)
43
+ if (start < 0) return
44
+ const end = start + quote.length
45
+ for (const sentence of sentences.segment(text)) {
46
+ if (sentence.index < end && sentence.index + sentence.segment.length > start && standingRequest(sentence.segment))
47
+ return choices
48
+ }
49
+ }
50
+
51
+ /** Both reviewers use the same reference into the native form. Unrelated
52
+ * options require an explicit null decision before saving a standing rule. */
53
+ export function resolveSelectedDirective(action: string, index: unknown, choices: SubmittedOption[] | undefined,
54
+ canSelect: boolean): {action: string; selection?: SelectionEvidence} | undefined {
55
+ if (index == null) {
56
+ if (choices?.length && canSelect && index !== null) return
57
+ return { action }
58
+ }
59
+ if (!canSelect || !Number.isSafeInteger(index) || !standingRequest(action)) return
60
+ const option = choices?.[Number(index)]
61
+ if (!option) return
62
+ const combined = selectedAction(action, option.label)
63
+ if (combined.length > 480) return
64
+ return { action: combined, selection: { directive: action, option } }
65
+ }
66
+
12
67
  const record = (value: unknown): value is Record<string, unknown> =>
13
68
  typeof value === 'object' && value !== null && !Array.isArray(value)
14
69
 
15
70
  function eligiblePrompt(text: string) {
16
71
  // Unlabelled answers like "123456" cannot identify an OTP by themselves.
17
- return !skipsAutomaticMemory(text) && !/\b(?:otp|pin|one[- ]time (?:code|password)|token)\b|令牌/iu.test(text)
72
+ return !skipsAutomaticMemory(text) && !/\b(?:otp|pin|one[- ]time (?:code|password)|token)\b|令牌|密码/iu.test(text)
18
73
  }
19
74
 
20
- /** Read the submitted free-text fields. DSH can preselect model-suggested labels. */
21
- function customAnswers(args: unknown, result: unknown, userSeq: number): QuestionAnswer[] {
75
+ /** Keep user-typed text and submitted option labels distinct. */
76
+ function submittedForm(args: unknown, result: unknown, userSeq: number, callSeq: number, resultSeq: number): QuestionForm | undefined {
22
77
  if (!record(args) || !Array.isArray(args.questions) || !record(result) ||
23
78
  Object.keys(result).some(key => key !== 'answers') || !Array.isArray(result.answers) ||
24
- !args.questions.length || result.answers.length !== args.questions.length) return []
25
- const questions = new Map<string, { text: string; eligible: boolean }>()
79
+ !args.questions.length || result.answers.length !== args.questions.length) return undefined
80
+ const questions = new Map<string, { text: string; eligible: boolean; options: unknown }>()
26
81
  for (const field of args.questions) {
27
82
  if (!record(field) || typeof field.id !== 'string' || !field.id.trim() || questions.has(field.id) ||
28
83
  typeof field.question !== 'string' || !field.question.trim() ||
29
- (field.header !== undefined && typeof field.header !== 'string')) return []
84
+ (field.header !== undefined && typeof field.header !== 'string')) return undefined
30
85
  const fieldName = field.id.replace(/([a-z])([A-Z])/gu, '$1 $2').replace(/[_-]/gu, ' ')
31
86
  questions.set(field.id, {
32
- text: field.question,
87
+ text: field.question, options: field.options,
33
88
  eligible: field.question.length <= 1024 && eligiblePrompt([fieldName, field.header, field.question].join(' ')),
34
89
  })
35
90
  }
36
91
  let offset = 0
37
92
  const answers: QuestionAnswer[] = []
93
+ const selected: SubmittedOption[] = []
94
+ let refusedBy: number | undefined
38
95
  for (const [block, answer] of result.answers.entries()) {
39
96
  if (!record(answer) || typeof answer.id !== 'string' || !Array.isArray(answer.selected) ||
40
97
  !answer.selected.every(label => typeof label === 'string') ||
41
98
  (answer.custom !== undefined && typeof answer.custom !== 'string') ||
42
- Object.keys(answer).some(key => !['id', 'selected', 'custom'].includes(key))) return []
99
+ Object.keys(answer).some(key => !['id', 'selected', 'custom'].includes(key))) return undefined
43
100
  const question = questions.get(answer.id)
44
- if (!question) return []
101
+ if (!question) return undefined
45
102
  questions.delete(answer.id)
46
- if (typeof answer.custom !== 'string' || !answer.custom.trim()) continue
103
+ if (typeof answer.custom !== 'string' || !answer.custom.trim()) {
104
+ const label = answer.selected.length === 1 ? answer.selected[0] : undefined
105
+ if (typeof label === 'string' && label.trim() && label.length <= 480 && Array.isArray(question.options) &&
106
+ question.options.filter(option => record(option) && option.label === label).length === 1) {
107
+ if (refusesAutomaticMemory(label)) refusedBy = userSeq
108
+ else if (question.eligible && !skipsAutomaticMemory(label))
109
+ selected.push({ userSeq, callSeq, resultSeq, questionId: answer.id, question: question.text, label })
110
+ }
111
+ continue
112
+ }
47
113
  // Offsets refer to the decoded custom answers joined by newlines, so escaped
48
114
  // characters and surrogate pairs have the same UTF-16 positions during rechecking.
49
115
  if (question.eligible || refusesAutomaticMemory(answer.custom))
50
116
  answers.push({ question: question.text, text: answer.custom, block, offset, userSeq })
51
117
  offset += answer.custom.length + 1
52
118
  }
53
- return answers
119
+ return { custom: answers, selected, refusedBy }
120
+ }
121
+
122
+ /** Only a native submitted result can supply a custom answer or an option selection. */
123
+ export function questionForm(session: Session, published: HostEvent) {
124
+ if (session.header.origin === 'subagent') return
125
+ return verifiedQuestionForm(session.snapshotEvents(), session.inheritedEventCount, published)
54
126
  }
55
127
 
56
- /** Original, in-time results of the native ask_user_question tool. */
57
128
  export function questionAnswers(session: Session, published: HostEvent): QuestionAnswer[] {
58
- if (session.header.origin === 'subagent') return []
59
- return verifiedQuestionAnswers(session.snapshotEvents(), session.inheritedEventCount, published)
129
+ return questionForm(session, published)?.custom ?? []
60
130
  }
61
131
 
62
- /** Accepts either a full session snapshot or a contiguous slice of its original event sequence. */
63
- export function verifiedQuestionAnswers(events: readonly HostEvent[], cut: number, published: HostEvent): QuestionAnswer[] {
64
- if (published.type !== 'tool/result') return []
132
+ /** Accepts a full session snapshot or a contiguous slice of its original event sequence. */
133
+ export function verifiedQuestionForm(events: readonly HostEvent[], cut: number, published: HostEvent): QuestionForm | undefined {
134
+ if (published.type !== 'tool/result') return undefined
65
135
  const offset = events[0]?.seq ?? 0
66
136
  const at = (seq: number) => events[seq - offset]
67
137
  const event = at(published.seq)
68
138
  if (event?.type !== 'tool/result' || event.surfaceOp !== 'append' ||
69
- event.sourceEventSeqs?.length !== 1 || event.data.error !== undefined) return []
139
+ event.sourceEventSeqs?.length !== 1 || event.data.error !== undefined) return undefined
70
140
  const { message, step, turn } = event.data
71
141
  const callId = message?.toolCallId
72
142
  if (!callId || message.role !== 'tool' || message.isError || message.source?.kind !== 'tool' ||
73
- message.source.callId !== callId || !Number.isSafeInteger(step) || !Number.isSafeInteger(turn)) return []
143
+ message.source.callId !== callId || !Number.isSafeInteger(step) || !Number.isSafeInteger(turn)) return undefined
74
144
  const [callSeq] = event.sourceEventSeqs
75
145
  const call = at(callSeq)
76
146
  if (callSeq < cut || callSeq >= event.seq || call?.seq !== callSeq ||
77
147
  call.type !== 'tool/call' || call.data.name !== 'ask_user_question' || call.data.callId !== callId ||
78
- call.data.turn !== turn || call.data.step !== step) return []
148
+ call.data.turn !== turn || call.data.step !== step) return undefined
79
149
 
80
150
  // Replay only the local turn. A call or an opening user prompt inherited at
81
151
  // a fork, or a change of project between prompt, question and answer, breaks attribution.
82
152
  let start = callSeq
83
153
  while (start >= cut && at(start).type !== 'turn/start') start--
84
- if (start < cut || at(start).data.turn !== turn) return []
154
+ if (start < cut || at(start).data.turn !== turn) return undefined
85
155
  let userSeq: number | undefined
86
156
  let calls = 0, results = 0
87
157
  for (let index = start + 1; index < offset + events.length; index++) {
88
158
  const e = at(index)
89
159
  if (e.type === 'turn/start' || e.type === 'turn/end') {
90
- if (e.seq < event.seq) return []
160
+ if (e.seq < event.seq) return undefined
91
161
  break
92
162
  }
93
- if (e.seq <= event.seq && e.type === 'working-directory/change' && userSeq !== undefined) return []
94
- if (e.seq > callSeq && e.seq < event.seq && (e.type === 'step/start' || e.type === 'step/end')) return []
163
+ if (e.seq <= event.seq && e.type === 'working-directory/change' && userSeq !== undefined) return undefined
164
+ if (e.seq > callSeq && e.seq < event.seq && (e.type === 'step/start' || e.type === 'step/end')) return undefined
95
165
  if (e.seq < event.seq && e.type === 'user/message' && e.data.source?.kind === 'user') {
96
- if ((e.surfaceOp && e.surfaceOp !== 'append') || !eligiblePrompt(messageText(e.data))) return []
166
+ if ((e.surfaceOp && e.surfaceOp !== 'append') || !eligiblePrompt(messageText(e.data))) return undefined
97
167
  if (e.seq < callSeq) userSeq = e.seq
98
168
  }
99
169
  if (e.data.turn !== turn || e.data.step !== step) continue
100
170
  if (e.type === 'tool/call' && e.data.callId === callId) calls++
101
171
  if (e.type === 'tool/result' && e.surfaceOp === 'append' && e.data.message?.toolCallId === callId) results++
102
172
  }
103
- if (userSeq === undefined || calls !== 1 || results !== 1 || message.content?.length !== 1) return []
173
+ if (userSeq === undefined || calls !== 1 || results !== 1 || message.content?.length !== 1) return undefined
104
174
  const [part] = message.content
105
- if (part.type !== 'text' || typeof part.text !== 'string' || typeof call.data.arguments !== 'string') return []
175
+ if (part.type !== 'text' || typeof part.text !== 'string' || typeof call.data.arguments !== 'string') return undefined
106
176
  try {
107
- return customAnswers(JSON.parse(call.data.arguments), JSON.parse(part.text), userSeq)
177
+ return submittedForm(JSON.parse(call.data.arguments), JSON.parse(part.text), userSeq, callSeq, event.seq)
108
178
  } catch {
109
- return []
179
+ return undefined
110
180
  }
111
181
  }
package/src/retrieval.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // Rank only the heads that have already passed the caller's scope and validity checks.
2
2
  import { normalizeLabel } from './personal.ts'
3
3
  import type { KeywordHit } from './search-index.ts'
4
- import type { Encoder } from './encoder.ts'
4
+ import { encoderId, queryLanguages, type Encoder } from './encoder.ts'
5
5
  import type { MemoryStore, Rule } from './store.ts'
6
6
  import { document, language, newSearchTrace, VectorIndex, type SearchRow, type SearchTrace } from './vector-index.ts'
7
7
  export { newSearchTrace, type SearchTrace } from './vector-index.ts'
@@ -9,12 +9,12 @@ export { newSearchTrace, type SearchTrace } from './vector-index.ts'
9
9
  export type SearchMode = 'hybrid' | 'keyword' | 'semantic'
10
10
  export interface SearchOptions { subject?: string; topic?: string; scope?: 'project' | 'profile'; alternateQuery?: string }
11
11
 
12
- // Both bundled encoders are monolingual. Rank each wording in its own language
13
- // and only combine scores belonging to the same eligible revision.
12
+ // Rank each distinct wording in its own language and retain the strongest
13
+ // match per revision. This also admits paraphrases in a single language.
14
14
  function queryVariants(query: string, options: SearchOptions) {
15
15
  const primary = normalizeLabel(query || options.topic || '')
16
16
  const alternate = normalizeLabel(options.alternateQuery ?? '')
17
- return primary && alternate && language(primary) !== language(alternate) ? [primary, alternate] : [primary]
17
+ return primary && alternate && primary !== alternate ? [primary, alternate] : [primary]
18
18
  }
19
19
  export function matchingTopics(rows: SearchRow[], options: SearchOptions) {
20
20
  const subject = normalizeLabel(options.subject ?? '')
@@ -48,6 +48,17 @@ export class Retrieval {
48
48
  return [...hits.values()]
49
49
  }
50
50
 
51
+ // A foreground save only consumes matched candidates, not corpus coverage statistics.
52
+ // A revision with neither a lexical hit nor any passage of a requested model cannot
53
+ // score. Include every indexed passage, even when it shares no words with the proposal.
54
+ reviewRefs(domains: string[], query: string, options: SearchOptions, lexical: KeywordHit[]) {
55
+ const langs = new Set(queryVariants(query, options).flatMap(queryLanguages))
56
+ const models = this.vectors.languages.filter(lang => langs.has(lang)).flatMap(lang =>
57
+ Array.from({length: 8}, (_, i) => encoderId(lang) + '/passage-' + i))
58
+ const refs = domains.flatMap(domain => this.store.vectorRefs(domain, models))
59
+ return [...new Map([...refs, ...lexical].map(row => [JSON.stringify([row.domain,row.id,row.rev]), row])).values()]
60
+ }
61
+
51
62
  async search(
52
63
  rows: SearchRow[], query: string, mode?: SearchMode,
53
64
  options: SearchOptions = {}, trace: SearchTrace = newSearchTrace(), keywordHits?: KeywordHit[],
@@ -81,14 +92,20 @@ export class Retrieval {
81
92
  trace.sqliteMs += performance.now() - started
82
93
  const semantic = new Map<string, number>()
83
94
  if (mode !== 'keyword') {
84
- const docs = rows.map(row => ({ ...row, text: document(row.rule) }))
95
+ const languages = this.vectors.languages
96
+ const docs = languages.length ? rows.map(row => ({ ...row, text: document(row.rule) })) : []
85
97
  const coverage = new Set<SearchTrace['coverage']>()
86
- for (const wording of queryVariants(q, options)) {
87
- const lang = language(wording)
98
+ const queries = queryVariants(q, options).flatMap(wording => queryLanguages(wording).map(lang => ({ wording, lang })))
99
+ if (!queries.length) coverage.add('unavailable')
100
+ for (const { wording, lang } of queries) {
101
+ if (!languages.includes(lang)) {
102
+ coverage.add('unavailable')
103
+ continue
104
+ }
88
105
  if (!docs.some(doc => language(doc.text) === lang)) continue
89
106
  try {
90
- const scores = await this.vectors.scores(wording, docs, trace)
91
- for (const [id, score] of scores) semantic.set(id, score)
107
+ const scores = await this.vectors.scores(wording, docs, trace, lang)
108
+ for (const [id, score] of scores) semantic.set(id, Math.max(score, semantic.get(id) ?? -Infinity))
92
109
  coverage.add(trace.coverage)
93
110
  } catch {
94
111
  coverage.add('unavailable')
@@ -0,0 +1,58 @@
1
+ import { isDeepStrictEqual } from 'node:util'
2
+ import { skipsAutomaticMemory } from './automatic.ts'
3
+ import type { AccessDomain } from './domain.ts'
4
+ import type { Agent } from './host.ts'
5
+ import { isPersonalSlot } from './personal.ts'
6
+ import type { SemanticCandidate } from './semantic.ts'
7
+ import type { ProjectMemory } from './service.ts'
8
+ import { StoreError, type Ref, type Rule } from './store.ts'
9
+
10
+ type Agreement = Rule & { kind: 'rule' | 'preference'; semanticTopic: string }
11
+
12
+ function isAgreement(rule: Rule): rule is Agreement {
13
+ return Boolean(rule.semanticTopic) && (rule.kind === 'rule' || rule.kind === 'preference')
14
+ }
15
+
16
+ /** Bind a follow-up such as "I meant this project" to the actual agreement from
17
+ * the preceding turn. An assistant-supplied ID alone cannot authorize moving it. */
18
+ export function previousScopeAgreement(memory: ProjectMemory, agent: Agent, project: AccessDomain,
19
+ ref: Ref, generation: number, turn: string): Agreement {
20
+ const old = memory.current(memory.personal, ref.id)
21
+ if (!old || old.source.sessionId !== agent.id || old.source.storeId !== memory.storeId(agent.session))
22
+ throw new StoreError('target_not_found')
23
+ if (old.rev !== ref.rev) throw new StoreError('stale_revision')
24
+ if (!isPersonalSlot(old.slot) || !isAgreement(old) ||
25
+ old.channel !== 'automatic' || old.pinned || old.usageOverride || old.sensitive || old.localException ||
26
+ old.quoteType !== 'user_quote' || !old.evidence ||
27
+ skipsAutomaticMemory([old.action, old.user_quote, old.when, old.exceptions, old.semanticTopic,
28
+ old.subject, ...(old.keywords ?? [])].join('\n')))
29
+ throw new StoreError('protected_revision')
30
+
31
+ const starts = agent.session.snapshotEvents().slice(agent.session.inheritedEventCount)
32
+ .filter(event => event.type === 'turn/start').slice(-2)
33
+ if (starts.length !== 2 || String(starts[1].data.turn) !== turn || String(starts[0].data.turn) !== old.source.turnId)
34
+ throw new StoreError('invalid_source')
35
+ const prior = memory.proposalSources(agent, agent, project, old.source.turnId, generation)
36
+ const span = old.evidence
37
+ const block = prior.events.find(event => {
38
+ const start = span.start - (event.offset ?? 0)
39
+ return event.seq === old.source.seq && event.seq === span.seq && start >= 0 &&
40
+ event.text.slice(start, start + span.end - span.start) === old.user_quote &&
41
+ (!old.source.formSelection || event.formSelections?.some(option => isDeepStrictEqual(option, old.source.formSelection)))
42
+ })
43
+ if (prior.reason || !block) throw new StoreError(prior.reason ?? 'invalid_source')
44
+ if (!memory.store.soleTurnAgreement([project.id, memory.personal.id], old.source, ref))
45
+ throw new StoreError('ambiguous_topic')
46
+ return old
47
+ }
48
+
49
+ /** Project the saved agreement. The second proposal supplies only a clarification,
50
+ * never a new body, a new subject, or model-invented path restrictions. */
51
+ export function projectAgreement(old: Agreement): SemanticCandidate {
52
+ return {
53
+ scope: 'project', kind: old.kind, topic: old.semanticTopic,
54
+ action: old.action, user_quote: old.user_quote, subject: old.subject, when: old.when,
55
+ exceptions: old.exceptions, paths: old.paths, keywords: old.keywords ?? [],
56
+ usage: old.usage ?? 'on_demand', sensitive: false, conflicts_with_repo_guidance: false,
57
+ }
58
+ }
@@ -1,5 +1,5 @@
1
1
  import type { DatabaseSync } from 'node:sqlite'
2
- import { encoderId } from './encoder.ts'
2
+ import { encoderId, language } from './encoder.ts'
3
3
  import { isKnowledge } from './knowledge.ts'
4
4
  import { normalizeLabel } from './personal.ts'
5
5
  import type { DraftItem, Ref } from './store.ts'
@@ -23,12 +23,27 @@ export function document(rule: DraftItem) {
23
23
  export const indexWords = (text: string) => searchWords(text).map(word => Buffer.from(word).toString('hex'))
24
24
  const characters = (text: string) => Array.from(text, char => char.codePointAt(0)!.toString(16)).join(' ')
25
25
 
26
- // Each FTS row and vector job uses the stable primary key of its source revision.
27
- export function indexRevision(db: DatabaseSync, rid: number | bigint, rule: DraftItem) {
28
- const text = normalizeLabel(document(rule))
29
- db.prepare('INSERT INTO memory_fts(rowid,words,chars) VALUES(?,?,?)')
30
- .run(rid, indexWords(text).join(' '), characters(text))
31
- db.prepare('INSERT INTO memory_vector_jobs(rid) VALUES(?)').run(rid)
26
+ function indexLabels(db: DatabaseSync, domain: string, rid: number | bigint, rule: DraftItem) {
27
+ const canonical = normalizeLabel(rule.semanticTopic ?? '')
28
+ const aliases = new Set([canonical, ...(rule.keywords ?? []).map(normalizeLabel)])
29
+ aliases.delete('')
30
+ if (!aliases.size) return
31
+ const subject = normalizeLabel(rule.subject ?? '')
32
+ const insert = db.prepare('INSERT INTO memory_topic_labels(domain,label,subject,rid,canonical) VALUES(?,?,?,?,?)')
33
+ for (const label of aliases)
34
+ insert.run(domain, label, subject, rid, Number(label === canonical))
35
+ }
36
+
37
+ // Each derived row belongs to the stable primary key of its source revision.
38
+ export function indexRevision(db: DatabaseSync, domain: string, rid: number | bigint, rule: DraftItem) {
39
+ indexLabels(db, domain, rid, rule)
40
+ const content = document(rule)
41
+ const text = normalizeLabel(content)
42
+ const labels = rule.sensitive || rule.usage !== 'on_demand' ? '' :
43
+ normalizeLabel([rule.semanticTopic, ...(rule.keywords ?? [])].filter(Boolean).join(' '))
44
+ db.prepare('INSERT INTO memory_fts(rowid,words,chars,labels) VALUES(?,?,?,?)')
45
+ .run(rid, indexWords(text).join(' '), characters(text), indexWords(labels).join(' '))
46
+ db.prepare('INSERT INTO memory_vector_jobs(rid,language) VALUES(?,?)').run(rid, language(content))
32
47
  }
33
48
 
34
49
  export function promptRole(rule: DraftItem) {
@@ -47,10 +62,11 @@ export class SearchIndex {
47
62
  CREATE INDEX revision_current_slot ON revisions(domain,slot)
48
63
  WHERE state='confirmed' AND slot IS NOT NULL;
49
64
  CREATE INDEX revision_prompt_role ON revisions(domain,proactive) WHERE state='confirmed';
50
- CREATE VIRTUAL TABLE memory_fts USING fts5(words,chars,content='',contentless_delete=1);
65
+ CREATE VIRTUAL TABLE memory_fts USING fts5(words,chars,labels,content='',contentless_delete=1);
51
66
  INSERT INTO memory_fts(memory_fts,rank) VALUES('secure-delete',1);
52
- CREATE TABLE memory_vector_jobs (rid INTEGER PRIMARY KEY, available INTEGER NOT NULL DEFAULT 0);
67
+ CREATE TABLE memory_vector_jobs (rid INTEGER PRIMARY KEY, available INTEGER NOT NULL DEFAULT 0, language TEXT NOT NULL);
53
68
  CREATE INDEX memory_vector_ready ON memory_vector_jobs(available,rid);
69
+ CREATE INDEX memory_vector_language_ready ON memory_vector_jobs(language,available,rid);
54
70
  CREATE TABLE memory_vector_format (version TEXT PRIMARY KEY);
55
71
  CREATE TRIGGER remove_retired_search AFTER UPDATE OF state ON revisions WHEN OLD.state='confirmed' AND NEW.state<>'confirmed' BEGIN
56
72
  DELETE FROM memory_fts WHERE rowid=NEW.rid;
@@ -59,13 +75,77 @@ export class SearchIndex {
59
75
  `)
60
76
  }
61
77
 
78
+ ensureTopicLabels() {
79
+ if (this.db.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name='memory_topic_labels'").get()) {
80
+ const pending = this.db.prepare(`SELECT r.rid,r.domain,r.payload FROM memory_unindexed_topics u
81
+ CROSS JOIN revisions r ON u.rid=r.rid AND r.state='confirmed'`)
82
+ for (const row of pending.iterate())
83
+ indexLabels(this.db, String(row.domain), Number(row.rid), JSON.parse(String(row.payload)))
84
+ this.db.exec('DELETE FROM memory_unindexed_topics')
85
+ return
86
+ }
87
+ // Backfill once, under the same write transaction as initialization. Retired revisions
88
+ // never contribute aliases and consent cleanup removes their derived labels atomically.
89
+ // An older CLI sharing the same database can write FTS without knowing this index.
90
+ // The heads trigger marks just those revisions. New writers have already indexed
91
+ // their labels before they publish a head. A reader includes pending rows immediately.
92
+ const queueUnindexed = `INSERT OR IGNORE INTO memory_unindexed_topics(domain,rid)
93
+ 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'
94
+ AND (json_type(r.payload,'$.semanticTopic')='text' OR json_array_length(r.payload,'$.keywords')>0)
95
+ AND NOT EXISTS(SELECT 1 FROM memory_topic_labels l WHERE l.rid=r.rid);`
96
+ this.db.exec(`CREATE TABLE memory_topic_labels (
97
+ domain TEXT NOT NULL, label TEXT NOT NULL, subject TEXT NOT NULL, rid INTEGER NOT NULL,
98
+ canonical INTEGER NOT NULL, PRIMARY KEY(domain,label,subject,rid)
99
+ ) WITHOUT ROWID;
100
+ CREATE INDEX memory_topic_revision ON memory_topic_labels(rid);
101
+ CREATE TABLE memory_unindexed_topics(domain TEXT NOT NULL,rid INTEGER NOT NULL,PRIMARY KEY(domain,rid)) WITHOUT ROWID;
102
+ CREATE TRIGGER queue_legacy_topic_insert AFTER INSERT ON heads BEGIN ${queueUnindexed} END;
103
+ CREATE TRIGGER queue_legacy_topic_update AFTER UPDATE OF rev ON heads BEGIN ${queueUnindexed} END;
104
+ CREATE INDEX memory_scope_vector_models ON memory_vectors(domain,model,id,rev);
105
+ CREATE TRIGGER retire_topic_labels AFTER UPDATE OF state ON revisions
106
+ WHEN OLD.state='confirmed' AND NEW.state<>'confirmed'
107
+ BEGIN DELETE FROM memory_topic_labels WHERE rid=OLD.rid;
108
+ DELETE FROM memory_unindexed_topics WHERE domain=OLD.domain AND rid=OLD.rid; END;`)
109
+ const heads = this.db.prepare(`SELECT r.domain,r.rid,r.payload FROM heads h
110
+ CROSS JOIN revisions r USING(domain,id,rev) WHERE r.state='confirmed'`)
111
+ for (const row of heads.iterate())
112
+ indexLabels(this.db, String(row.domain), Number(row.rid), JSON.parse(String(row.payload)))
113
+ }
114
+
115
+ topicRefs(domain: string, topic: string, subject?: string, canonicalScope?: 'global' | 'project') {
116
+ const hasSubject = canonicalScope !== undefined || subject !== undefined
117
+ const slot = canonicalScope === 'global' ? " AND r.slot GLOB 'profile.topic.*'" :
118
+ canonicalScope === 'project' ? " AND r.slot GLOB 'project.topic.*'" : ''
119
+ const normalized = normalizeLabel(topic)
120
+ const owner = normalizeLabel(subject ?? '')
121
+ const rows = this.db.prepare(`SELECT r.id,r.rev,r.confirmed,NULL AS pending FROM memory_topic_labels l
122
+ 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
123
+ WHERE l.domain=? AND l.label=? ${hasSubject ? 'AND l.subject=?' : ''}${canonicalScope ? ' AND l.canonical=1' : ''}${slot}
124
+ AND r.state='confirmed'
125
+ UNION ALL SELECT r.id,r.rev,r.confirmed,r.payload AS pending FROM memory_unindexed_topics u
126
+ 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
127
+ WHERE u.domain=? AND r.state='confirmed'${slot} ORDER BY 3 DESC,1`)
128
+ .all(domain, normalized, ...(hasSubject ? [owner] : []), domain)
129
+ return rows.flatMap(row => {
130
+ if (row.pending) {
131
+ const rule: DraftItem = JSON.parse(String(row.pending))
132
+ if (hasSubject && normalizeLabel(rule.subject ?? '') !== owner) return []
133
+ const labels = canonicalScope ? [rule.semanticTopic] : [rule.semanticTopic, ...(rule.keywords ?? [])]
134
+ if (!labels.some(label => label && normalizeLabel(label) === normalized)) return []
135
+ }
136
+ return [{domain, id: String(row.id), rev: Number(row.rev)}]
137
+ })
138
+ }
139
+
62
140
  syncVectorFormat() {
63
141
  // Changing the encoder or passage layout requeues current revisions, including completed jobs.
64
142
  const version = [encoderId('en'), encoderId('zh'), 'passages-v1'].join('|')
65
143
  if (!this.db.prepare('SELECT 1 FROM memory_vector_format WHERE version=?').get(version)) {
66
- this.db.exec(`DELETE FROM memory_vector_format;
67
- INSERT OR IGNORE INTO memory_vector_jobs(rid)
68
- SELECT r.rid FROM heads h CROSS JOIN revisions r USING(domain,id,rev) WHERE r.state='confirmed'`)
144
+ this.db.exec('DELETE FROM memory_vector_format')
145
+ const heads = this.db.prepare("SELECT r.rid,r.payload FROM heads h JOIN revisions r USING(domain,id,rev) WHERE r.state='confirmed'")
146
+ const enqueue = this.db.prepare('INSERT OR IGNORE INTO memory_vector_jobs(rid,language) VALUES(?,?)')
147
+ for (const row of heads.iterate())
148
+ enqueue.run(row.rid, language(document(JSON.parse(String(row.payload)))))
69
149
  this.db.prepare('INSERT INTO memory_vector_format VALUES(?)').run(version)
70
150
  }
71
151
  }
@@ -79,7 +159,7 @@ export class SearchIndex {
79
159
  const reviewable = filter === 'review_topics'
80
160
  ? " AND r.slot IS NOT NULL AND json_extract(r.payload,'$.sensitive') IS NOT 1"
81
161
  : ''
82
- const collect = (expression: string, weight: '3' | '-bm25(memory_fts,1,0)') => {
162
+ const collect = (expression: string, weight: '3' | '-bm25(memory_fts,1,0,0)') => {
83
163
  const find = this.db.prepare(`SELECT r.rid,r.domain,r.id,r.rev,${weight} AS weight
84
164
  FROM memory_fts CROSS JOIN revisions r ON r.rid=memory_fts.rowid
85
165
  WHERE memory_fts MATCH ? AND r.domain IN (${where})${reviewable}`)
@@ -90,7 +170,7 @@ export class SearchIndex {
90
170
  hits.set(rid, hit)
91
171
  }
92
172
  }
93
- if (terms.length) collect('words:(' + terms.join(' OR ') + ')', '-bm25(memory_fts,1,0)')
173
+ if (terms.length) collect('words:(' + terms.join(' OR ') + ')', '-bm25(memory_fts,1,0,0)')
94
174
  if (q) collect('chars:"' + characters(q) + '"', '3')
95
175
  return [...hits.values()]
96
176
  }