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
package/src/ui.ts CHANGED
@@ -3,15 +3,22 @@ import type { Host } from './host.ts'
3
3
  import type { ProjectMemory, publicRule } from './service.ts'
4
4
  import type { Ref } from './store.ts'
5
5
 
6
- type MemoryUI = Pick<ProjectMemory, 'view' | 'review' | 'manage' | 'domainOf' | 'store' |
6
+ type MemoryUI = Pick<ProjectMemory, 'view' | 'review' | 'manage' | 'domainOf' | 'store' | 'turnReceipts' |
7
7
  'listConsolidation' | 'decideConsolidation'>
8
+ type ReviewView = Pick<ReturnType<MemoryUI['view']>, 'proposals' | 'rules'>
8
9
  type ReviewInput = Parameters<MemoryUI['review']>[1]
9
10
  type Inputs = Partial<ReviewInput> & {
10
11
  sessionId?: unknown
11
12
  version?: string
13
+ lease?: string
14
+ answerSeq?: unknown
12
15
  op?: Parameters<MemoryUI['manage']>[1]
13
16
  args?: Parameters<MemoryUI['manage']>[2]
14
17
  scope?: 'profile' | 'project'
18
+ details?: unknown
19
+ includePending?: boolean
20
+ page?: { offset: number; limit: number }
21
+ expectedContext?: { root?: unknown; cwd?: unknown; projectKey?: unknown } | null
15
22
  enabled?: unknown
16
23
  root?: unknown
17
24
  left?: unknown
@@ -57,6 +64,9 @@ function chatRule<T extends ReturnType<typeof publicRule>>(rule: T) {
57
64
  ? { id: rule.id, rev: rule.rev, scope: rule.scope, topic: rule.topic, usage: rule.usage }
58
65
  : rule
59
66
  }
67
+ function hasReviewCards(value: object): value is ReviewView {
68
+ return 'proposals' in value && Array.isArray(value.proposals) && 'rules' in value
69
+ }
60
70
  interface Watch {
61
71
  version: string
62
72
  listeners: Set<() => void>
@@ -92,6 +102,8 @@ function waitForChange(watches: Watch[], version: string | undefined, signal: Ab
92
102
  export function registerUI(ctx: Host, api: MemoryUI) {
93
103
  ctx.inject(['connection', 'agents'], (host: UIHost) => {
94
104
  const watches = new WeakMap<object, Watch>()
105
+ // Receipts contain no rule bodies. Keep at most one per visible projection per session.
106
+ const leases = new WeakMap<object, Map<string, { token: string; stamp: string }>>()
95
107
  const settings = createWatch()
96
108
  const wake = (sessionId: string) => {
97
109
  const session = host.agents.get(sessionId)?.session
@@ -134,18 +146,19 @@ export function registerUI(ctx: Host, api: MemoryUI) {
134
146
  return { ok: true, value: { memoryEnabled: api.store.memoryEnabled(), consolidation: api.store.consolidation.status(),
135
147
  readOnly, version: settings.version } }
136
148
  }
137
- if (typeof args.sessionId !== 'string' || args.sessionId.length > 256) return failure('unavailable')
149
+ const sessionId = args.sessionId
150
+ if (typeof sessionId !== 'string' || sessionId.length > 256) return failure('unavailable')
138
151
  const allowed = () => globalAllowed() &&
139
- host.get('remoteAccess')?.allows({ kind: 'session', id: args.sessionId }) !== false
152
+ host.get('remoteAccess')?.allows({ kind: 'session', id: sessionId }) !== false
140
153
  if (!allowed()) return failure('unavailable')
141
154
  const agent =
142
- host.agents.get(args.sessionId) ??
143
- (await host.get('sessionController')?.resolveAgent(args.sessionId))?.agent
155
+ host.agents.get(sessionId) ??
156
+ (await host.get('sessionController')?.resolveAgent(sessionId))?.agent
144
157
  if (
145
158
  !agent ||
146
159
  agent.session.header.origin === 'subagent' ||
147
160
  !allowed() ||
148
- host.agents.get(args.sessionId) !== agent
161
+ host.agents.get(sessionId) !== agent
149
162
  )
150
163
  return failure('unavailable')
151
164
  const context = () => {
@@ -153,13 +166,53 @@ export function registerUI(ctx: Host, api: MemoryUI) {
153
166
  return {
154
167
  root: project?.root ?? null,
155
168
  cwd: project?.cwd ?? host.workingDirectory.get(agent.session),
169
+ projectKey: project?.id ?? null,
156
170
  readOnly: host.get('sandboxPolicy')?.resolve({ session: agent.session }).mode === 'read-only',
157
171
  }
158
172
  }
159
- if (method === 'context') return { ok: true, value: context() }
173
+ const matchesContext = (expected: Inputs['expectedContext'], live: ReturnType<typeof context>) =>
174
+ expected === undefined || (!!expected && expected.root === live.root &&
175
+ expected.cwd === live.cwd && expected.projectKey === live.projectKey)
176
+ const stillAllowed = () => !signal.aborted && allowed() && host.agents.get(sessionId) === agent
177
+ const stamp = (live: ReturnType<typeof context>, scope?: Inputs['scope']) => {
178
+ if (!api.store.uiChangeStamp) return ''
179
+ const domains = []
180
+ if (scope !== 'project') domains.push('profile:personal')
181
+ if (scope !== 'profile' && live.projectKey) domains.push(live.projectKey)
182
+ return JSON.stringify([api.store.uiChangeStamp(domains), scope ? args.args?.locale :
183
+ watches.get(agent.session)?.version, live, args.page && [args.page.offset, args.page.limit]])
184
+ }
185
+ const unchanged = (key: string, current: string) => {
186
+ const lease = leases.get(agent.session)?.get(key)
187
+ return current && lease && lease.token === args.lease && lease.stamp === current
188
+ }
189
+ const grant = (key: string, current: string) => {
190
+ let entries = leases.get(agent.session)
191
+ if (!entries) leases.set(agent.session, entries = new Map())
192
+ const old = entries.get(key)
193
+ if (old?.stamp === current) return old.token
194
+ const token = randomUUID()
195
+ entries.set(key, { token, stamp: current })
196
+ return token
197
+ }
198
+ const boundContext = args.expectedContext === undefined ? undefined : context()
199
+ if (signal.aborted || (boundContext && !matchesContext(args.expectedContext, boundContext)))
200
+ return failure('unavailable')
201
+ if (method === 'context') {
202
+ const live = boundContext ?? context()
203
+ return { ok: true, value: { ...live, ...(args.includePending && live.projectKey && {
204
+ hasPending: api.store.inbox(live.projectKey, sessionId).length > 0,
205
+ }) } }
206
+ }
207
+ if (method === 'turn-receipts') {
208
+ if (typeof args.answerSeq !== 'number' || !Number.isSafeInteger(args.answerSeq) || args.answerSeq < 0)
209
+ return failure('invalid_input')
210
+ if (signal.aborted) return failure('unavailable')
211
+ return { ok: true, value: api.turnReceipts(agent, args.answerSeq) }
212
+ }
160
213
  if (method === 'consolidation-suggestions' || method === 'decide-consolidation') {
161
- const project = context()
162
- if (signal.aborted || args.scope !== 'project' || !project.root || project.root !== args.root)
214
+ const project = boundContext ?? context()
215
+ if (args.scope !== 'project' || !project.root || project.root !== args.root)
163
216
  return failure('unavailable')
164
217
  if (method === 'consolidation-suggestions')
165
218
  return { ok: true, value: { suggestions: api.listConsolidation(agent) } }
@@ -182,19 +235,59 @@ export function registerUI(ctx: Host, api: MemoryUI) {
182
235
  (args.scope !== undefined && args.scope !== 'profile' && args.scope !== 'project')
183
236
  )
184
237
  return failure('invalid_input')
238
+ if (args.details !== undefined && (typeof args.details !== 'boolean' ||
239
+ (args.details && (!args.scope || !['list', 'search'].includes(args.op)))))
240
+ return failure('invalid_input')
241
+ if (args.page !== undefined && (!args.details || !args.page || !Number.isSafeInteger(args.page.offset) ||
242
+ args.page.offset < 0 || !Number.isSafeInteger(args.page.limit) || args.page.limit < 0 || args.page.limit > 50))
243
+ return failure('invalid_input')
185
244
  const write = !['list', 'search', 'read', 'source'].includes(args.op)
186
- const readOnly = host.get('sandboxPolicy')?.resolve({ session: agent.session }).mode === 'read-only'
187
- if (readOnly && write) return failure('read_only', '当前会话处于只读模式')
188
- const result = await api.manage(agent, args.op, { ...args.args, scope: args.scope })
189
- if (signal.aborted || !allowed() || host.agents.get(args.sessionId) !== agent)
190
- return failure('unavailable')
245
+ const before = boundContext ?? context()
246
+ if (before.readOnly && write) return failure('read_only', '当前会话处于只读模式')
247
+ const listLease = args.op === 'list' && args.page && args.scope ? 'list:' + args.scope : ''
248
+ const initial = listLease ? stamp(before, args.scope) : ''
249
+ if (unchanged(listLease, initial)) return { ok: true, value: { unchanged: true, lease: args.lease } }
250
+ const check = { reusable: false }
251
+ const result = await api.manage(agent, args.op, { ...args.args, scope: args.scope }, listLease ? check : undefined, args.page)
252
+ if (!stillAllowed()) return failure('unavailable')
253
+ const live = context()
254
+ if (!matchesContext(before, live)) return failure('unavailable')
255
+ const { readOnly } = live
191
256
  if (write) wake(agent.id)
192
257
  if (args.scope && 'rules' in result) {
193
258
  const inScope = (item: { scope: string }) => item.scope === args.scope
194
- return { ok: true, value: { readOnly, result: {
259
+ const scoped = {
195
260
  rules: result.rules.filter(inScope),
196
261
  needs_review: result.needs_review.filter(inScope),
197
- } } }
262
+ }
263
+ if (!args.details) return { ok: true, value: { readOnly, result: scoped } }
264
+ // Pending cards belong to this session in the project's store. List already
265
+ // carries the view; search may also need replacement choices outside its hits.
266
+ let review: ReviewView | undefined
267
+ if (args.scope === 'project' && live.projectKey) {
268
+ if (hasReviewCards(result)) review = 'choices' in result && Array.isArray(result.choices)
269
+ ? { proposals: result.proposals, rules: result.choices } : result
270
+ else if (api.store.inbox(live.projectKey, agent.id).length) review = api.view(agent, 'project')
271
+ }
272
+ const proposals = review?.proposals.filter(card => card.state === 'pending' &&
273
+ (!('scope' in card) || card.scope === args.scope)) ?? []
274
+ const reviewRules = review && proposals.some(card => !card.source.fileImport)
275
+ ? review.rules.filter(rule => inScope(rule) && !('knowledge' in rule)).map(rule => {
276
+ const { id, rev, scope, topic, usage, when, action, paths } = rule
277
+ return usage === 'on_demand' && topic ? { id, rev, scope, topic, usage }
278
+ : { id, rev, scope, topic, usage, when, action, paths }
279
+ }) : []
280
+ const suggestions = args.op === 'list' && args.scope === 'project' && live.projectKey
281
+ ? api.listConsolidation(agent) : []
282
+ const lease = listLease && check.reusable && initial && initial === stamp(live, args.scope) ? grant(listLease, initial) : undefined
283
+ const pagedTotal = 'total' in result && typeof result.total === 'number' ? result.total : undefined
284
+ const total = pagedTotal ?? scoped.rules.length + scoped.needs_review.length
285
+ const { offset, limit } = args.page ?? { offset: 0, limit: total }
286
+ const resultPage = args.page && pagedTotal === undefined ? { rules: scoped.rules.slice(offset, offset + limit),
287
+ needs_review: scoped.needs_review.slice(Math.max(0, offset - scoped.rules.length),
288
+ Math.max(0, offset + limit - scoped.rules.length)) } : scoped
289
+ return { ok: true, value: { lease, readOnly, result: resultPage, ...(args.page && { total }), proposals, reviewRules, suggestions,
290
+ memoryEnabled: api.store.memoryEnabled(), context: live } }
198
291
  }
199
292
  return { ok: true, value: { result, readOnly } }
200
293
  }
@@ -206,29 +299,31 @@ export function registerUI(ctx: Host, api: MemoryUI) {
206
299
  }
207
300
  const observed = [watch, settings]
208
301
  await waitForChange(observed, args.version, signal)
209
- if (signal.aborted || !allowed() || host.agents.get(args.sessionId) !== agent)
210
- return failure('unavailable')
302
+ if (!stillAllowed()) return failure('unavailable')
303
+ const live = context()
304
+ if (!matchesContext(args.expectedContext, live)) return failure('unavailable')
211
305
  const version = watchVersion(observed)
212
- const { proposals, rules, saved } = api.view(agent)
306
+ const initial = stamp(live)
307
+ if (unchanged('chat', initial)) return { ok: true, value: { unchanged: true, version, lease: args.lease } }
308
+ const check = { reusable: false }
309
+ const { conversationCards = [], rules, saved } = api.view(agent, 'chat', check)
213
310
  // Chat polls for receipts every turn. Values of on-demand global memories are
214
311
  // returned through an explicit manager read, never through this polling channel.
215
- const receipts = new Set(proposals.flatMap(proposal =>
216
- proposal.receipt?.entries.map(ref => ref.id + '@' + ref.rev) ?? []))
312
+ const receipts = new Set(conversationCards.flatMap(card => card.entries.map(ref => ref.id + '@' + ref.rev)))
217
313
  const visibleRules = rules
218
314
  .filter(rule => rule.usage === 'proactive' || !rule.topic || receipts.has(rule.id + '@' + rule.rev))
219
315
  .map(chatRule)
220
- const cards = proposals.map(proposal => ({
221
- ...proposal, items: proposal.items.map(item => ({ ...item, related: item.related.map(chatRule) })),
222
- }))
223
316
  const notices = saved.map(row => ({
224
317
  id: row.id, rev: row.rev, scope: row.scope, turnId: row.turnId, topic: row.topic,
225
318
  usage: row.usage, hasPrevious: !!row.previous,
226
319
  }))
227
- return { ok: true, value: { proposals: cards, rules: visibleRules, saved: notices, context: context(), version,
320
+ const lease = check.reusable && initial && initial === stamp(live) ? grant('chat', initial) : undefined
321
+ return { ok: true, value: { proposals: conversationCards, rules: visibleRules, saved: notices, context: live, version, lease,
228
322
  memoryEnabled: api.store.memoryEnabled() } }
229
323
  }
230
324
  if (host.get('sandboxPolicy')?.resolve({ session: agent.session }).mode === 'read-only')
231
325
  return failure('read_only', '当前会话处于只读模式')
326
+ if (args.scope !== undefined && args.scope !== 'project') return failure('unavailable')
232
327
  if (
233
328
  typeof args.id !== 'string' ||
234
329
  typeof args.revision !== 'number' ||
@@ -236,7 +331,7 @@ export function registerUI(ctx: Host, api: MemoryUI) {
236
331
  !Array.isArray(args.selections)
237
332
  )
238
333
  return failure('invalid_input')
239
- const result = await api.review(
334
+ const result = api.review(
240
335
  agent,
241
336
  { id: args.id, revision: args.revision, digest: args.digest, selections: args.selections },
242
337
  undefined,
@@ -252,7 +347,7 @@ export function registerUI(ctx: Host, api: MemoryUI) {
252
347
  }
253
348
  // The panel reads, reviews and manages. Saving a new statement by hand is the /project-memory remember command.
254
349
  for (const method of ['get-settings', 'set-memory-enabled', 'set-consolidation',
255
- 'context', 'view', 'review', 'manage', 'consolidation-suggestions', 'decide-consolidation']) {
350
+ 'context', 'view', 'turn-receipts', 'review', 'manage', 'consolidation-suggestions', 'decide-consolidation']) {
256
351
  connection.fetch.register({
257
352
  path: '/api/' + endpoint + method,
258
353
  methods: ['POST'],
@@ -4,10 +4,10 @@ import { document, type KeywordHit } from './search-index.ts'
4
4
  export { document } from './search-index.ts'
5
5
  import { createHash } from 'node:crypto'
6
6
  import { setImmediate as yieldToHost } from 'node:timers/promises'
7
- import { encoderId, SentenceEncoder, type Encoder } from './encoder.ts'
7
+ import { encoderId, language, modelLanguages, queryLanguages, SentenceEncoder, type Encoder, type ModelLanguage } from './encoder.ts'
8
8
  import type { Rule, MemoryStore } from './store.ts'
9
9
 
10
- export const language = (text: string) => /\p{Script=Han}/u.test(text) ? 'zh' : 'en'
10
+ export { language } from './encoder.ts'
11
11
 
12
12
  export type SearchCoverage = 'complete' | 'partial' | 'missing' | 'unavailable'
13
13
 
@@ -36,7 +36,12 @@ export class VectorIndex {
36
36
  this.encoder = encoder
37
37
  }
38
38
 
39
+ get languages() {
40
+ return this.encoder.languages ?? modelLanguages
41
+ }
42
+
39
43
  start() {
44
+ if (!this.languages.length) return
40
45
  this.store.onHeadsChanged = () => this.enqueue()
41
46
  this.enqueue()
42
47
  }
@@ -55,7 +60,7 @@ export class VectorIndex {
55
60
  private async drain() {
56
61
  try {
57
62
  while (!this.closed) {
58
- const job = this.store.nextVectorJob()
63
+ const job = this.store.nextVectorJob(this.languages.length === 1 ? this.languages[0] : undefined)
59
64
  if (!job) break
60
65
  await yieldToHost()
61
66
  if (this.closed) return
@@ -84,18 +89,15 @@ export class VectorIndex {
84
89
  }
85
90
  }
86
91
 
87
- private passages({ rule, domain }: SearchRow, text: string, trace?: SearchTrace) {
92
+ private passages(rule: Rule, text: string, cached?: ReturnType<MemoryStore['headVectors']>) {
88
93
  const model = encoderId(language(text))
89
94
  const segments = rule.action.split(/[,,;;。!?::\n]+/u).map(s => s.trim())
90
95
  .filter(s => s.length >= 6 && s !== rule.action)
91
96
  const parts = [...new Set([text, ...segments])].slice(0, 8)
92
- const start = performance.now()
93
- const cached = this.store.headVectors(domain, rule.id, rule.rev)
94
- if (trace) trace.sqliteMs += performance.now() - start
95
97
  return parts.map((part, i) => {
96
98
  const key = model + '/passage-' + i
97
99
  const digest = createHash('sha256').update(part).digest('hex')
98
- const entry = cached.get(key)
100
+ const entry = cached?.get(key)
99
101
  return { text: part, key, digest, vector: entry?.digest === digest ? entry.vector : undefined }
100
102
  })
101
103
  }
@@ -120,7 +122,7 @@ export class VectorIndex {
120
122
 
121
123
  async indexRule(row: SearchRow) {
122
124
  const text = document(row.rule)
123
- const missing = this.passages(row, text).filter(p => !p.vector)
125
+ const missing = this.passages(row.rule, text, this.store.headVectors(row.domain, row.rule.id, row.rule.rev)).filter(p => !p.vector)
124
126
  if (!missing.length) {
125
127
  this.store.finishVectorJob(row.domain, row.rule.id, row.rule.rev)
126
128
  return
@@ -138,8 +140,7 @@ export class VectorIndex {
138
140
  this.store.finishVectorJob(row.domain, row.rule.id, row.rule.rev)
139
141
  }
140
142
 
141
- private async queryVector(query: string, trace?: SearchTrace) {
142
- const lang = language(query)
143
+ private async queryVector(query: string, lang: ModelLanguage, trace?: SearchTrace) {
143
144
  const instruction = lang === 'zh'
144
145
  ? '为这个句子生成表示以用于检索相关文章:'
145
146
  : 'Represent this sentence for searching relevant passages: '
@@ -150,12 +151,25 @@ export class VectorIndex {
150
151
  // Compare existing document vectors without loading historical quotes or keeping a
151
152
  // SQLite reader open during inference. Empty or unindexed domains cost no encoding.
152
153
  async reviewTopics(domains: string[], query: string) {
153
- const model = encoderId(language(query)) + '/passage-0'
154
+ const hits: KeywordHit[] = []
155
+ for (const lang of queryLanguages(query)) {
156
+ if (!this.languages.includes(lang)) continue
157
+ try {
158
+ hits.push(...await this.reviewLanguage(domains, query, lang))
159
+ } catch {
160
+ // Another installed language and the lexical index can still offer candidates.
161
+ }
162
+ }
163
+ return hits.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id))
164
+ }
165
+
166
+ private async reviewLanguage(domains: string[], query: string, lang: ModelLanguage) {
167
+ const model = encoderId(lang) + '/passage-0'
154
168
  const probe = this.store.reviewVectors(domains, model)
155
169
  const empty = probe.next().done
156
170
  probe.return()
157
171
  if (empty) return []
158
- const q = await this.queryVector(query)
172
+ const q = await this.queryVector(query, lang)
159
173
  const hits: KeywordHit[] = []
160
174
  for (const { domain, id, rev, vector } of this.store.reviewVectors(domains, model)) {
161
175
  if (vector.length !== q.length) continue
@@ -164,30 +178,44 @@ export class VectorIndex {
164
178
  // The model must still identify one target and the write path verifies the quote.
165
179
  if (score >= 0.4) hits.push({ domain, id, rev, score })
166
180
  }
167
- return hits.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id))
181
+ return hits
168
182
  }
169
183
 
170
- async scores(query: string, docs: (SearchRow & { text: string })[], trace: SearchTrace) {
171
- const lang = language(query)
172
- const vectors: { id: string; vector: Float32Array }[] = []
173
- let missing = 0
184
+ async scores(query: string, docs: (SearchRow & { text: string })[], trace: SearchTrace, lang: ModelLanguage) {
185
+ const groups = new Map<string, typeof docs>()
174
186
  for (const doc of docs) {
175
187
  if (language(doc.text) !== lang) continue
176
- for (const passage of this.passages(doc, doc.text, trace)) {
177
- if (passage.vector) vectors.push({ id: doc.rule.id, vector: passage.vector })
178
- else missing++
179
- }
188
+ const group = groups.get(doc.domain)
189
+ if (group) group.push(doc)
190
+ else groups.set(doc.domain, [doc])
180
191
  }
181
- trace.coverage = missing ? vectors.length ? 'partial' : 'missing' : 'complete'
182
192
  const scores = new Map<string, number>()
183
- if (!vectors.length) return scores
184
- const q = await this.queryVector(query, trace)
185
- for (const { id, vector } of vectors) {
186
- if (vector.length === q.length) {
187
- const score = vector.reduce((sum, v, i) => sum + v * q[i], 0)
188
- scores.set(id, Math.max(scores.get(id) ?? -1, score))
193
+ let q: Float32Array | undefined
194
+ let missing = false
195
+ for (const [domain, group] of groups) {
196
+ // Read complete candidate batches before yielding. Other sessions can write during
197
+ // inference, and a broad query never holds all passage vectors in memory.
198
+ for (let start = 0; start < group.length; start += 96) {
199
+ if (start) await yieldToHost()
200
+ const batch = group.slice(start, start + 96)
201
+ const before = performance.now()
202
+ const stored = this.store.headVectorsMany(domain, batch.map(({rule}) => ({id: rule.id, rev: rule.rev})))
203
+ trace.sqliteMs += performance.now() - before
204
+ for (const { rule, text } of batch) {
205
+ const cached = stored.get(rule.id)
206
+ if (!cached) { missing = true; continue }
207
+ for (const { vector } of this.passages(rule, text, cached)) {
208
+ if (!vector) { missing = true; continue }
209
+ q ??= await this.queryVector(query, lang, trace)
210
+ if (vector.length !== q.length) continue
211
+ let score = 0
212
+ for (let i = 0; i < q.length; i++) score += vector[i] * q[i]
213
+ scores.set(rule.id, Math.max(scores.get(rule.id) ?? -1, score))
214
+ }
215
+ }
189
216
  }
190
217
  }
218
+ trace.coverage = missing ? q ? 'partial' : 'missing' : 'complete'
191
219
  return scores
192
220
  }
193
221