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.
- package/CHANGELOG.md +6 -7
- package/README.md +125 -91
- package/README.zh-CN.md +122 -92
- package/SECURITY.md +29 -0
- package/dist/audit.js +155 -80
- package/dist/automatic.js +10 -2
- package/dist/client.js +2035 -0
- package/dist/command-scope.js +4 -4
- package/dist/commands.js +15 -9
- package/dist/consolidation-store.js +87 -20
- package/dist/consolidation.js +2 -6
- package/dist/domain.js +8 -4
- package/dist/encoder.js +46 -5
- package/dist/file-import-store.js +120 -0
- package/dist/file-import.js +265 -0
- package/dist/foreground-attempts.js +91 -0
- package/dist/guidance.js +133 -92
- package/dist/host.js +13 -0
- package/dist/index-policy.js +91 -48
- package/dist/index.js +102 -40
- package/dist/knowledge-hooks.js +70 -27
- package/dist/knowledge.js +2 -3
- package/dist/maintenance-store.js +38 -4
- package/dist/maintenance.js +29 -5
- package/dist/personal.js +37 -0
- package/dist/policy.js +45 -47
- package/dist/prompt-copy.js +93 -0
- package/dist/proposal-receipts.js +70 -0
- package/dist/proposal-review.js +656 -0
- package/dist/propose-contract.js +32 -36
- package/dist/question-answers.js +86 -29
- package/dist/retrieval.js +25 -8
- package/dist/scope-narrowing.js +49 -0
- package/dist/search-index.js +93 -13
- package/dist/semantic.js +69 -207
- package/dist/service.js +633 -204
- package/dist/sharing.js +7 -13
- package/dist/sources.js +28 -3
- package/dist/store.js +432 -96
- package/dist/tool-experience.js +87 -0
- package/dist/turn-review-store.js +83 -16
- package/dist/turn-review.js +155 -59
- package/dist/ui.js +128 -26
- package/dist/vector-index.js +69 -33
- package/docs/architecture.zh-CN.md +52 -0
- package/docs/benchmark.zh-CN.md +60 -0
- package/docs/benchmarks/repository-tasks.json +5355 -0
- package/docs/images/bond-memory-principle-en.svg +644 -0
- package/docs/images/bond-memory-principle-zh.svg +644 -0
- package/docs/images/bond-memory-principle.drawio +644 -0
- package/docs/images/memory-settings-en.png +0 -0
- package/docs/images/memory-settings-zh.png +0 -0
- package/docs/images/memory-turn-recalled-en.png +0 -0
- package/docs/images/memory-turn-recalled-zh.png +0 -0
- package/docs/images/memory-turn-saved-en.png +0 -0
- package/docs/images/memory-turn-saved-zh.png +0 -0
- package/docs/media/memory-bond-name-en.gif +0 -0
- package/docs/media/memory-bond-name-en.mp4 +0 -0
- package/docs/media/memory-bond-name-zh.gif +0 -0
- package/docs/media/memory-bond-name-zh.mp4 +0 -0
- package/locale/detail.en.md +5 -1
- package/locale/detail.zh.md +5 -1
- package/locale/en.json +338 -0
- package/locale/zh.json +338 -0
- package/native/embeddings/NOTICE.md +2 -2
- package/package.json +39 -19
- package/scripts/benchmark-bond.mjs +72 -0
- package/scripts/benchmark-conditions.mjs +144 -0
- package/scripts/benchmark-example.mjs +37 -0
- package/scripts/benchmark-scale.mjs +119 -0
- package/scripts/benchmark-scenarios.mjs +57 -0
- package/scripts/benchmark-tasks.mjs +244 -0
- package/src/audit.ts +144 -85
- package/src/automatic.ts +12 -2
- package/src/command-scope.ts +4 -4
- package/src/commands.ts +12 -8
- package/src/consolidation-store.ts +80 -18
- package/src/consolidation.ts +2 -6
- package/src/domain.ts +9 -4
- package/src/encoder.ts +46 -6
- package/src/file-import-store.ts +139 -0
- package/src/file-import.ts +256 -0
- package/src/foreground-attempts.ts +97 -0
- package/src/guidance.ts +138 -102
- package/src/host.ts +22 -2
- package/src/index-policy.ts +93 -46
- package/src/index.ts +87 -43
- package/src/knowledge-hooks.ts +71 -29
- package/src/knowledge.ts +2 -3
- package/src/maintenance-store.ts +37 -4
- package/src/maintenance.ts +25 -5
- package/src/personal.ts +36 -0
- package/src/policy.ts +55 -52
- package/src/prompt-copy.ts +99 -0
- package/src/proposal-receipts.ts +59 -0
- package/src/proposal-review.ts +614 -0
- package/src/propose-contract.ts +31 -35
- package/src/question-answers.ts +99 -29
- package/src/retrieval.ts +26 -9
- package/src/scope-narrowing.ts +58 -0
- package/src/search-index.ts +94 -14
- package/src/semantic.ts +67 -188
- package/src/service.ts +595 -210
- package/src/sharing.ts +7 -14
- package/src/sources.ts +26 -4
- package/src/store.ts +434 -97
- package/src/tool-experience.ts +93 -0
- package/src/turn-review-store.ts +86 -15
- package/src/turn-review.ts +142 -60
- package/src/ui.ts +122 -27
- package/src/vector-index.ts +57 -29
- package/client/index.js +0 -1186
- package/design/dsh-memory-plugin-design.md +0 -46
- package/design/dsh-memory-plugin-evaluation.md +0 -135
- package/design/evaluations/locomo-conv-26-2026-12-03.json +0 -252
- package/design/evaluations/locomo-conv-26-paired-2026-12-03.json +0 -549
- package/design/evaluations/locomo-conv-26-write-replay-2026-12-03.json +0 -289
- package/design/evaluations/project-memory-tasks-2026-12-03.json +0 -1059
- package/design/memory-lifecycle-consolidation.excalidraw +0 -1212
- package/design/memory-lifecycle-consolidation.mobile.excalidraw +0 -1083
- package/design/memory-lifecycle-consolidation.mobile.svg +0 -2
- package/design/memory-lifecycle-consolidation.mobile.zh-CN.excalidraw +0 -1083
- package/design/memory-lifecycle-consolidation.mobile.zh-CN.svg +0 -94
- package/design/memory-lifecycle-consolidation.svg +0 -2
- package/design/memory-lifecycle-consolidation.zh-CN.excalidraw +0 -1212
- package/design/memory-lifecycle-consolidation.zh-CN.svg +0 -94
- package/design/memory-lifecycle.excalidraw +0 -2105
- package/design/memory-lifecycle.mobile.excalidraw +0 -1896
- package/design/memory-lifecycle.mobile.svg +0 -95
- package/design/memory-lifecycle.mobile.zh-CN.excalidraw +0 -1896
- package/design/memory-lifecycle.mobile.zh-CN.svg +0 -97
- package/design/memory-lifecycle.svg +0 -95
- package/design/memory-lifecycle.zh-CN.excalidraw +0 -2105
- package/design/memory-lifecycle.zh-CN.svg +0 -97
- package/native/embeddings/LICENSE +0 -21
- package/native/embeddings/en/model.onnx +0 -4
- package/native/embeddings/en/vocab.txt +0 -30522
- package/native/embeddings/runtime/LICENSE +0 -21
- package/native/embeddings/runtime/ThirdPartyNotices.txt +0 -6156
- package/native/embeddings/runtime/ort-wasm-simd-threaded.mjs +0 -70
- package/native/embeddings/runtime/ort-wasm-simd-threaded.wasm +0 -0
- package/native/embeddings/runtime/ort.wasm.min.mjs +0 -7
- package/native/embeddings/worker.mjs +0 -97
- package/native/embeddings/zh/model.onnx +0 -0
- 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
|
-
|
|
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:
|
|
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(
|
|
143
|
-
(await host.get('sessionController')?.resolveAgent(
|
|
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(
|
|
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
|
-
|
|
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 (
|
|
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
|
|
187
|
-
if (readOnly && write) return failure('read_only', '当前会话处于只读模式')
|
|
188
|
-
const
|
|
189
|
-
|
|
190
|
-
|
|
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
|
-
|
|
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 (
|
|
210
|
-
|
|
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
|
|
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(
|
|
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
|
-
|
|
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 =
|
|
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'],
|
package/src/vector-index.ts
CHANGED
|
@@ -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
|
|
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(
|
|
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
|
|
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
|
|
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
|
|
181
|
+
return hits
|
|
168
182
|
}
|
|
169
183
|
|
|
170
|
-
async scores(query: string, docs: (SearchRow & { text: string })[], trace: SearchTrace) {
|
|
171
|
-
const
|
|
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
|
-
|
|
177
|
-
|
|
178
|
-
|
|
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
|
-
|
|
184
|
-
|
|
185
|
-
for (const
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
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
|
|