dsh-memu-memory 1.2.3 → 1.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +2 -1
- package/README.md +3 -15
- package/README.zh.md +3 -15
- package/docs/client-conventions.md +1 -0
- package/docs/contributing.md +1 -1
- package/docs/env-and-commands.md +48 -6
- package/docs/troubleshooting.md +41 -0
- package/lib/binding-diagnostics.js +1 -1
- package/lib/client.js +71 -10
- package/lib/embedding-catalog.js +416 -138
- package/lib/embedding-download.js +36 -11
- package/lib/inject.js +99 -3
- package/lib/local-embedding-manager.js +3 -2
- package/lib/local-embedding-protocol.js +40 -3
- package/lib/local-embedding-worker.js +36 -6
- package/lib/local-vector-service.js +18 -4
- package/lib/memu.js +15 -7
- package/lib/private.js +25 -5
- package/lib/rpc.js +4 -1
- package/lib/state.js +81 -0
- package/package.json +3 -2
- package/scripts/drive-session.mjs +19 -8
- package/scripts/simulate-injection.mjs +298 -0
- package/tests/client-render.test.mjs +56 -1
- package/tests/consolidation-fork.test.mjs +14 -1
- package/tests/drive-session.test.mjs +152 -0
- package/tests/embedding-catalog.test.mjs +116 -8
- package/tests/embedding-download.test.mjs +97 -2
- package/tests/embedding-runtime.test.mjs +21 -13
- package/tests/injection-rollback.test.mjs +230 -0
- package/tests/local-embedding-env.test.mjs +51 -0
- package/tests/local-embedding-manager.test.mjs +18 -0
- package/tests/local-embedding-protocol.test.mjs +28 -2
- package/tests/local-embedding-worker.test.mjs +94 -0
- package/tests/simulate-injection.test.mjs +76 -0
- package/tests/vector-profile.test.mjs +28 -4
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import os from 'node:os'
|
|
5
|
+
import path from 'node:path'
|
|
6
|
+
|
|
7
|
+
// §3.24 —— 宿主会把失败的整轮回滚(真机实测:连用户消息都不留在转录里),而插件在"消息交回
|
|
8
|
+
// 决策"之后就记了账。不撤销的话,guide / 锚点 / 当日纪念日 / 复提时钟这类一次性内容就永远
|
|
9
|
+
// 不再投,整段对话只是"记忆像没接上",一句错都不报。判据是本轮那几条注入消息到底进过转录没有:
|
|
10
|
+
// 进过(请求已经发出去)就保住记账,没进过才撤回。这里把撤与不撤两面都钉住。
|
|
11
|
+
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-rollback-'))
|
|
12
|
+
process.env.DSH_MEMU_HOME = home
|
|
13
|
+
|
|
14
|
+
const state = await import('../lib/state.js')
|
|
15
|
+
const inject = await import('../lib/inject.js')
|
|
16
|
+
const activity = await import('../lib/activity-log.js')
|
|
17
|
+
|
|
18
|
+
const handlers = new Map()
|
|
19
|
+
const warns = []
|
|
20
|
+
const ctx = {
|
|
21
|
+
on: (topic, handler) => { handlers.set(topic, handler); return () => {} },
|
|
22
|
+
get: () => undefined,
|
|
23
|
+
logger: { warn: (message) => warns.push(String(message)), info: () => {}, error: () => {} },
|
|
24
|
+
effect: (fn) => { try { fn() } catch {} },
|
|
25
|
+
slots: { inject: () => {} },
|
|
26
|
+
webServer: { register: () => {} },
|
|
27
|
+
}
|
|
28
|
+
inject.registerInjection(ctx)
|
|
29
|
+
const preStep = handlers.get('agent/pre-step')
|
|
30
|
+
const sessionEvent = handlers.get('session/event')
|
|
31
|
+
assert.equal(typeof preStep, 'function', 'registerInjection must expose agent/pre-step')
|
|
32
|
+
assert.equal(typeof sessionEvent, 'function', 'registerInjection must listen to session/event')
|
|
33
|
+
|
|
34
|
+
const GUIDE_RE = /<memory-guide/
|
|
35
|
+
const ANCHOR_RE = /=====\s*memory\s*anchor\s*=====/
|
|
36
|
+
const textOf = (message) => (typeof message?.content === 'string'
|
|
37
|
+
? message.content
|
|
38
|
+
: (message?.content || []).map((part) => part?.text || '').join(''))
|
|
39
|
+
const countWith = (messages, re) => messages.filter((message) => re.test(textOf(message))).length
|
|
40
|
+
const user = (n, text) => ({ id: `u-${n}`, role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text }] })
|
|
41
|
+
const assistant = (n, text) => ({ id: `a-${n}`, role: 'assistant', content: [{ type: 'text', text }] })
|
|
42
|
+
|
|
43
|
+
function makeSession(id) {
|
|
44
|
+
const cwd = path.join(home, id)
|
|
45
|
+
const binding = state.ensureSession(id, { cwd, agentPreset: 'coding' })
|
|
46
|
+
state.setSessionBinding(id, { useLibrary: true, useGlobal: false })
|
|
47
|
+
const now = new Date().toISOString()
|
|
48
|
+
state.updatePrivateIndex(binding.libraryId, (index) => {
|
|
49
|
+
for (let i = 1; i <= 3; i += 1) {
|
|
50
|
+
index.entries[`mem-${id}-${i}`] = {
|
|
51
|
+
id: `mem-${id}-${i}`, track: 'memory', layer: 'long_term', status: 'active',
|
|
52
|
+
title: `林眠的相机镜头跑焦维修进度 ${i}`,
|
|
53
|
+
content: `林眠的相机镜头送修,报价与工期记录在第 ${i} 条。`,
|
|
54
|
+
visibility: 'shared', disclosure: 'can_tell', owner: 'me',
|
|
55
|
+
createdAt: now, updatedAt: now,
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
})
|
|
59
|
+
return { id, cwd }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function step(session, turn, messages) {
|
|
63
|
+
const out = await preStep({
|
|
64
|
+
agent: { session: { header: { id: session.id, cwd: session.cwd, agentPreset: 'coding', origin: 'user' } } },
|
|
65
|
+
turn, step: 1, signal: { aborted: false },
|
|
66
|
+
}, async () => ({ kind: 'enter', messages }))
|
|
67
|
+
return out?.messages || messages
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function failTurn(session, turn) {
|
|
71
|
+
return sessionEvent(
|
|
72
|
+
{ header: { id: session.id } },
|
|
73
|
+
{ type: 'turn/end', data: { turn, reason: { kind: 'error', error: { message: 'llm unreachable' } } } },
|
|
74
|
+
)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function completeTurn(session, turn) {
|
|
78
|
+
return sessionEvent({ header: { id: session.id } }, { type: 'turn/end', data: { turn, reason: { kind: 'completed' } } })
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const facts = (id) => {
|
|
82
|
+
const binding = state.getSessionBinding(id) || {}
|
|
83
|
+
return {
|
|
84
|
+
guide: binding.guideRulesKey || null,
|
|
85
|
+
anchor: (binding.injectedIds || []).includes(inject.ANCHOR_SENTINEL),
|
|
86
|
+
rollback: binding.injectionRollback || null,
|
|
87
|
+
injected: (binding.injectedIds || []).filter((entry) => entry !== inject.ANCHOR_SENTINEL).length,
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
test('a failed turn gives back the one-shot accounting, and the next turn re-places it', async () => {
|
|
92
|
+
const session = makeSession('rb-err')
|
|
93
|
+
const first = await step(session, 1, [user(1, '林眠的相机镜头修好了吗')])
|
|
94
|
+
assert.equal(countWith(first, GUIDE_RE), 1, 'turn 1 places the guide')
|
|
95
|
+
assert.equal(countWith(first, ANCHOR_RE), 1, 'turn 1 places the anchor')
|
|
96
|
+
const placed = facts(session.id)
|
|
97
|
+
assert.ok(placed.guide && placed.anchor && placed.injected > 0, 'the accounting says everything was delivered')
|
|
98
|
+
|
|
99
|
+
await failTurn(session, 1)
|
|
100
|
+
const rolled = facts(session.id)
|
|
101
|
+
assert.equal(rolled.guide, null, 'guide key rolled back')
|
|
102
|
+
assert.equal(rolled.anchor, false, 'anchor sentinel rolled back')
|
|
103
|
+
assert.equal(rolled.injected, 0, 'the recall ids of that turn are forgotten too')
|
|
104
|
+
assert.equal(rolled.rollback, null, 'the rollback record is consumed, not left to age')
|
|
105
|
+
assert.ok(warns.some((line) => /rolled back injection accounting/.test(line)), 'the rollback leaves a log signal')
|
|
106
|
+
const events = activity.listEvents({ limit: 50, kind: 'system' })
|
|
107
|
+
assert.ok(events.some((event) => event.sessionId === session.id && /已撤回本轮的注入记账/.test(event.message || '')),
|
|
108
|
+
'and an activity-log row explains what happened')
|
|
109
|
+
|
|
110
|
+
// 下一轮:宿主给的转录里没有任何一次性的东西,必须重新投出来。
|
|
111
|
+
const second = await step(session, 2, [user(1, '林眠的相机镜头修好了吗'), user(2, '那维修报价给了吗')])
|
|
112
|
+
assert.equal(countWith(second, GUIDE_RE), 1, 'the guide comes back')
|
|
113
|
+
assert.equal(countWith(second, ANCHOR_RE), 1, 'the anchor comes back')
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
test('a completed turn keeps its accounting, so nothing is re-placed', async () => {
|
|
117
|
+
const session = makeSession('rb-ok')
|
|
118
|
+
const first = await step(session, 1, [user(1, '林眠的相机镜头修好了吗')])
|
|
119
|
+
assert.equal(countWith(first, GUIDE_RE), 1)
|
|
120
|
+
await completeTurn(session, 1)
|
|
121
|
+
|
|
122
|
+
const kept = facts(session.id)
|
|
123
|
+
assert.ok(kept.guide, 'a completed turn must not forget the guide key')
|
|
124
|
+
assert.equal(kept.anchor, true, 'nor the anchor sentinel')
|
|
125
|
+
|
|
126
|
+
const view = [...first, assistant(1, '还在修。'), user(2, '林眠镜头跑焦的工期多久')]
|
|
127
|
+
const second = await step(session, 2, view)
|
|
128
|
+
assert.equal(countWith(second, GUIDE_RE), 1, 'the guide stays single-copy')
|
|
129
|
+
assert.equal(countWith(second, ANCHOR_RE), 1, 'the anchor is not repeated')
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
test('a completed turn consumes its record, so a late error cannot un-place what is already in the transcript', async () => {
|
|
133
|
+
const session = makeSession('rb-stale')
|
|
134
|
+
const first = await step(session, 1, [user(1, '林眠的相机镜头修好了吗')])
|
|
135
|
+
assert.equal(countWith(first, GUIDE_RE), 1)
|
|
136
|
+
assert.ok(facts(session.id).rollback, 'the turn that just delivered leaves a rollback record')
|
|
137
|
+
|
|
138
|
+
await completeTurn(session, 1)
|
|
139
|
+
const kept = facts(session.id)
|
|
140
|
+
assert.equal(kept.rollback, null, 'a completed turn consumes the record')
|
|
141
|
+
assert.ok(kept.guide, 'its guide key stays')
|
|
142
|
+
assert.equal(kept.anchor, true, 'and so does the anchor sentinel')
|
|
143
|
+
|
|
144
|
+
// 迟到的 error 事件不能再撤回已经落在转录里的那一份,否则下一轮就凭空多出第二条规则消息/锚点。
|
|
145
|
+
await failTurn(session, 1)
|
|
146
|
+
const after = facts(session.id)
|
|
147
|
+
assert.ok(after.guide, 'the late error does not forget the guide key')
|
|
148
|
+
assert.equal(after.anchor, true, 'nor re-arm the anchor')
|
|
149
|
+
assert.equal(after.injected, kept.injected, 'the recall ids of that turn stay accounted')
|
|
150
|
+
|
|
151
|
+
const warnBefore = warns.length
|
|
152
|
+
const second = await step(session, 2, [...first, assistant(1, '还在修。'), user(2, '维修报价给了吗')])
|
|
153
|
+
assert.equal(countWith(second, GUIDE_RE), 1, 'no second rules message')
|
|
154
|
+
assert.equal(countWith(second, ANCHOR_RE), 1, 'no second anchor')
|
|
155
|
+
assert.equal(warns.slice(warnBefore).filter((line) => /rolled back injection accounting/.test(line)).length, 0,
|
|
156
|
+
'and nothing was rolled back along the way')
|
|
157
|
+
})
|
|
158
|
+
|
|
159
|
+
test('a failure after the injection reached the transcript keeps the accounting', async () => {
|
|
160
|
+
const session = makeSession('rb-admitted')
|
|
161
|
+
const first = await step(session, 1, [user(1, '林眠的相机镜头修好了吗')])
|
|
162
|
+
const injected = first.find((message) => message?.source?.kind === 'plugin:dsh-memu-memory')
|
|
163
|
+
assert.ok(injected?.id, 'the turn produced an identified injection message')
|
|
164
|
+
|
|
165
|
+
// 宿主在第一次尝试里就把 decision.messages 逐条追加进转录,之后才连模型。上游 500 / 超时
|
|
166
|
+
// 属于这一类:内容已经在转录里,撤回记账只会让下一轮多出第二份规则消息与锚点。
|
|
167
|
+
await sessionEvent({ header: { id: session.id } }, { type: 'user/message', data: injected })
|
|
168
|
+
await failTurn(session, 1)
|
|
169
|
+
const kept = facts(session.id)
|
|
170
|
+
assert.ok(kept.guide, 'the rules message stays accounted')
|
|
171
|
+
assert.equal(kept.anchor, true, 'and so does the anchor')
|
|
172
|
+
assert.equal(kept.rollback, null, 'the record is consumed instead of rolled back')
|
|
173
|
+
|
|
174
|
+
const warnBefore = warns.length
|
|
175
|
+
const second = await step(session, 2, [...first, user(2, '维修报价给了吗')])
|
|
176
|
+
assert.equal(countWith(second, GUIDE_RE), 1, 'no second rules message')
|
|
177
|
+
assert.equal(countWith(second, ANCHOR_RE), 1, 'no second anchor')
|
|
178
|
+
assert.equal(warns.slice(warnBefore).filter((line) => /rolled back injection accounting/.test(line)).length, 0,
|
|
179
|
+
'nothing was rolled back along the way')
|
|
180
|
+
})
|
|
181
|
+
|
|
182
|
+
test('a cancel before the messages were appended also gives the accounting back', async () => {
|
|
183
|
+
const session = makeSession('rb-abort')
|
|
184
|
+
const first = await step(session, 1, [user(1, '林眠的相机镜头修好了吗')])
|
|
185
|
+
assert.equal(countWith(first, ANCHOR_RE), 1)
|
|
186
|
+
|
|
187
|
+
// 用户在模型调用之前就按了停止:转录里什么都没有,aborted 同样该把记账还回来。
|
|
188
|
+
await sessionEvent({ header: { id: session.id } }, {
|
|
189
|
+
type: 'turn/end', data: { turn: 1, reason: { kind: 'aborted', reason: 'user stop' } },
|
|
190
|
+
})
|
|
191
|
+
const after = facts(session.id)
|
|
192
|
+
assert.equal(after.guide, null, '取消发生在投放之前:一次性内容还没有落进转录')
|
|
193
|
+
assert.equal(after.anchor, false)
|
|
194
|
+
|
|
195
|
+
const again = await step(session, 2, [user(1, '林眠的相机镜头修好了吗')])
|
|
196
|
+
assert.equal(countWith(again, ANCHOR_RE), 1, 'the anchor is placed again next turn')
|
|
197
|
+
})
|
|
198
|
+
|
|
199
|
+
test('rollback also clears the day marks so dated blocks can return', async () => {
|
|
200
|
+
const session = makeSession('rb-dated')
|
|
201
|
+
const now = Date.now()
|
|
202
|
+
const iso = (offsetDays) => new Date(now + offsetDays * 86400000).toISOString()
|
|
203
|
+
const day = (offset) => {
|
|
204
|
+
const value = new Date(now + offset * 86400000)
|
|
205
|
+
return `${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, '0')}-${String(value.getDate()).padStart(2, '0')}`
|
|
206
|
+
}
|
|
207
|
+
state.updatePrivateIndex(state.getSessionBinding(session.id).libraryId, (index) => {
|
|
208
|
+
index.entries['mem-rb-dated-lost'] = {
|
|
209
|
+
id: 'mem-rb-dated-lost', track: 'memory', layer: 'long_term', status: 'active',
|
|
210
|
+
title: '明天要把镜头还给林眠', content: '说明天在城南咖啡店把镜头还给林眠。',
|
|
211
|
+
salientDate: day(1), openLoop: true, visibility: 'shared', disclosure: 'can_tell', owner: 'me',
|
|
212
|
+
createdAt: iso(-2), updatedAt: iso(-2),
|
|
213
|
+
}
|
|
214
|
+
index.entries['mem-rb-dated-loop'] = {
|
|
215
|
+
id: 'mem-rb-dated-loop', track: 'memory', layer: 'long_term', status: 'active',
|
|
216
|
+
title: '答应给林眠带咖啡豆', content: '一直没做,也没有约定日期。',
|
|
217
|
+
openLoop: true, visibility: 'shared', disclosure: 'can_tell', owner: 'me',
|
|
218
|
+
createdAt: iso(-5), updatedAt: iso(-5),
|
|
219
|
+
}
|
|
220
|
+
})
|
|
221
|
+
|
|
222
|
+
await step(session, 1, [user(1, '明天有什么我要办的事')])
|
|
223
|
+
const binding = state.getSessionBinding(session.id)
|
|
224
|
+
assert.ok(Object.keys(binding.anniversariesShown || {}).length > 0 || (binding.injectedIds || []).length > 1,
|
|
225
|
+
'the dated blocks recorded their own clocks on that turn')
|
|
226
|
+
await failTurn(session, 1)
|
|
227
|
+
const after = state.getSessionBinding(session.id)
|
|
228
|
+
assert.equal(Object.keys(after.anniversariesShown || {}).length, 0, 'the day mark is withdrawn with the turn')
|
|
229
|
+
assert.equal(Object.keys(after.openLoopRemindedAt || {}).length, 0, 'and so is the re-reminder clock')
|
|
230
|
+
})
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import os from 'node:os'
|
|
5
|
+
import path from 'node:path'
|
|
6
|
+
|
|
7
|
+
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-env-'))
|
|
8
|
+
process.env.DSH_MEMU_MEMORY_HOME = home
|
|
9
|
+
|
|
10
|
+
const { localEmbeddingEnv } = await import('../lib/memu.js')
|
|
11
|
+
|
|
12
|
+
test.after(() => fs.rmSync(home, { recursive: true, force: true }))
|
|
13
|
+
|
|
14
|
+
const E5 = 'multilingual-e5-small@252d0dcb679dda2c7b6fd5bbfed15df3c7feaebf+dsh-local-embedding-v1'
|
|
15
|
+
const BGE = 'bge-small-zh-v1.5-int8@313386ad7ffad360a4870fd1910f8ecaf1a05151+dsh-local-embedding-v1'
|
|
16
|
+
const BASE = 'http://127.0.0.1:45123/v1'
|
|
17
|
+
const TOKEN = 'worker-token-0123456789abcdef'
|
|
18
|
+
|
|
19
|
+
// §14.4:MemU 的请求信封里没有角色字段,所以「这条文本是查询还是条目」只能由启动子进程的
|
|
20
|
+
// 插件来说——它写在 model 字符串上,由 worker 解析回来。
|
|
21
|
+
test('the role the plugin knows rides on the model string MemU echoes back', () => {
|
|
22
|
+
const query = localEmbeddingEnv({ baseUrl: BASE, token: TOKEN, model: E5, rolesRequired: true, role: 'query', db: 'C:/x/global.sqlite3' })
|
|
23
|
+
assert.equal(query.MEMU_EMBED_MODEL, E5 + ':query')
|
|
24
|
+
const document = localEmbeddingEnv({ baseUrl: BASE, token: TOKEN, model: E5, rolesRequired: true, role: 'document' })
|
|
25
|
+
assert.equal(document.MEMU_EMBED_MODEL, E5 + ':passage')
|
|
26
|
+
// 未知角色也只能落在文档读法上,不能悄悄变成查询读法
|
|
27
|
+
assert.equal(localEmbeddingEnv({ baseUrl: BASE, token: TOKEN, model: E5, rolesRequired: true }).MEMU_EMBED_MODEL, E5 + ':passage')
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
test('a model with one prefix for both sides keeps the byte-identical model string', () => {
|
|
31
|
+
for (const role of [undefined, 'query', 'document']) {
|
|
32
|
+
assert.equal(
|
|
33
|
+
localEmbeddingEnv({ baseUrl: BASE, token: TOKEN, model: BGE, rolesRequired: false, role }).MEMU_EMBED_MODEL,
|
|
34
|
+
BGE,
|
|
35
|
+
'BGE/MiniLM must not pick up a role suffix',
|
|
36
|
+
)
|
|
37
|
+
}
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
test('the strict-local envelope is unchanged: loopback base, token as key, telemetry off', () => {
|
|
41
|
+
const env = localEmbeddingEnv({ baseUrl: BASE, token: TOKEN, model: BGE, db: 'C:/x/global.sqlite3' })
|
|
42
|
+
assert.equal(env.MEMU_MEMORY_MODE, 'local')
|
|
43
|
+
assert.equal(env.MEMU_EMBED_PROVIDER, 'openai')
|
|
44
|
+
assert.equal(env.MEMU_TELEMETRY, '0')
|
|
45
|
+
assert.equal(env.DO_NOT_TRACK, '1')
|
|
46
|
+
assert.equal(env.MEMU_EVENTS_BASE_URL, '')
|
|
47
|
+
assert.equal(env.MEMU_BASE_URL, BASE)
|
|
48
|
+
assert.equal(env.MEMU_API_KEY, TOKEN, 'the loopback token is the only credential this env can carry')
|
|
49
|
+
assert.equal(env.MEMU_DB, 'C:/x/global.sqlite3')
|
|
50
|
+
assert.equal(Object.keys(env).filter(name => /PROXY/i.test(name)).length, 0)
|
|
51
|
+
})
|
|
@@ -308,6 +308,24 @@ test('an EPIPE on the worker pipes degrades recall instead of crashing the host'
|
|
|
308
308
|
assert.doesNotThrow(() => manager.close())
|
|
309
309
|
})
|
|
310
310
|
|
|
311
|
+
test('the endpoint tells the caller whether roles must be named, derived from the manifest prefixes', async () => {
|
|
312
|
+
const cases = [
|
|
313
|
+
{ prefixes: undefined, expected: false },
|
|
314
|
+
{ prefixes: { query: '', document: '' }, expected: false },
|
|
315
|
+
{ prefixes: { query: 'query: ', document: 'passage: ' }, expected: true },
|
|
316
|
+
]
|
|
317
|
+
for (const item of cases) {
|
|
318
|
+
const { spawnImpl, children } = fakeSpawn()
|
|
319
|
+
const manager = makeManager({ spawnImpl })
|
|
320
|
+
const profile = Object.freeze({ ...PROFILE, manifest: Object.freeze({ ...PROFILE.manifest, prefixes: item.prefixes }) })
|
|
321
|
+
const pending = manager.acquire(profile)
|
|
322
|
+
push(children[0], readyLine())
|
|
323
|
+
const endpoint = await pending
|
|
324
|
+
assert.equal(endpoint.rolesRequired, item.expected, JSON.stringify(item.prefixes))
|
|
325
|
+
manager.close()
|
|
326
|
+
}
|
|
327
|
+
})
|
|
328
|
+
|
|
311
329
|
test('ambient proxies and remote credentials never reach the worker', async () => {
|
|
312
330
|
const ambient = {
|
|
313
331
|
HTTP_PROXY: 'http://127.0.0.1:7890',
|
|
@@ -2,6 +2,7 @@ import test from 'node:test'
|
|
|
2
2
|
import assert from 'node:assert/strict'
|
|
3
3
|
import {
|
|
4
4
|
DEFAULT_MAX_BATCH,
|
|
5
|
+
ROLE_SUFFIXES,
|
|
5
6
|
LocalEmbeddingError,
|
|
6
7
|
assertVector,
|
|
7
8
|
buildEmbeddingResponse,
|
|
@@ -10,7 +11,9 @@ import {
|
|
|
10
11
|
errorBody,
|
|
11
12
|
errorStatus,
|
|
12
13
|
estimateUsage,
|
|
14
|
+
modelIdForRole,
|
|
13
15
|
parseEmbeddingRequest,
|
|
16
|
+
splitModelRole,
|
|
14
17
|
} from '../lib/local-embedding-protocol.js'
|
|
15
18
|
|
|
16
19
|
const MODEL = 'bge-small-zh-v1.5@r1+mean-l2-512'
|
|
@@ -44,8 +47,8 @@ test('vectors must be finite, non-zero and exactly the manifest dimension', () =
|
|
|
44
47
|
})
|
|
45
48
|
|
|
46
49
|
test('the request parser accepts exactly the SDK shapes and refuses the rest', () => {
|
|
47
|
-
assert.deepEqual(parseEmbeddingRequest({ model: MODEL, input: 'hello' }, { model: MODEL }), { inputs: ['hello'], encoding: 'float' })
|
|
48
|
-
assert.deepEqual(parseEmbeddingRequest({ model: MODEL, input: ['a', 'b'], encoding_format: 'base64' }, { model: MODEL }), { inputs: ['a', 'b'], encoding: 'base64' })
|
|
50
|
+
assert.deepEqual(parseEmbeddingRequest({ model: MODEL, input: 'hello' }, { model: MODEL }), { inputs: ['hello'], encoding: 'float', role: 'document' })
|
|
51
|
+
assert.deepEqual(parseEmbeddingRequest({ model: MODEL, input: ['a', 'b'], encoding_format: 'base64' }, { model: MODEL }), { inputs: ['a', 'b'], encoding: 'base64', role: 'document' })
|
|
49
52
|
rejects(() => parseEmbeddingRequest(null, { model: MODEL }), /^LOCAL_VECTOR_BAD_REQUEST$/)
|
|
50
53
|
rejects(() => parseEmbeddingRequest([], { model: MODEL }), /^LOCAL_VECTOR_BAD_REQUEST$/)
|
|
51
54
|
rejects(() => parseEmbeddingRequest({ input: 'hello' }, { model: MODEL }), /^LOCAL_VECTOR_BAD_REQUEST$/)
|
|
@@ -59,6 +62,29 @@ test('the request parser accepts exactly the SDK shapes and refuses the rest', (
|
|
|
59
62
|
rejects(() => parseEmbeddingRequest({ model: MODEL, input: 'x'.repeat(65_537) }, { model: MODEL }), /^LOCAL_VECTOR_INPUT_TOO_LONG$/)
|
|
60
63
|
})
|
|
61
64
|
|
|
65
|
+
// §14.4: a model that reads query and document differently must be told which one it
|
|
66
|
+
// is getting. MemU's envelope has no role field, so the role rides on the model string
|
|
67
|
+
// the plugin injects — and a bare id must be refused, never defaulted.
|
|
68
|
+
test('the role travels on the model string and a role-less request is refused when roles matter', () => {
|
|
69
|
+
assert.equal(modelIdForRole(MODEL, 'query'), MODEL + ':query')
|
|
70
|
+
assert.equal(modelIdForRole(MODEL, 'document'), MODEL + ':passage')
|
|
71
|
+
assert.deepEqual(splitModelRole(MODEL + ':query'), { model: MODEL, role: 'query' })
|
|
72
|
+
assert.deepEqual(splitModelRole(MODEL + ':passage'), { model: MODEL, role: 'document' })
|
|
73
|
+
assert.deepEqual(splitModelRole(MODEL), { model: MODEL, role: null })
|
|
74
|
+
|
|
75
|
+
const query = parseEmbeddingRequest({ model: modelIdForRole(MODEL, 'query'), input: '她怕什么' }, { model: MODEL, rolesRequired: true })
|
|
76
|
+
assert.deepEqual(query, { inputs: ['她怕什么'], encoding: 'float', role: 'query' })
|
|
77
|
+
const passage = parseEmbeddingRequest({ model: modelIdForRole(MODEL, 'document'), input: '林夏害怕打雷' }, { model: MODEL, rolesRequired: true })
|
|
78
|
+
assert.equal(passage.role, 'document')
|
|
79
|
+
rejects(() => parseEmbeddingRequest({ model: MODEL, input: '她怕什么' }, { model: MODEL, rolesRequired: true }), /^LOCAL_VECTOR_ROLE_REQUIRED$/)
|
|
80
|
+
// 后缀不能拿来冒充另一个模型
|
|
81
|
+
rejects(() => parseEmbeddingRequest({ model: 'other' + ROLE_SUFFIXES.query, input: 'x' }, { model: MODEL, rolesRequired: true }), /^LOCAL_VECTOR_MODEL_MISMATCH$/)
|
|
82
|
+
|
|
83
|
+
// 一个前缀两边相同的模型没有角色可言:裸 id 保持原来的行为
|
|
84
|
+
assert.equal(parseEmbeddingRequest({ model: MODEL, input: 'x' }, { model: MODEL }).role, 'document')
|
|
85
|
+
assert.equal(parseEmbeddingRequest({ model: modelIdForRole(MODEL, 'query'), input: 'x' }, { model: MODEL }).role, 'query')
|
|
86
|
+
})
|
|
87
|
+
|
|
62
88
|
test('the batch cap is enforced before any inference happens', () => {
|
|
63
89
|
const many = new Array(DEFAULT_MAX_BATCH + 1).fill('x')
|
|
64
90
|
rejects(() => parseEmbeddingRequest({ model: MODEL, input: many }, { model: MODEL }), /^LOCAL_VECTOR_BATCH_TOO_LARGE$/)
|
|
@@ -4,6 +4,7 @@ import fs from 'node:fs'
|
|
|
4
4
|
import http from 'node:http'
|
|
5
5
|
import os from 'node:os'
|
|
6
6
|
import path from 'node:path'
|
|
7
|
+
import { pathToFileURL } from 'node:url'
|
|
7
8
|
import {
|
|
8
9
|
createOnnxAdapter,
|
|
9
10
|
manifestDimension,
|
|
@@ -213,6 +214,62 @@ test('auth, origin, host, method, content type and JSON failures are all refused
|
|
|
213
214
|
}
|
|
214
215
|
})
|
|
215
216
|
|
|
217
|
+
// last-token pooling 是新写的算术(因果 LM 取最后一个非 pad token),所以拿假的
|
|
218
|
+
// ORT/tokenizer 树把它钉住:同一份 hidden state 下,cls / mean / last 必须各自算对,
|
|
219
|
+
// 且 padding 不参与 last 的定位。
|
|
220
|
+
test('last-token pooling picks the last unmasked token, not the last row', async () => {
|
|
221
|
+
const hidden = [
|
|
222
|
+
[1, 0],
|
|
223
|
+
[0, 2],
|
|
224
|
+
[3, 1],
|
|
225
|
+
[7, 7],
|
|
226
|
+
]
|
|
227
|
+
const mask = [1, 1, 1, 0]
|
|
228
|
+
const ortFile = path.join(modelDir, 'fake-ort.mjs')
|
|
229
|
+
const tokFile = path.join(modelDir, 'fake-tokenizers.mjs')
|
|
230
|
+
fs.writeFileSync(ortFile, [
|
|
231
|
+
'export class Tensor { constructor(type, data, dims) { this.type = type; this.data = data; this.dims = dims } }',
|
|
232
|
+
'export class InferenceSession {',
|
|
233
|
+
' static async create() { return new InferenceSession() }',
|
|
234
|
+
' constructor() { this.inputNames = [\'input_ids\', \'attention_mask\']; this.outputNames = [\'last_hidden_state\'] }',
|
|
235
|
+
' async run() { return { last_hidden_state: { dims: [1, 4, 2], data: [' + hidden.map(row => row.join(',')).join(',') + '] } } }',
|
|
236
|
+
' async release() {}',
|
|
237
|
+
'}',
|
|
238
|
+
'',
|
|
239
|
+
].join('\n'), 'utf8')
|
|
240
|
+
fs.writeFileSync(tokFile, [
|
|
241
|
+
'export class Tokenizer {',
|
|
242
|
+
' static fromFile() { return new Tokenizer() }',
|
|
243
|
+
' async encode() { return { getIds: () => [1, 2, 3, 0], getAttentionMask: () => [' + mask.join(',') + '], getTypeIds: () => [0, 0, 0, 0] } }',
|
|
244
|
+
'}',
|
|
245
|
+
'',
|
|
246
|
+
].join('\n'), 'utf8')
|
|
247
|
+
fs.writeFileSync(path.join(modelDir, 'model.onnx'), 'fake graph bytes', 'utf8')
|
|
248
|
+
fs.writeFileSync(path.join(modelDir, 'tokenizer.json'), '{}', 'utf8')
|
|
249
|
+
const ortUrl = pathToFileURL(ortFile).href
|
|
250
|
+
const tokUrl = pathToFileURL(tokFile).href
|
|
251
|
+
const expectations = {
|
|
252
|
+
cls: [1, 0],
|
|
253
|
+
mean: [4 / 3, 1].map(value => value / Math.hypot(4 / 3, 1)),
|
|
254
|
+
last: [3, 1].map(value => value / Math.hypot(3, 1)),
|
|
255
|
+
}
|
|
256
|
+
for (const pooling of ['cls', 'mean', 'last']) {
|
|
257
|
+
const adapter = await createOnnxAdapter({
|
|
258
|
+
modelDir,
|
|
259
|
+
manifest: manifest({ pooling, dimension: 2, maxTokens: 8 }),
|
|
260
|
+
runtimeDir: modelDir,
|
|
261
|
+
runtimeModule: ortUrl,
|
|
262
|
+
tokenizerModule: tokUrl,
|
|
263
|
+
})
|
|
264
|
+
const [vector] = await adapter.encode(['任何文本'])
|
|
265
|
+
assert.equal(vector.length, 2, pooling)
|
|
266
|
+
vector.forEach((value, index) => assert.ok(Math.abs(value - expectations[pooling][index]) < 1e-9, `${pooling}[${index}] got ${value}`))
|
|
267
|
+
const norm = Math.sqrt(vector.reduce((sum, item) => sum + item * item, 0))
|
|
268
|
+
assert.ok(Math.abs(norm - 1) < 1e-9, pooling + ' must stay L2 normalised')
|
|
269
|
+
await adapter.close()
|
|
270
|
+
}
|
|
271
|
+
})
|
|
272
|
+
|
|
216
273
|
test('an unknown model is refused instead of being served by the loaded weights', async () => {
|
|
217
274
|
const { worker, adapter } = await fixture()
|
|
218
275
|
try {
|
|
@@ -225,6 +282,43 @@ test('an unknown model is refused instead of being served by the loaded weights'
|
|
|
225
282
|
}
|
|
226
283
|
})
|
|
227
284
|
|
|
285
|
+
// §14.4:前缀是模型自己的事实,所以由 worker 施加;两种读法不同的模型,绝不能被一个
|
|
286
|
+
// 没说角色的请求「默认」成某一种——默认错了一边,向量空间就错了而 HTTP 还是 200。
|
|
287
|
+
test('query/document prefixes come from the manifest and a role-less request is refused when they differ', async () => {
|
|
288
|
+
const asymmetric = fakeAdapter()
|
|
289
|
+
const { worker } = await fixture({ adapter: asymmetric, manifest: manifest({ prefixes: { query: 'query: ', document: 'passage: ' } }) })
|
|
290
|
+
try {
|
|
291
|
+
const bare = await post(worker, { model: MODEL, input: ['她怕打雷'] })
|
|
292
|
+
assert.equal(bare.status, 400)
|
|
293
|
+
assert.equal(bare.body.error.code, 'LOCAL_VECTOR_ROLE_REQUIRED')
|
|
294
|
+
assert.deepEqual(asymmetric.calls, [['embedding readiness probe']], 'a refused role must not reach inference')
|
|
295
|
+
|
|
296
|
+
const query = await post(worker, { model: MODEL + ':query', input: ['她怕打雷'] })
|
|
297
|
+
const passage = await post(worker, { model: MODEL + ':passage', input: ['她怕打雷'] })
|
|
298
|
+
assert.equal(query.status, 200)
|
|
299
|
+
assert.equal(passage.status, 200)
|
|
300
|
+
assert.deepEqual(asymmetric.calls.slice(1), [['query: 她怕打雷'], ['passage: 她怕打雷']])
|
|
301
|
+
assert.notEqual(JSON.stringify(query.body.data[0].embedding), JSON.stringify(passage.body.data[0].embedding))
|
|
302
|
+
|
|
303
|
+
const health = await (await fetch(worker.healthUrl, { headers: auth })).json()
|
|
304
|
+
assert.equal(health.rolesRequired, true)
|
|
305
|
+
} finally {
|
|
306
|
+
await worker.close()
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// 两边同一个前缀(BGE/MiniLM 就是这种):裸 model id 的字节级行为保持不变。
|
|
310
|
+
const symmetric = fakeAdapter()
|
|
311
|
+
const same = await fixture({ adapter: symmetric, manifest: manifest({ prefixes: { query: '', document: '' } }) })
|
|
312
|
+
try {
|
|
313
|
+
const bare = await post(same.worker, { model: MODEL, input: ['她怕打雷'] })
|
|
314
|
+
assert.equal(bare.status, 200)
|
|
315
|
+
assert.deepEqual(symmetric.calls, [['embedding readiness probe'], ['她怕打雷']])
|
|
316
|
+
assert.equal((await (await fetch(same.worker.healthUrl, { headers: auth })).json()).rolesRequired, false)
|
|
317
|
+
} finally {
|
|
318
|
+
await same.worker.close()
|
|
319
|
+
}
|
|
320
|
+
})
|
|
321
|
+
|
|
228
322
|
test('body and batch limits are enforced before inference', async () => {
|
|
229
323
|
const { worker, adapter } = await fixture({ maxBatch: 2, maxBodyBytes: 256 })
|
|
230
324
|
try {
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import os from 'node:os'
|
|
5
|
+
import path from 'node:path'
|
|
6
|
+
import { fileURLToPath } from 'node:url'
|
|
7
|
+
import { execFileSync } from 'node:child_process'
|
|
8
|
+
|
|
9
|
+
// 工单 B 的离线模拟器本身也要有回归:它一旦失真,报告里的数字就全成了装饰。
|
|
10
|
+
// 这里钉的是"量具的正确属性",不是某一次的注入次数(那个随设置与播种变化)。
|
|
11
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
|
12
|
+
const REPO = path.resolve(HERE, '..')
|
|
13
|
+
const SCRIPT = path.join(REPO, 'scripts', 'simulate-injection.mjs')
|
|
14
|
+
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-sim-test-'))
|
|
15
|
+
|
|
16
|
+
const run = (args) => execFileSync(process.execPath, [SCRIPT, ...args], {
|
|
17
|
+
cwd: REPO,
|
|
18
|
+
encoding: 'utf8',
|
|
19
|
+
env: { ...process.env, DSH_MEMU_HOME: path.join(home, 'memu'), DSH_MEMU_MEMORY_HOME: path.join(home, 'memu') },
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
test.after(() => {
|
|
23
|
+
try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
test('the simulator measures what the injection pipeline put in each request', () => {
|
|
27
|
+
const out = path.join(home, 'run-6')
|
|
28
|
+
const summary = JSON.parse(run(['--turns', '6', '--json', '--out', out, '--home', path.join(home, 'home-6')]))
|
|
29
|
+
|
|
30
|
+
assert.equal(summary.turns, 6)
|
|
31
|
+
assert.equal(summary.warnCount, 0, 'a warn means the pipeline itself complained: that is a failure, not noise')
|
|
32
|
+
assert.equal(summary.sendFailures, 0)
|
|
33
|
+
// 规则 guide 只在首回合投放一次,靠的就是"转录里带着之前发过的插件消息"。
|
|
34
|
+
// 若驱动把历史丢掉,这里会变成 6 而不是 1。
|
|
35
|
+
assert.equal(summary.deltaTotals.guide, 1, 'the rules guide is placed once, not per turn')
|
|
36
|
+
assert.equal(summary.deltaTotals.anchor, 1, 'the anchor lands on the first turn only')
|
|
37
|
+
assert.ok(summary.deltaTotals.context >= 1, 'per-turn recall title cards are counted')
|
|
38
|
+
// 标题卡口径:正文不许混进 prompt。
|
|
39
|
+
assert.equal(summary.titleCardBodyLineMax, 0, 'title cards must not carry body continuation lines')
|
|
40
|
+
|
|
41
|
+
const report = fs.readFileSync(summary.reportPath, 'utf8')
|
|
42
|
+
assert.match(report, /## Per-request marker matrix/)
|
|
43
|
+
assert.match(report, /## Totals by block/)
|
|
44
|
+
assert.match(report, /## Zero-injection requests/)
|
|
45
|
+
assert.match(report, /marker set: plugin \d+\.\d+\.\d+/, 'the report names the pinned marker set')
|
|
46
|
+
|
|
47
|
+
// 隐私面:日志只有元数据。正文与标题词一旦落进 jsonl,这台量具就成了窃听器。
|
|
48
|
+
const jsonl = fs.readFileSync(summary.logPath, 'utf8')
|
|
49
|
+
assert.ok(jsonl.length > 0)
|
|
50
|
+
assert.ok(!jsonl.includes('的正文'), 'request bodies must never reach the log')
|
|
51
|
+
assert.ok(!jsonl.includes('林眠'), 'memory titles must never reach the log')
|
|
52
|
+
|
|
53
|
+
const snapshot = JSON.parse(fs.readFileSync(summary.snapshotPath, 'utf8'))
|
|
54
|
+
assert.equal(typeof snapshot.settings.freshnessDays, 'number', 'the snapshot is the reading context for C/D knobs')
|
|
55
|
+
assert.equal(typeof snapshot.settings.openLoopRemindDays, 'number')
|
|
56
|
+
assert.equal(snapshot.settings.salientWake, 'off', 'the simulator never turns on host wake-up')
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
test('a zero cue chance is the reproducible default and --cue can restore the shipped one', () => {
|
|
60
|
+
const summary = JSON.parse(run(['--turns', '4', '--json', '--out', path.join(home, 'run-cue'), '--home', path.join(home, 'home-cue')]))
|
|
61
|
+
const snapshot = JSON.parse(fs.readFileSync(summary.snapshotPath, 'utf8'))
|
|
62
|
+
assert.equal(snapshot.settings.randomCueChance, 0, 'random side-events are off by default so totals are reproducible')
|
|
63
|
+
assert.equal(summary.deltaTotals.cue, 0)
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
test('usage errors exit 2 and never write a library', () => {
|
|
67
|
+
for (const args of [['--turns', '0'], ['--turns', '501'], ['--cue', '2'], ['--nope']]) {
|
|
68
|
+
let code = 0
|
|
69
|
+
try {
|
|
70
|
+
execFileSync(process.execPath, [SCRIPT, ...args], { cwd: REPO, stdio: 'pipe' })
|
|
71
|
+
} catch (error) {
|
|
72
|
+
code = error.status
|
|
73
|
+
}
|
|
74
|
+
assert.equal(code, 2, args.join(' ') + ' must be rejected as a usage error')
|
|
75
|
+
}
|
|
76
|
+
})
|
|
@@ -139,11 +139,35 @@ test('profile depends on the catalog only: it never touches state', () => {
|
|
|
139
139
|
|
|
140
140
|
// ---------------------------------------------------------------- 拒绝
|
|
141
141
|
|
|
142
|
+
// 三条已核实条目都能建 profile:切换功能的前提是「任意两条之间都能换」,而前缀必须随
|
|
143
|
+
// profile 下发到 worker,否则 e5 的两种读法在建 profile 这一步就丢了。
|
|
144
|
+
test('every verified catalog entry builds a profile that carries its prefixes', () => {
|
|
145
|
+
for (const entry of catalog.getEmbeddingCatalog()) {
|
|
146
|
+
const built = vp.profileFromCatalog(entry.id)
|
|
147
|
+
assert.equal(built.catalogId, entry.id)
|
|
148
|
+
assert.ok(Number.isInteger(built.dimension) && built.dimension > 0, entry.id)
|
|
149
|
+
assert.deepEqual(built.prefixes, entry.prefixes, entry.id)
|
|
150
|
+
assert.equal(built.fingerprint, entry.profileFingerprint, entry.id)
|
|
151
|
+
assert.equal(built.verification.status, 'verified', entry.id)
|
|
152
|
+
}
|
|
153
|
+
})
|
|
154
|
+
|
|
142
155
|
test('a pending model is refused instead of guessed', () => {
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
156
|
+
// 目录里三条都已核实,所以「未核实」用注入的候选条目验:挡住的是状态,不是某个 id。
|
|
157
|
+
const pending = clone(entry)
|
|
158
|
+
pending.id = 'pending-candidate'
|
|
159
|
+
pending.availability = 'pending'
|
|
160
|
+
pending.files = []
|
|
161
|
+
pending.verification = { ...pending.verification, status: 'unverified' }
|
|
162
|
+
delete pending.profileFingerprint
|
|
163
|
+
vp.setCatalogEntryResolver(id => (id === 'pending-candidate' ? pending : catalog.getEmbeddingModel(id)))
|
|
164
|
+
try {
|
|
165
|
+
assertCode(() => vp.profileFromCatalog('pending-candidate'), 'VECTOR_PROFILE_PENDING')
|
|
166
|
+
assertCode(() => vp.profileFromCatalog('nope-not-in-catalog'), 'VECTOR_PROFILE_UNKNOWN')
|
|
167
|
+
assertCode(() => vp.profileFromCatalog(null), 'VECTOR_PROFILE_UNKNOWN')
|
|
168
|
+
} finally {
|
|
169
|
+
vp.resetCatalogEntryResolver()
|
|
170
|
+
}
|
|
147
171
|
})
|
|
148
172
|
|
|
149
173
|
test('an unverified manifest is refused', () => {
|