dsh-memu-memory 1.2.2 → 1.2.3
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 +3 -1
- package/README.md +12 -4
- package/README.zh.md +13 -5
- package/docs/client-conventions.md +1 -0
- package/docs/contributing.md +7 -6
- package/docs/emotion-model-spec.md +2 -2
- package/docs/env-and-commands.md +20 -0
- package/docs/host-api.md +19 -0
- package/docs/memory-semantics.md +10 -1
- package/docs/troubleshooting.md +36 -3
- package/lib/activity-log.js +1 -1
- package/lib/binding-diagnostics.js +1 -1
- package/lib/client.js +152 -9
- package/lib/cycle.js +9 -1
- package/lib/freshness.js +97 -0
- package/lib/graph.js +244 -2
- package/lib/inject.js +119 -8
- package/lib/memory.js +83 -17
- package/lib/rpc.js +13 -2
- package/lib/salient-wake.js +402 -0
- package/lib/state.js +92 -1
- package/package.json +1 -1
- package/scripts/drive-session.mjs +853 -0
- package/scripts/mock-llm.mjs +903 -0
- package/tests/client-render.test.mjs +13 -1
- 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/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/stubs/dsh-schedule.js +105 -0
- package/tests/webui-auth.test.mjs +4 -0
|
@@ -11,6 +11,7 @@ process.env.DSH_MEMU_HOME = home
|
|
|
11
11
|
const state = await import('../lib/state.js')
|
|
12
12
|
const memory = await import('../lib/memory.js')
|
|
13
13
|
const inject = await import('../lib/inject.js')
|
|
14
|
+
const budget = await import('../lib/budget.js')
|
|
14
15
|
|
|
15
16
|
test.after(() => {
|
|
16
17
|
try { state.flushState() } catch {}
|
|
@@ -189,3 +190,178 @@ test('the remember tool tells the model to resolve a relative day', () => {
|
|
|
189
190
|
assert.ok(source.includes('A relative day'), 'the tool description must mention relative days')
|
|
190
191
|
assert.ok(source.includes('turns one appointment into a yearly reminder'), 'and why it matters')
|
|
191
192
|
})
|
|
193
|
+
|
|
194
|
+
// ------------------------------------- D: freshness hint is conditional and bounded
|
|
195
|
+
// The hint is a footnote to a recall that already succeeded: it must appear once,
|
|
196
|
+
// after every closed <memory-context> block, and must never turn a normal turn into
|
|
197
|
+
// a hint-only or failed turn.
|
|
198
|
+
|
|
199
|
+
const DAY_MS = 86_400_000
|
|
200
|
+
|
|
201
|
+
function seedRecallEntry(binding, id, patch = {}) {
|
|
202
|
+
const now = new Date().toISOString()
|
|
203
|
+
const index = state.loadPrivateIndex(binding.libraryId)
|
|
204
|
+
index.entries[id] = {
|
|
205
|
+
track: 'memory',
|
|
206
|
+
layer: 'long_term',
|
|
207
|
+
title: '部署脚本的位置',
|
|
208
|
+
content: '部署脚本放在 tools/deploy.ps1,先跑 staging smoke。',
|
|
209
|
+
status: 'active',
|
|
210
|
+
confidence: 0.9,
|
|
211
|
+
createdAt: now,
|
|
212
|
+
updatedAt: now,
|
|
213
|
+
...patch,
|
|
214
|
+
}
|
|
215
|
+
state.savePrivateIndex(binding.libraryId, index)
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async function recallFor(sessionId, binding, query, patch = {}) {
|
|
219
|
+
const exec = { agent: { session: { header: { id: sessionId, agentPreset: 'coding' } } } }
|
|
220
|
+
return inject.buildRecall(binding, query, 1, {
|
|
221
|
+
...state.getSettings(),
|
|
222
|
+
relevanceThreshold: 0,
|
|
223
|
+
...patch,
|
|
224
|
+
}, exec, sessionId)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
test('a stale recalled memory appends exactly one freshness hint after the closed blocks', async () => {
|
|
228
|
+
const cwd = path.join(home, 'project-freshness-stale')
|
|
229
|
+
const binding = state.ensureSession('chain-freshness-stale', { cwd, agentPreset: 'coding' })
|
|
230
|
+
const old = new Date(Date.now() - 45 * DAY_MS).toISOString()
|
|
231
|
+
seedRecallEntry(binding, 'mem-fresh-deploy', { updatedAt: old })
|
|
232
|
+
seedRecallEntry(binding, 'mem-fresh-release', {
|
|
233
|
+
title: '发布流程的审批',
|
|
234
|
+
content: '发布流程需要提前一天审批。',
|
|
235
|
+
updatedAt: old,
|
|
236
|
+
})
|
|
237
|
+
|
|
238
|
+
const recall = await recallFor('chain-freshness-stale', binding, '部署脚本和发布流程')
|
|
239
|
+
assert.deepEqual(recall.errors, [])
|
|
240
|
+
assert.ok(recall.ids.includes('mem-fresh-deploy'))
|
|
241
|
+
assert.ok(recall.ids.includes('mem-fresh-release'))
|
|
242
|
+
assert.equal((recall.text.match(/<memory-freshness>/g) || []).length, 1, 'the hint appears exactly once')
|
|
243
|
+
assert.ok(recall.text.includes('上面有 2 条记忆带时间敏感信号'), 'N counts the unique stale entries')
|
|
244
|
+
assert.ok(recall.text.indexOf('<memory-freshness>') > recall.text.lastIndexOf('</memory-context>'),
|
|
245
|
+
'the hint follows the last closed context block')
|
|
246
|
+
assert.equal((recall.text.match(/<memory-context\b/g) || []).length, 1, 'recall still has one context block')
|
|
247
|
+
assert.equal((recall.text.match(/<\/memory-context>/g) || []).length, 1)
|
|
248
|
+
assert.ok(recall.text.endsWith('</memory-freshness>'))
|
|
249
|
+
|
|
250
|
+
// The age leg obeys freshnessDays: 45-day-old entries are fresh at 100 days.
|
|
251
|
+
const lenient = await recallFor('chain-freshness-stale', binding, '部署脚本和发布流程', { freshnessDays: 100 })
|
|
252
|
+
assert.ok(lenient.text.includes('</memory-context>'))
|
|
253
|
+
assert.equal(lenient.text.includes('<memory-freshness>'), false)
|
|
254
|
+
})
|
|
255
|
+
|
|
256
|
+
test('a fresh recalled memory adds no freshness hint', async () => {
|
|
257
|
+
const cwd = path.join(home, 'project-freshness-fresh')
|
|
258
|
+
const binding = state.ensureSession('chain-freshness-fresh', { cwd, agentPreset: 'coding' })
|
|
259
|
+
seedRecallEntry(binding, 'mem-fresh-now')
|
|
260
|
+
|
|
261
|
+
const recall = await recallFor('chain-freshness-fresh', binding, '部署脚本放在哪里')
|
|
262
|
+
assert.ok(recall.ids.includes('mem-fresh-now'))
|
|
263
|
+
assert.ok(recall.text.includes('</memory-context>'))
|
|
264
|
+
assert.equal(recall.text.includes('<memory-freshness>'), false)
|
|
265
|
+
})
|
|
266
|
+
|
|
267
|
+
test('the hint ships in the same plugin message as the recall block', async () => {
|
|
268
|
+
state.updateSettings({ randomCueChance: 0 })
|
|
269
|
+
const cwd = path.join(home, 'project-freshness-message')
|
|
270
|
+
const binding = state.ensureSession('chain-freshness-message', { cwd, agentPreset: 'coding' })
|
|
271
|
+
seedRecallEntry(binding, 'mem-fresh-message', { updatedAt: new Date(Date.now() - 45 * DAY_MS).toISOString() })
|
|
272
|
+
|
|
273
|
+
const user = {
|
|
274
|
+
id: 'u-freshness', role: 'user', source: { kind: 'user' },
|
|
275
|
+
content: [{ type: 'text', text: '部署脚本放在哪里' }],
|
|
276
|
+
}
|
|
277
|
+
const agent = { session: { header: { id: 'chain-freshness-message', cwd, agentPreset: 'coding', origin: 'user' } } }
|
|
278
|
+
const out = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: [user] }, turn: 1, step: 1, signal: { aborted: false } })
|
|
279
|
+
|
|
280
|
+
assert.equal(out.messages.length, 2)
|
|
281
|
+
assert.equal(out.messages[0].source.kind, 'plugin:dsh-memu-memory')
|
|
282
|
+
const text = out.messages[0].content[0].text
|
|
283
|
+
assert.ok(text.includes('[mem-fresh-message]'))
|
|
284
|
+
assert.equal((text.match(/<memory-freshness>/g) || []).length, 1)
|
|
285
|
+
assert.ok(text.indexOf('<memory-freshness>') > text.lastIndexOf('</memory-context>'))
|
|
286
|
+
assert.equal(state.getSessionBinding('chain-freshness-message').lastRecallError, undefined)
|
|
287
|
+
})
|
|
288
|
+
|
|
289
|
+
test('anchor-only and autoInject off never append the freshness hint', async () => {
|
|
290
|
+
const cwd = path.join(home, 'project-freshness-modes')
|
|
291
|
+
const binding = state.ensureSession('chain-freshness-modes', { cwd, agentPreset: 'coding' })
|
|
292
|
+
seedRecallEntry(binding, 'mem-fresh-modes', { updatedAt: new Date(Date.now() - 90 * DAY_MS).toISOString() })
|
|
293
|
+
|
|
294
|
+
const anchorOnly = await recallFor('chain-freshness-modes', binding, '部署脚本放在哪里', { autoInject: 'anchor-only' })
|
|
295
|
+
assert.ok(anchorOnly.text.includes('</memory-context>'))
|
|
296
|
+
assert.equal(anchorOnly.text.includes('<memory-freshness>'), false)
|
|
297
|
+
|
|
298
|
+
// buildRecall itself is not the off switch; the caller is. The hint still must
|
|
299
|
+
// not appear if a future caller forgets that.
|
|
300
|
+
const off = await recallFor('chain-freshness-modes', binding, '部署脚本放在哪里', { autoInject: 'off' })
|
|
301
|
+
assert.ok(off.text.includes('</memory-context>'))
|
|
302
|
+
assert.equal(off.text.includes('<memory-freshness>'), false)
|
|
303
|
+
})
|
|
304
|
+
|
|
305
|
+
test('a query shorter than minUserChars gets the recall but no freshness hint', async () => {
|
|
306
|
+
const cwd = path.join(home, 'project-freshness-short')
|
|
307
|
+
const binding = state.ensureSession('chain-freshness-short', { cwd, agentPreset: 'coding' })
|
|
308
|
+
seedRecallEntry(binding, 'mem-fresh-short', {
|
|
309
|
+
title: '最新的部署方式',
|
|
310
|
+
content: '最新的部署方式放在 tools/deploy.ps1。',
|
|
311
|
+
})
|
|
312
|
+
|
|
313
|
+
const recall = await recallFor('chain-freshness-short', binding, '最新')
|
|
314
|
+
assert.ok(recall.ids.includes('mem-fresh-short'))
|
|
315
|
+
assert.ok(recall.text.includes('</memory-context>'))
|
|
316
|
+
assert.equal(recall.text.includes('<memory-freshness>'), false)
|
|
317
|
+
})
|
|
318
|
+
|
|
319
|
+
test('freshnessHint false suppresses the freshness hint', async () => {
|
|
320
|
+
const cwd = path.join(home, 'project-freshness-switch')
|
|
321
|
+
const binding = state.ensureSession('chain-freshness-switch', { cwd, agentPreset: 'coding' })
|
|
322
|
+
seedRecallEntry(binding, 'mem-fresh-switch', { updatedAt: new Date(Date.now() - 45 * DAY_MS).toISOString() })
|
|
323
|
+
|
|
324
|
+
const recall = await recallFor('chain-freshness-switch', binding, '部署脚本放在哪里', { freshnessHint: false })
|
|
325
|
+
assert.ok(recall.ids.includes('mem-fresh-switch'))
|
|
326
|
+
assert.ok(recall.text.includes('</memory-context>'))
|
|
327
|
+
assert.equal(recall.text.includes('<memory-freshness>'), false)
|
|
328
|
+
})
|
|
329
|
+
|
|
330
|
+
test('the hint is dropped when turnTokens cannot fit it, and the recall still succeeds', async () => {
|
|
331
|
+
const cwd = path.join(home, 'project-freshness-budget')
|
|
332
|
+
const binding = state.ensureSession('chain-freshness-budget', { cwd, agentPreset: 'coding' })
|
|
333
|
+
seedRecallEntry(binding, 'mem-fresh-budget', { updatedAt: new Date(Date.now() - 45 * DAY_MS).toISOString() })
|
|
334
|
+
|
|
335
|
+
const full = await recallFor('chain-freshness-budget', binding, '部署脚本放在哪里', { turnTokens: 800 })
|
|
336
|
+
const marker = '\n\n<memory-freshness>'
|
|
337
|
+
const at = full.text.indexOf(marker)
|
|
338
|
+
assert.ok(at > 0, 'with room the hint appears')
|
|
339
|
+
const hint = full.text.slice(at)
|
|
340
|
+
const base = full.text.slice(0, at)
|
|
341
|
+
const needed = budget.estTokens(base)
|
|
342
|
+
assert.ok(budget.estTokens(base + hint) > needed, 'the hint itself costs something')
|
|
343
|
+
|
|
344
|
+
// The smallest budget that still fits the card cannot also fit the footnote.
|
|
345
|
+
let squeezed = null
|
|
346
|
+
for (let extra = 0; extra <= 12 && !squeezed; extra += 1) {
|
|
347
|
+
const turnTokens = needed + extra
|
|
348
|
+
const attempt = await recallFor('chain-freshness-budget', binding, '部署脚本放在哪里', { turnTokens })
|
|
349
|
+
if (attempt.text) squeezed = { attempt, turnTokens }
|
|
350
|
+
}
|
|
351
|
+
assert.ok(squeezed, 'a budget near the base size still fits one card')
|
|
352
|
+
assert.ok(squeezed.attempt.text.includes('[mem-fresh-budget]'))
|
|
353
|
+
assert.ok(squeezed.attempt.text.includes('</memory-context>'))
|
|
354
|
+
assert.equal(squeezed.attempt.text.includes('<memory-freshness>'), false)
|
|
355
|
+
assert.ok(budget.estTokens(squeezed.attempt.text) <= squeezed.turnTokens)
|
|
356
|
+
})
|
|
357
|
+
|
|
358
|
+
test('no recall means no freshness hint', async () => {
|
|
359
|
+
const cwd = path.join(home, 'project-freshness-none')
|
|
360
|
+
const binding = state.ensureSession('chain-freshness-none', { cwd, agentPreset: 'coding' })
|
|
361
|
+
seedRecallEntry(binding, 'mem-fresh-none', { updatedAt: new Date(Date.now() - 45 * DAY_MS).toISOString() })
|
|
362
|
+
|
|
363
|
+
const recall = await recallFor('chain-freshness-none', binding, 'zzz-unrelated-token-zzz')
|
|
364
|
+
assert.equal(recall.text, '')
|
|
365
|
+
assert.deepEqual(recall.ids, [])
|
|
366
|
+
assert.equal(recall.text.includes('<memory-freshness>'), false)
|
|
367
|
+
})
|
|
@@ -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
|
+
})
|