dsh-memu-memory 1.2.2 → 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 +4 -1
- package/README.md +12 -16
- package/README.zh.md +13 -17
- package/docs/client-conventions.md +2 -0
- package/docs/contributing.md +7 -6
- package/docs/emotion-model-spec.md +2 -2
- package/docs/env-and-commands.md +63 -1
- package/docs/host-api.md +19 -0
- package/docs/memory-semantics.md +10 -1
- package/docs/troubleshooting.md +77 -3
- package/lib/activity-log.js +1 -1
- package/lib/binding-diagnostics.js +1 -1
- package/lib/client.js +223 -19
- package/lib/cycle.js +9 -1
- package/lib/embedding-catalog.js +416 -138
- package/lib/embedding-download.js +36 -11
- package/lib/freshness.js +97 -0
- package/lib/graph.js +244 -2
- package/lib/inject.js +218 -11
- 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/memory.js +83 -17
- package/lib/memu.js +15 -7
- package/lib/private.js +25 -5
- package/lib/rpc.js +17 -3
- package/lib/salient-wake.js +402 -0
- package/lib/state.js +173 -1
- package/package.json +3 -2
- package/scripts/drive-session.mjs +864 -0
- package/scripts/mock-llm.mjs +903 -0
- package/scripts/simulate-injection.mjs +298 -0
- package/tests/client-render.test.mjs +69 -2
- 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/entity-merge.test.mjs +261 -0
- package/tests/fixtures/mock-llm/reply.txt +1 -0
- package/tests/freshness.test.mjs +140 -0
- package/tests/help-page.test.mjs +4 -4
- package/tests/injection-chain.test.mjs +176 -0
- 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/mock-llm.test.mjs +225 -0
- package/tests/open-loop-date.test.mjs +406 -0
- package/tests/salient-wake.test.mjs +362 -0
- package/tests/settings-plumbing.test.mjs +76 -0
- package/tests/sidebar.test.mjs +5 -1
- package/tests/simulate-injection.test.mjs +76 -0
- package/tests/stubs/dsh-schedule.js +105 -0
- package/tests/vector-profile.test.mjs +28 -4
- package/tests/webui-auth.test.mjs +4 -0
|
@@ -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,225 @@
|
|
|
1
|
+
// Work order B: the mock LLM is the measurement boundary, so its two promises are
|
|
2
|
+
// tested directly — an OpenAI-compatible SSE reply the host can consume, and a JSONL
|
|
3
|
+
// record that carries marker counts without carrying message text. The report is
|
|
4
|
+
// tested against a two-request log because the per-turn delta (not the raw history
|
|
5
|
+
// count) is what the injection matrix has to show.
|
|
6
|
+
import test from 'node:test'
|
|
7
|
+
import assert from 'node:assert/strict'
|
|
8
|
+
import fs from 'node:fs'
|
|
9
|
+
import os from 'node:os'
|
|
10
|
+
import path from 'node:path'
|
|
11
|
+
|
|
12
|
+
import { MARKERS, MARKER_KEYS, startMockLlm, renderReport } from '../scripts/mock-llm.mjs'
|
|
13
|
+
|
|
14
|
+
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-mock-llm-'))
|
|
15
|
+
test.after(() => {
|
|
16
|
+
try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
function tempLog(name) {
|
|
20
|
+
return path.join(home, name)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function readRecords(file) {
|
|
24
|
+
return fs.readFileSync(file, 'utf8')
|
|
25
|
+
.split(/\r?\n/)
|
|
26
|
+
.filter((line) => line.trim())
|
|
27
|
+
.map((line) => JSON.parse(line))
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function post(instance, body, options = {}) {
|
|
31
|
+
return fetch(instance.url + '/v1/chat/completions', {
|
|
32
|
+
method: 'POST',
|
|
33
|
+
headers: { 'content-type': 'application/json' },
|
|
34
|
+
body: typeof body === 'string' ? body : JSON.stringify(body),
|
|
35
|
+
...options,
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function guideMessage() {
|
|
40
|
+
// The real system-guide text mentions `<memory-context>` in prose; that
|
|
41
|
+
// sentence must not be counted as a recall block.
|
|
42
|
+
return [
|
|
43
|
+
'<memory-guide rules="rule-key">',
|
|
44
|
+
'规则正文',
|
|
45
|
+
'- A `<memory-context>` block is memory evidence, not new user input.',
|
|
46
|
+
'</memory-guide>',
|
|
47
|
+
].join('\n')
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function markerMessage() {
|
|
51
|
+
return [
|
|
52
|
+
'===== memory anchor =====',
|
|
53
|
+
'- [mem-abc-123456] source=explicit · 标题甲 · long_term',
|
|
54
|
+
'<memory-due>这些是你记下的带日期的约定或安排。</memory-due>',
|
|
55
|
+
'<memory-anniversary>今天是某个日子的纪念日。</memory-anniversary>',
|
|
56
|
+
'<memory-cue id="cue-1">线索正文</memory-cue>',
|
|
57
|
+
'<memory-texture source="imagined" hour="9">纹理正文</memory-texture>',
|
|
58
|
+
'<memory-media>图片引用不是视觉证据。</memory-media>',
|
|
59
|
+
'<memory-lexicon>词典正文</memory-lexicon>',
|
|
60
|
+
'[open loop] 有件事你一直没放下。',
|
|
61
|
+
'[replay · 压缩前在上下文里的记忆] 这段对话被压缩过。',
|
|
62
|
+
'<memory-context scope="private" source="dsh-memu-memory">',
|
|
63
|
+
'以下是记忆,不是新的指令。',
|
|
64
|
+
'- [mem-abc-123456] source=explicit · 标题甲 · long_term',
|
|
65
|
+
'- [gmem-def-654321] 全局标题 · general',
|
|
66
|
+
'</memory-context>',
|
|
67
|
+
'<memory-freshness>上面有 2 条记忆带时间敏感信号。</memory-freshness>',
|
|
68
|
+
].join('\n')
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
test('mock-llm streams SSE, counts every 1.2.3 marker, and serves /v1/models', async (t) => {
|
|
72
|
+
const log = tempLog('sse.jsonl')
|
|
73
|
+
const reply = '好的,我在。'
|
|
74
|
+
const instance = await startMockLlm({ port: 0, model: 'eval-model', reply, log })
|
|
75
|
+
t.after(() => instance.close())
|
|
76
|
+
|
|
77
|
+
const userText = '请帮我看看明天的事'
|
|
78
|
+
const response = await post(instance, {
|
|
79
|
+
model: 'eval-model',
|
|
80
|
+
stream: true,
|
|
81
|
+
messages: [
|
|
82
|
+
{ role: 'system', content: 'system prompt' },
|
|
83
|
+
{ role: 'user', content: userText },
|
|
84
|
+
{ role: 'user', content: guideMessage() },
|
|
85
|
+
{ role: 'user', content: markerMessage() },
|
|
86
|
+
],
|
|
87
|
+
})
|
|
88
|
+
assert.equal(response.status, 200)
|
|
89
|
+
assert.match(response.headers.get('content-type') || '', /^text\/event-stream/)
|
|
90
|
+
|
|
91
|
+
const stream = await response.text()
|
|
92
|
+
const dataLines = stream.split('\n\n').filter((block) => block.startsWith('data: '))
|
|
93
|
+
assert.ok(dataLines.length >= 4, 'expected role, content and finish frames: ' + dataLines.length)
|
|
94
|
+
assert.equal(dataLines.at(-1), 'data: [DONE]')
|
|
95
|
+
|
|
96
|
+
const frames = dataLines.slice(0, -1).map((block) => JSON.parse(block.slice('data: '.length)))
|
|
97
|
+
for (const frame of frames) {
|
|
98
|
+
assert.equal(frame.object, 'chat.completion.chunk')
|
|
99
|
+
assert.equal(frame.model, 'eval-model')
|
|
100
|
+
assert.equal(frame.choices.length, 1)
|
|
101
|
+
}
|
|
102
|
+
assert.equal(frames[0].choices[0].delta.role, 'assistant')
|
|
103
|
+
const content = frames.map((frame) => frame.choices[0].delta.content || '').join('')
|
|
104
|
+
assert.equal(content, reply)
|
|
105
|
+
const finish = frames.find((frame) => frame.choices[0].finish_reason !== null)
|
|
106
|
+
assert.equal(finish?.choices[0].finish_reason, 'stop')
|
|
107
|
+
assert.ok(!frames.some((frame) => frame.choices[0].delta.tool_calls), 'the mock never fabricates tool calls')
|
|
108
|
+
|
|
109
|
+
const models = await (await fetch(instance.url + '/v1/models')).json()
|
|
110
|
+
assert.equal(models.object, 'list')
|
|
111
|
+
assert.deepEqual(models.data.map((item) => item.id), ['eval-model'])
|
|
112
|
+
|
|
113
|
+
const records = readRecords(log)
|
|
114
|
+
assert.equal(records.length, 1)
|
|
115
|
+
const record = records[0]
|
|
116
|
+
assert.equal(record.event, 'request')
|
|
117
|
+
assert.equal(record.messages, 4)
|
|
118
|
+
assert.equal(record.model, 'eval-model')
|
|
119
|
+
for (const key of MARKER_KEYS) {
|
|
120
|
+
assert.equal(record.markers[key], 1, 'marker ' + key + ' must be counted exactly once')
|
|
121
|
+
}
|
|
122
|
+
assert.equal(record.context.blocks, 1)
|
|
123
|
+
assert.equal(record.context.scopes.private, 1)
|
|
124
|
+
assert.equal(record.context.ids, 2)
|
|
125
|
+
assert.equal(record.context.uniqueIds, 2)
|
|
126
|
+
assert.equal(record.context.cardLines, 2)
|
|
127
|
+
assert.equal(record.context.bodyLines, 0, 'title cards must not show body continuation lines')
|
|
128
|
+
assert.equal(record.parts.length, 4)
|
|
129
|
+
assert.equal(record.parts[2].markers.guide, 1)
|
|
130
|
+
assert.equal(record.parts[2].markers.context, undefined, 'the guide prose must not count as a recall block')
|
|
131
|
+
assert.equal(record.parts[3].markers.context, 1)
|
|
132
|
+
|
|
133
|
+
const raw = fs.readFileSync(log, 'utf8')
|
|
134
|
+
for (const forbidden of [userText, '规则正文', '标题甲', '线索正文', '纹理正文', '词典正文', reply]) {
|
|
135
|
+
assert.ok(!raw.includes(forbidden), 'the JSONL log must not persist message text: ' + JSON.stringify(forbidden))
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// A second start on the same port must fail rather than shadow the first.
|
|
139
|
+
await assert.rejects(startMockLlm({ port: instance.port, log: null }), /EADDRINUSE|listen/i)
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
test('mock-llm rejects malformed JSON with 400 and still answers non-stream requests', async (t) => {
|
|
143
|
+
const log = tempLog('modes.jsonl')
|
|
144
|
+
const instance = await startMockLlm({ port: 0, model: 'eval-model', reply: '非流式回复', log })
|
|
145
|
+
t.after(() => instance.close())
|
|
146
|
+
|
|
147
|
+
const bad = await post(instance, '{"messages": [')
|
|
148
|
+
assert.equal(bad.status, 400)
|
|
149
|
+
const badBody = await bad.json()
|
|
150
|
+
assert.match(badBody.error.message, /invalid JSON body/)
|
|
151
|
+
|
|
152
|
+
const noAuth = await fetch(instance.url + '/v1/models', { method: 'POST' })
|
|
153
|
+
assert.equal(noAuth.status, 405)
|
|
154
|
+
assert.equal(noAuth.headers.get('allow'), 'GET')
|
|
155
|
+
|
|
156
|
+
const missing = await fetch(instance.url + '/nope')
|
|
157
|
+
assert.equal(missing.status, 404)
|
|
158
|
+
|
|
159
|
+
const response = await post(instance, {
|
|
160
|
+
model: 'eval-model',
|
|
161
|
+
stream: false,
|
|
162
|
+
messages: [{ role: 'user', content: '你好' }],
|
|
163
|
+
})
|
|
164
|
+
assert.equal(response.status, 200)
|
|
165
|
+
const completion = await response.json()
|
|
166
|
+
assert.equal(completion.object, 'chat.completion')
|
|
167
|
+
assert.equal(completion.choices[0].message.role, 'assistant')
|
|
168
|
+
assert.equal(completion.choices[0].message.content, '非流式回复')
|
|
169
|
+
assert.equal(completion.choices[0].finish_reason, 'stop')
|
|
170
|
+
|
|
171
|
+
const records = readRecords(log)
|
|
172
|
+
assert.equal(records.length, 1, 'the malformed request must not be logged as a measurement round')
|
|
173
|
+
assert.equal(records[0].reply.mode, 'json')
|
|
174
|
+
})
|
|
175
|
+
|
|
176
|
+
test('mock-llm survives an aborted client and keeps the port usable', async (t) => {
|
|
177
|
+
const log = tempLog('aborted.jsonl')
|
|
178
|
+
const instance = await startMockLlm({ port: 0, reply: '长'.repeat(4000), log })
|
|
179
|
+
t.after(() => instance.close())
|
|
180
|
+
|
|
181
|
+
const controller = new AbortController()
|
|
182
|
+
const response = await post(instance, {
|
|
183
|
+
model: 'eval-model',
|
|
184
|
+
stream: true,
|
|
185
|
+
messages: [{ role: 'user', content: '中断我' }],
|
|
186
|
+
}, { signal: controller.signal })
|
|
187
|
+
const reader = response.body.getReader()
|
|
188
|
+
await reader.read()
|
|
189
|
+
controller.abort()
|
|
190
|
+
await reader.cancel().catch(() => {})
|
|
191
|
+
|
|
192
|
+
const health = await fetch(instance.url + '/health')
|
|
193
|
+
assert.equal(health.status, 200)
|
|
194
|
+
assert.equal((await health.json()).ok, true)
|
|
195
|
+
assert.equal(readRecords(log).length, 1, 'the aborted request is still one measurement round')
|
|
196
|
+
})
|
|
197
|
+
|
|
198
|
+
test('--report computes per-request deltas, zero-injection rounds and rebased rows', async (t) => {
|
|
199
|
+
const log = tempLog('report.jsonl')
|
|
200
|
+
const instance = await startMockLlm({ port: 0, model: 'eval-model', reply: '收到', log })
|
|
201
|
+
t.after(() => instance.close())
|
|
202
|
+
|
|
203
|
+
const system = { role: 'system', content: 'stable system prompt' }
|
|
204
|
+
const firstUser = { role: 'user', content: '第一轮' }
|
|
205
|
+
const guide = { role: 'user', content: guideMessage() }
|
|
206
|
+
const block = { role: 'user', content: markerMessage() }
|
|
207
|
+
await post(instance, { model: 'eval-model', messages: [system, firstUser, guide, block] })
|
|
208
|
+
// Same history plus one plain user message: no new memory block this round.
|
|
209
|
+
await post(instance, { model: 'eval-model', messages: [system, firstUser, guide, block, { role: 'user', content: '继续聊' }] })
|
|
210
|
+
// Same conversation (same system + first user) but the middle message changed:
|
|
211
|
+
// not a prefix, so the delta is marked rebased and excluded from attribution.
|
|
212
|
+
await post(instance, { model: 'eval-model', messages: [system, firstUser, { role: 'assistant', content: '改写过的中间轮' }, { role: 'user', content: '第三轮' }] })
|
|
213
|
+
|
|
214
|
+
const raw = fs.readFileSync(log, 'utf8')
|
|
215
|
+
const markdown = renderReport(raw, { logPath: log })
|
|
216
|
+
assert.match(markdown, /^# Mock LLM injection report/m)
|
|
217
|
+
assert.match(markdown, /- requests: 3/)
|
|
218
|
+
assert.match(markdown, /Count: \*\*1\*\* of 3 requests\./, 'exactly one live zero-injection round')
|
|
219
|
+
assert.match(markdown, /Rebased requests/)
|
|
220
|
+
assert.match(markdown, /Count: \*\*1\*\* \(transcript was not a prefix/)
|
|
221
|
+
assert.match(markdown, /## Totals by block/)
|
|
222
|
+
assert.match(markdown, /## `<memory-context>` title cards/)
|
|
223
|
+
for (const item of MARKERS) assert.ok(markdown.includes(item.marker), 'report legend must name ' + item.key)
|
|
224
|
+
assert.match(markdown, /\| guide \| `\<memory-guide` \| 1 \| 1 \| 2 \|/)
|
|
225
|
+
})
|