dsh-memu-memory 1.3.3 → 1.3.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 +6 -1
- package/CHANGELOG.md +27 -3
- package/README.md +1 -7
- package/README.zh.md +1 -7
- package/assets/screenshots/drawer.jpg +0 -0
- package/assets/screenshots/mobile.jpg +0 -0
- package/assets/screenshots/relations.jpg +0 -0
- package/assets/screenshots/settings.jpg +0 -0
- package/assets/screenshots/stats.jpg +0 -0
- package/assets/screenshots/webui-dark.jpg +0 -0
- package/assets/screenshots/webui-memory.jpg +0 -0
- package/docs/client-conventions.md +10 -0
- package/docs/contributing.md +1 -0
- package/docs/memory-semantics.md +17 -0
- package/docs/troubleshooting.md +29 -0
- package/lib/binding-diagnostics.js +2 -2
- package/lib/client.js +34 -21
- package/lib/consolidation-snapshot.js +101 -5
- package/lib/consolidation-worker.js +1 -1
- package/lib/cycle.js +19 -1
- package/lib/index.js +83 -2
- package/lib/private.js +450 -165
- package/lib/rpc.js +8 -0
- package/lib/state.js +11 -1
- package/lib/turn-log.js +522 -0
- package/lib/webui/standalone.css +4 -29
- package/lib/worker-pool.js +741 -0
- package/package.json +1 -1
- package/scripts/acceptance-local.mjs +6 -5
- package/scripts/check-idle-compositing.mjs +61 -0
- package/scripts/prune-turnlogs.mjs +30 -0
- package/tests/consolidation-snapshot.test.mjs +89 -1
- package/tests/loader.mjs +2 -0
- package/tests/salience-domain.test.mjs +139 -0
- package/tests/settings-coverage.test.mjs +97 -0
- package/tests/stubs/dsh-session-query.js +26 -0
- package/tests/turn-log.test.mjs +474 -0
- package/tests/webui.test.mjs +19 -0
- package/tests/worker-lifecycle.test.mjs +1046 -0
- package/docs/recall-benchmark.md +0 -238
package/package.json
CHANGED
|
@@ -688,11 +688,12 @@ await auto('F-4', 'the activation log prints the settings the engine actually ra
|
|
|
688
688
|
assert.equal(Number(match[7]), settings.unpinBudgetPerSession)
|
|
689
689
|
assert.deepEqual(
|
|
690
690
|
handlers.filter((entry) => ['agent/pre-step', 'session/event'].includes(entry.event)).map((entry) => entry.event).sort(),
|
|
691
|
-
|
|
692
|
-
'
|
|
691
|
+
// 两个 session/event:注入管线一个 + 增量回合日志记录器一个(设计文档 §3.2,T0 起挂载)。
|
|
692
|
+
['agent/pre-step', 'session/event', 'session/event'],
|
|
693
|
+
'the same activation must wire the injection hooks and the turn-log recorder',
|
|
693
694
|
)
|
|
694
695
|
for (const dispose of disposers) { try { dispose() } catch {} }
|
|
695
|
-
return 'line matches live settings,
|
|
696
|
+
return 'line matches live settings, injection + turn-log hooks wired'
|
|
696
697
|
})
|
|
697
698
|
|
|
698
699
|
await auto('G-1', 'the kept docs exist and nothing points at a retired one', async () => {
|
|
@@ -717,8 +718,8 @@ await auto('G-1', 'the kept docs exist and nothing points at a retired one', asy
|
|
|
717
718
|
const ruleLead = (text) => text.split(String.fromCharCode(10)).filter((l) => /^[0-9]+[.] [*][*]/.test(l)).map((l) => { const end = l.indexOf('**', 5); return end < 0 ? l.slice(0, 40) : l.slice(0, end + 2) })
|
|
718
719
|
const inIndex = ruleLead(agents)
|
|
719
720
|
const inAppendix = ruleLead(appendix)
|
|
720
|
-
assert.
|
|
721
|
-
assert.equal(inAppendix.length, inIndex.length, 'the appendix carries the same
|
|
721
|
+
assert.ok(inIndex.length >= 10, 'the index carries at least ten hard rules, got ' + inIndex.length)
|
|
722
|
+
assert.equal(inAppendix.length, inIndex.length, 'the appendix carries the same hard rules')
|
|
722
723
|
for (const lead of inIndex) assert.ok(inAppendix.includes(lead), 'rule drifted between AGENTS.md and appendix E: ' + lead)
|
|
723
724
|
const pointers = agents.match(new RegExp('docs/[A-Za-z0-9._-]+[.]md', 'g')) || []
|
|
724
725
|
for (const rel of new Set(pointers)) {
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { chromium } from 'playwright'
|
|
4
|
+
|
|
5
|
+
// 空闲合成负载探针:WebUI 的 GPU 占用问题不是算力,是「空闲期仍在持续产帧」。
|
|
6
|
+
// 用 CDP screencast 数帧:页面没有视觉变化就不该有帧;无限 CSS 动画 / 常开 rAF /
|
|
7
|
+
// 全屏 backdrop-filter 都会让帧率钉在刷新率上。跑法:
|
|
8
|
+
// node --import ./tests/loader-register.mjs scripts/preview.mjs --port 7789
|
|
9
|
+
// node scripts/check-idle-compositing.mjs
|
|
10
|
+
// 只读本地预览(隔离示例数据),不写任何记忆库。
|
|
11
|
+
const base = process.argv[2] || 'http://127.0.0.1:7789/dsh-memu-memory/ui'
|
|
12
|
+
const seconds = Number(process.argv[3] || 6)
|
|
13
|
+
|
|
14
|
+
const chromeExe = ['chromium-1248/chrome-win64/chrome.exe', 'chromium-1194/chrome-win/chrome.exe', 'chromium-1117/chrome-win/chrome.exe']
|
|
15
|
+
.map(rel => path.join(process.env.LOCALAPPDATA || '', 'ms-playwright', rel))
|
|
16
|
+
.find(p => fs.existsSync(p))
|
|
17
|
+
if (!chromeExe) throw new Error('no chromium build under %LOCALAPPDATA%/ms-playwright — run `npx playwright install chromium`')
|
|
18
|
+
|
|
19
|
+
const browser = await chromium.launch({ headless: true, executablePath: chromeExe })
|
|
20
|
+
|
|
21
|
+
async function measure(label, setup) {
|
|
22
|
+
const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, deviceScaleFactor: 1 })
|
|
23
|
+
const page = await context.newPage()
|
|
24
|
+
await page.goto(base + '#/settings/memories', { waitUntil: 'load' })
|
|
25
|
+
await page.waitForSelector('.dshm-wall-item', { timeout: 20000 })
|
|
26
|
+
await page.waitForTimeout(1500) // boot 遮罩 900ms 后移除,等它走完
|
|
27
|
+
if (setup) await setup(page)
|
|
28
|
+
await page.waitForTimeout(1200) // 让入场动画结束,只量「空闲」
|
|
29
|
+
const animations = await page.evaluate(() => document.getAnimations()
|
|
30
|
+
.filter(a => a.playState === 'running')
|
|
31
|
+
.map(a => ({ name: a.animationName || a.transitionProperty || a.constructor.name, target: String(a.effect?.target?.className || a.effect?.target?.tagName || '').slice(0, 40) })))
|
|
32
|
+
const cdp = await context.newCDPSession(page)
|
|
33
|
+
let frames = 0
|
|
34
|
+
cdp.on('Page.screencastFrame', async (event) => {
|
|
35
|
+
frames++
|
|
36
|
+
try { await cdp.send('Page.screencastFrameAck', { sessionId: event.sessionId }) } catch {}
|
|
37
|
+
})
|
|
38
|
+
await cdp.send('Page.startScreencast', { format: 'jpeg', quality: 20, everyNthFrame: 1 })
|
|
39
|
+
await page.waitForTimeout(seconds * 1000)
|
|
40
|
+
await cdp.send('Page.stopScreencast')
|
|
41
|
+
await context.close()
|
|
42
|
+
return { label, frames, fps: Number((frames / seconds).toFixed(1)), animations }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const results = []
|
|
46
|
+
results.push(await measure('wall idle', null))
|
|
47
|
+
results.push(await measure('drawer open', async (page) => { await page.click('.dshm-wall-item'); await page.waitForSelector('.dshm-drawer') }))
|
|
48
|
+
results.push(await measure('graph cooled', async (page) => {
|
|
49
|
+
await page.goto(base + '#/settings/graph', { waitUntil: 'load' })
|
|
50
|
+
await page.waitForSelector('canvas.dshm-graph-canvas', { timeout: 20000 })
|
|
51
|
+
await page.waitForTimeout(6000) // 等力导向冷下来
|
|
52
|
+
}))
|
|
53
|
+
await browser.close()
|
|
54
|
+
|
|
55
|
+
for (const r of results) {
|
|
56
|
+
console.log(`${r.label.padEnd(12)} frames=${String(r.frames).padStart(4)} fps=${String(r.fps).padStart(5)} running animations: ${r.animations.length ? JSON.stringify(r.animations) : 'none'}`)
|
|
57
|
+
}
|
|
58
|
+
const idle = results.filter(r => r.label !== 'graph cooled')
|
|
59
|
+
const bad = idle.some(r => r.fps > 2)
|
|
60
|
+
console.log(bad ? 'FAIL: 空闲期仍在持续产帧(合成器没睡)' : 'PASS: 空闲期合成器已睡')
|
|
61
|
+
process.exitCode = bad ? 1 : 0
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// 手动清理回合日志(设计文档 §3.4)。默认 dry-run:只列出将删的文件与理由;
|
|
3
|
+
// --apply 才真删;--days N 覆盖 30 天默认。与 prune-sessions / prune-vectors 同款纪律。
|
|
4
|
+
//
|
|
5
|
+
// 两个条件缺一不可(§3.4 休眠 GC 行):会话 ≥N 天无任何活动(lastTurnAt),且日志
|
|
6
|
+
// 无未结算增量(max seqEnd ≤ lastSleepSeq)——有未结算增量的日志是增量来源,删了
|
|
7
|
+
// 就得整段重建;没到 idle 期限的删了也是白删(复活成本一样)。
|
|
8
|
+
import { listSessionBindings } from '../lib/state.js'
|
|
9
|
+
import { gcTurnLogs, turnLogPath } from '../lib/turn-log.js'
|
|
10
|
+
|
|
11
|
+
const args = process.argv.slice(2)
|
|
12
|
+
const apply = args.includes('--apply')
|
|
13
|
+
const daysFlag = args.indexOf('--days')
|
|
14
|
+
const days = daysFlag >= 0 ? Number(args[daysFlag + 1]) : 30
|
|
15
|
+
// 0 used to mean "every log is old enough", which made this a wipe command with a
|
|
16
|
+
// harmless-looking flag. The log is a cache so deletion is recoverable, but the
|
|
17
|
+
// rebuild cost is real — refuse the footgun all the same.
|
|
18
|
+
if (!Number.isFinite(days) || days <= 0) {
|
|
19
|
+
console.error('prune-turnlogs: --days must be a positive number of days (0 is not "all")')
|
|
20
|
+
process.exit(2)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const result = gcTurnLogs(listSessionBindings(), { olderThanDays: days, dryRun: !apply })
|
|
24
|
+
for (const sessionId of result.deleted) {
|
|
25
|
+
console.log(`${apply ? 'deleted' : 'would delete'} ${turnLogPath(sessionId)}`)
|
|
26
|
+
}
|
|
27
|
+
for (const item of result.kept) {
|
|
28
|
+
console.log(`kept ${item.sessionId}: ${item.reason}`)
|
|
29
|
+
}
|
|
30
|
+
console.log(JSON.stringify({ dryRun: !apply, days, deleted: result.deleted, kept: result.kept }, null, 2))
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import test from 'node:test'
|
|
2
2
|
import assert from 'node:assert/strict'
|
|
3
3
|
|
|
4
|
-
const { captureSessionSnapshot, safePrefix, toolPairing, lastClosedTurnSeq, snapshotHash } = await import('../lib/consolidation-snapshot.js')
|
|
4
|
+
const { captureSessionSnapshot, reconcilePersistedAhead, safePrefix, toolPairing, lastClosedTurnSeq, snapshotHash } = await import('../lib/consolidation-snapshot.js')
|
|
5
5
|
const { probeToolSurface, lastHeaderTools, buildWorkerBrief } = await import('../lib/consolidation-worker.js')
|
|
6
6
|
|
|
7
7
|
// C 包第 1、2 条:安全前缀必须可解释。这里逐条钉住「什么算完整」,
|
|
@@ -237,6 +237,94 @@ test('a failing observeSession is a retryable failure with the host message', as
|
|
|
237
237
|
assert.match(captured.error, /disk gone/)
|
|
238
238
|
})
|
|
239
239
|
|
|
240
|
+
// ---- 外部追加恢复:活视图落后于持久日志时改读冷日志(bench S1 冻结) ----
|
|
241
|
+
|
|
242
|
+
function coldAheadHost({ sessionId, liveEvents, coldEvents, coldHeader = null, liveHeader = null }) {
|
|
243
|
+
const rec = { coldReads: 0, disposed: 0 }
|
|
244
|
+
const ctx = {
|
|
245
|
+
rec,
|
|
246
|
+
on: () => () => {},
|
|
247
|
+
get: (name) => {
|
|
248
|
+
if (name === 'sessionQuery') {
|
|
249
|
+
return {
|
|
250
|
+
observeSession: async () => ({
|
|
251
|
+
source: 'live',
|
|
252
|
+
header: liveHeader || { id: sessionId, cwd: 'D:/proj', createdAt: 1 },
|
|
253
|
+
inheritedEventCount: 0,
|
|
254
|
+
events: liveEvents,
|
|
255
|
+
cursor: liveEvents.at(-1)?.seq ?? -1,
|
|
256
|
+
[Symbol.dispose]: () => { rec.disposed += 1 },
|
|
257
|
+
}),
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
if (name === 'sessionPersistence') return { open: async () => ({}) }
|
|
261
|
+
return undefined
|
|
262
|
+
},
|
|
263
|
+
}
|
|
264
|
+
const loadColdLogModule = async () => ({
|
|
265
|
+
readColdSessionLog: async () => {
|
|
266
|
+
rec.coldReads += 1
|
|
267
|
+
return {
|
|
268
|
+
header: coldHeader || { id: sessionId, cwd: 'D:/proj', createdAt: 1 },
|
|
269
|
+
inheritedEventCount: 0,
|
|
270
|
+
events: coldEvents,
|
|
271
|
+
}
|
|
272
|
+
},
|
|
273
|
+
assertSessionHeadersCompatible: (a, b) => {
|
|
274
|
+
if (a.id !== b.id || a.createdAt !== b.createdAt || a.cwd !== b.cwd) throw new Error('header conflict')
|
|
275
|
+
},
|
|
276
|
+
})
|
|
277
|
+
return { ctx, rec, loadColdLogModule }
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
test('a live observation behind the persisted log is replaced by the cold log', async () => {
|
|
281
|
+
const liveEvents = turn(1, 1) // seq 0-5
|
|
282
|
+
const coldEvents = [...turn(1, 1), ...closeTurn([], 2, 6)] // seq 0-10
|
|
283
|
+
const { ctx, rec, loadColdLogModule } = coldAheadHost({
|
|
284
|
+
sessionId: 'sess-ahead', liveEvents, coldEvents,
|
|
285
|
+
})
|
|
286
|
+
const captured = await captureSessionSnapshot(ctx, 'sess-ahead', { loadColdLogModule })
|
|
287
|
+
assert.equal(captured.ok, true)
|
|
288
|
+
assert.equal(captured.snapshot.source, 'persisted-ahead', 'the persisted log wins when it is ahead')
|
|
289
|
+
assert.equal(captured.snapshot.throughSeq, 10)
|
|
290
|
+
assert.equal(captured.snapshot.eventCount, coldEvents.length)
|
|
291
|
+
assert.equal(rec.coldReads, 1)
|
|
292
|
+
assert.equal(rec.disposed, 1, 'the original live lease is still released')
|
|
293
|
+
})
|
|
294
|
+
|
|
295
|
+
test('a live observation that is already the newest keeps the live cut', async () => {
|
|
296
|
+
const liveEvents = [...turn(1, 1), ...closeTurn([], 2, 6)]
|
|
297
|
+
const { ctx, rec, loadColdLogModule } = coldAheadHost({
|
|
298
|
+
sessionId: 'sess-live-wins', liveEvents, coldEvents: liveEvents,
|
|
299
|
+
})
|
|
300
|
+
const captured = await captureSessionSnapshot(ctx, 'sess-live-wins', { loadColdLogModule })
|
|
301
|
+
assert.equal(captured.ok, true)
|
|
302
|
+
assert.equal(captured.snapshot.source, 'lease-live')
|
|
303
|
+
assert.equal(captured.snapshot.throughSeq, 10)
|
|
304
|
+
assert.equal(rec.coldReads, 1, 'one probe is enough; the TTL cache skips the next few seconds')
|
|
305
|
+
})
|
|
306
|
+
|
|
307
|
+
test('a cold log with a conflicting header never replaces the live cut', async () => {
|
|
308
|
+
const liveEvents = turn(1, 1)
|
|
309
|
+
const coldEvents = [...turn(1, 1), ...closeTurn([], 2, 6)]
|
|
310
|
+
const { ctx, loadColdLogModule } = coldAheadHost({
|
|
311
|
+
sessionId: 'sess-conflict', liveEvents, coldEvents,
|
|
312
|
+
coldHeader: { id: 'sess-conflict', cwd: 'D:/elsewhere', createdAt: 1 },
|
|
313
|
+
})
|
|
314
|
+
const captured = await captureSessionSnapshot(ctx, 'sess-conflict', { loadColdLogModule })
|
|
315
|
+
assert.equal(captured.ok, true)
|
|
316
|
+
assert.equal(captured.snapshot.source, 'lease-live')
|
|
317
|
+
assert.equal(captured.snapshot.throughSeq, 5)
|
|
318
|
+
})
|
|
319
|
+
|
|
320
|
+
test('reconcilePersistedAhead degrades silently without persistence or the cold-read module', async () => {
|
|
321
|
+
assert.equal(await reconcilePersistedAhead({ persistence: null, sessionId: 'x', liveEvents: turn(1, 1) }), null)
|
|
322
|
+
assert.equal(await reconcilePersistedAhead({
|
|
323
|
+
persistence: { open: async () => ({}) }, sessionId: 'x', liveEvents: turn(1, 1),
|
|
324
|
+
loadModule: async () => { throw new Error('module missing') },
|
|
325
|
+
}), null)
|
|
326
|
+
})
|
|
327
|
+
|
|
240
328
|
// ---- 工具面:标准 / PTC / 未知 三种都要能分辨 ----
|
|
241
329
|
|
|
242
330
|
const MEMU_TOOLS = [
|
package/tests/loader.mjs
CHANGED
|
@@ -3,6 +3,8 @@ const map = {
|
|
|
3
3
|
'@deepseek-ai/dsh-tools': new URL('dsh-tools.js', stubs),
|
|
4
4
|
'@deepseek-ai/dsh-llm': new URL('dsh-llm.js', stubs),
|
|
5
5
|
'@deepseek-ai/dsh-session': new URL('dsh-session.js', stubs),
|
|
6
|
+
// 外部追加恢复(consolidation-snapshot.js 的冷日志交叉核对)动态 import 的宿主 peer。
|
|
7
|
+
'@deepseek-ai/dsh-session-query': new URL('dsh-session-query.js', stubs),
|
|
6
8
|
// 整理 fork 自定义模型 route(lib/fork-model.js)动态 import 的宿主 peer:测试进程
|
|
7
9
|
// 装不上真包,桩只提供可构造的 PiAiAdapter 让生产接线走通成功路径。
|
|
8
10
|
'@deepseek-ai/dsh-llm-pi-ai': new URL('dsh-llm-pi-ai.js', stubs),
|
|
@@ -0,0 +1,139 @@
|
|
|
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-salience-'))
|
|
8
|
+
process.env.DSH_MEMU_HOME = home
|
|
9
|
+
|
|
10
|
+
const { salienceScore, mustCoverCandidates, candidateSeedEvents } = await import('../lib/private.js')
|
|
11
|
+
|
|
12
|
+
test.after(() => {
|
|
13
|
+
try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
// —— §6.1 回归:general/rp/默认参数下,中文文本得分与旧全域表逐条一致 ——
|
|
17
|
+
test('Chinese text scores identically to the legacy global table (general/rp/default)', () => {
|
|
18
|
+
const legacy = new Map([
|
|
19
|
+
['说好周末拿给阿兰换伞骨,记得带过去。', 5],
|
|
20
|
+
['今天天气不错。', 2],
|
|
21
|
+
['她讨厌被叫错名字,更喜欢被称作阿兰。', 4],
|
|
22
|
+
['我欠你一顿饭,月底之前还。', 6],
|
|
23
|
+
['明天下午三点到期的账单别忘了。', 6],
|
|
24
|
+
['阿兰说他下周要接手这份工作。', 4],
|
|
25
|
+
['你好。', 0],
|
|
26
|
+
])
|
|
27
|
+
for (const [text, expected] of legacy) {
|
|
28
|
+
assert.equal(salienceScore(text), expected, `default: ${text}`)
|
|
29
|
+
assert.equal(salienceScore(text, 'general'), expected, `general: ${text}`)
|
|
30
|
+
assert.equal(salienceScore(text, 'rp'), expected, `rp: ${text}`)
|
|
31
|
+
}
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
// —— §6.1 验收:同一段中英混排 coding 文本得分 ≥3 ——
|
|
35
|
+
test('mixed-script coding text clears the must-cover bar', () => {
|
|
36
|
+
const text = '修复了 login bug 并部署到 staging,shipped v2.3.1'
|
|
37
|
+
assert.ok(salienceScore(text, 'coding') >= 3)
|
|
38
|
+
assert.ok(salienceScore(text, 'mixed') >= 3)
|
|
39
|
+
assert.ok(salienceScore(text, 'mixed') >= salienceScore(text, 'coding'), 'mixed covers coding signals')
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
// —— §6.1 匹配规则:Latin 必须 \b 词边界,fix 不命中 fixture/prefix ——
|
|
43
|
+
test('Latin words respect word boundaries', () => {
|
|
44
|
+
assert.equal(salienceScore('fixture list and prefix tree', 'coding'), 0)
|
|
45
|
+
assert.equal(salienceScore('the environment and database', 'coding'), 0, 'env must not hit environment')
|
|
46
|
+
assert.equal(salienceScore('fix the typo', 'coding'), 2, 'bare fix still hits')
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
// —— §6.1 匹配规则:大小写不敏感(FIX/Fixed 要命中)——
|
|
50
|
+
test('Latin patterns are case-insensitive', () => {
|
|
51
|
+
assert.equal(salienceScore('FIX the fixture', 'coding'), 2, 'FIX hits, fixture does not')
|
|
52
|
+
assert.equal(salienceScore('FIXED and shipped v2.3.1', 'coding'), 4)
|
|
53
|
+
assert.equal(salienceScore('OPTIMIZE the build, renamed the config', 'coding'), 4)
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
// —— §6.1 验收:英文 coding 文本得分 ——
|
|
57
|
+
test('plain-English coding turns score above the must-cover bar', () => {
|
|
58
|
+
assert.ok(salienceScore('fixed the login bug and shipped v2.3.1', 'coding') >= 3)
|
|
59
|
+
assert.equal(salienceScore('Deployed the hotfix after a crash', 'coding'), 6)
|
|
60
|
+
assert.ok(salienceScore('breaking change in the API config, root cause was a migration', 'coding') >= 3)
|
|
61
|
+
assert.equal(salienceScore('we are still discussing the refactor plan', 'coding'), 1, 'weak-only signal scores 1')
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
// —— §6.1 rp 行:剧情词/英文同人词只属于 rp,general 不受影响 ——
|
|
65
|
+
test('rp extras score in rp and mixed but stay out of general', () => {
|
|
66
|
+
assert.equal(salienceScore('人设和世界观都更新了', 'rp'), 2)
|
|
67
|
+
assert.equal(salienceScore('人设和世界观都更新了', 'general'), 0)
|
|
68
|
+
assert.equal(salienceScore('her persona is canon, out of character moment', 'rp'), 3)
|
|
69
|
+
assert.equal(salienceScore('人设更新:她讨厌甜食,设定里不吃辣。', 'mixed'), 4, 'mixed keeps rp weak words')
|
|
70
|
+
assert.ok(salienceScore('修复了人设相关的 bug,明天发布', 'mixed') >= salienceScore('修复了人设相关的 bug,明天发布', 'coding'), 'mixed keeps coding strong words')
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
// —— §6.1 匹配规则:未知域回退 general ——
|
|
74
|
+
test('unknown domains fall back to general', () => {
|
|
75
|
+
const text = '生日快乐,记得还书。'
|
|
76
|
+
assert.equal(salienceScore(text, 'totally-new-domain'), salienceScore(text, 'general'))
|
|
77
|
+
assert.equal(salienceScore(text, 'totally-new-domain'), 6)
|
|
78
|
+
assert.notEqual(salienceScore(text, 'coding'), salienceScore(text, 'general'), 'domains separate real signals')
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
// —— 回归:mustCoverCandidates 不传 domain 时与旧代码一致 ——
|
|
82
|
+
test('mustCoverCandidates without domain behaves like the legacy code', () => {
|
|
83
|
+
const events = [
|
|
84
|
+
{ seq: 0, type: 'turn/start', data: {} },
|
|
85
|
+
{ seq: 1, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '说好周末拿给阿兰换伞骨,记得带过去。' }] } },
|
|
86
|
+
{ seq: 2, type: 'turn/end', data: {} },
|
|
87
|
+
{ seq: 3, type: 'turn/start', data: {} },
|
|
88
|
+
{ seq: 4, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '今天天气不错。' }] } },
|
|
89
|
+
{ seq: 5, type: 'turn/end', data: {} },
|
|
90
|
+
]
|
|
91
|
+
const rows = mustCoverCandidates(events)
|
|
92
|
+
assert.equal(rows.length, 1, 'a turn below minScore is not a must-cover candidate')
|
|
93
|
+
assert.equal(rows[0].fromSeq, 0)
|
|
94
|
+
assert.equal(rows[0].throughSeq, 2)
|
|
95
|
+
assert.equal(rows[0].score, 5)
|
|
96
|
+
assert.equal(rows[0].tag, '人物/关系')
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
// —— §6.1 缺口修复:英文 coding 会话的必写候选不再塌方 ——
|
|
100
|
+
test('English coding turns produce must-cover candidates under the coding domain', () => {
|
|
101
|
+
const events = [
|
|
102
|
+
{ seq: 0, type: 'turn/start', data: {} },
|
|
103
|
+
{ seq: 1, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: 'fixed the login bug and shipped v2.3.1' }] } },
|
|
104
|
+
{ seq: 2, type: 'turn/end', data: {} },
|
|
105
|
+
{ seq: 3, type: 'turn/start', data: {} },
|
|
106
|
+
{ seq: 4, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: 'deploying to staging now, hotfix for the crash' }] } },
|
|
107
|
+
{ seq: 5, type: 'turn/end', data: {} },
|
|
108
|
+
]
|
|
109
|
+
const rows = mustCoverCandidates(events, { domain: 'coding' })
|
|
110
|
+
assert.equal(rows.length, 2)
|
|
111
|
+
assert.ok(rows.every((row) => row.score >= 3))
|
|
112
|
+
assert.deepEqual(rows.map((row) => row.fromSeq), [0, 3])
|
|
113
|
+
assert.deepEqual(mustCoverCandidates(events), [], 'without domain the legacy gap still applies')
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
// —— 签名透传:candidateSeedEvents 按域保留回合,默认行为不变 ——
|
|
117
|
+
test('candidateSeedEvents honours domain without changing defaults', () => {
|
|
118
|
+
const events = [
|
|
119
|
+
{ seq: 0, type: 'turn/start', data: {} },
|
|
120
|
+
{ seq: 1, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '今天天气不错。' }] } },
|
|
121
|
+
{ seq: 2, type: 'turn/end', data: {} },
|
|
122
|
+
{ seq: 3, type: 'turn/start', data: {} },
|
|
123
|
+
{ seq: 4, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: 'fixed the login bug and shipped v2.3.1' }] } },
|
|
124
|
+
{ seq: 5, type: 'turn/end', data: {} },
|
|
125
|
+
{ seq: 6, type: 'turn/start', data: {} },
|
|
126
|
+
{ seq: 7, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '嗯。' }] } },
|
|
127
|
+
{ seq: 8, type: 'turn/end', data: {} },
|
|
128
|
+
{ seq: 9, type: 'turn/start', data: {} },
|
|
129
|
+
{ seq: 10, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '先这样。' }] } },
|
|
130
|
+
{ seq: 11, type: 'turn/end', data: {} },
|
|
131
|
+
{ seq: 12, type: 'turn/start', data: {} },
|
|
132
|
+
{ seq: 13, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '回头再说。' }] } },
|
|
133
|
+
{ seq: 14, type: 'turn/end', data: {} },
|
|
134
|
+
]
|
|
135
|
+
const general = candidateSeedEvents(events)
|
|
136
|
+
assert.deepEqual(general.map((event) => event.seq), [0, 1, 2, 3, 4, 5], 'general keeps only the Chinese turn and its neighbour')
|
|
137
|
+
const coding = candidateSeedEvents(events, { domain: 'coding' })
|
|
138
|
+
assert.deepEqual(coding.map((event) => event.seq), [0, 1, 2, 3, 4, 5, 6, 7, 8], 'coding keeps the English turn and its neighbours')
|
|
139
|
+
})
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// 设置面全覆盖守卫(设计文档 §11 第 6 项):防止"新增设置键 + 多处白名单"漂移。
|
|
2
|
+
// 四条断言:
|
|
3
|
+
// 1. state.js 枚举表(:425 附近的 enums 对象)里的每个键必须出现在 setSettings
|
|
4
|
+
// 白名单里——枚举校验为可设置的键而存在,校验了却不可设置 = 死键。
|
|
5
|
+
// (注意:resetSettings 是产品 curated 名单——backend 类选择如 vectorSource
|
|
6
|
+
// 有意不参与"重置调参",故 reset 不做全量断言。)
|
|
7
|
+
// 2. resetSettings 名单的每个键必须在 DEFAULT_SETTINGS 里——reset 的实现是
|
|
8
|
+
// `patch[key] = DEFAULT_SETTINGS[key]`,键缺默认就会把 undefined 写进 state。
|
|
9
|
+
// 3. 每个枚举键的 DEFAULT_SETTINGS 默认值必须是该枚举的合法值——默认值越界等于
|
|
10
|
+
// 出厂即非法。
|
|
11
|
+
// 4. 三个新键(consolidationRunner / consolidationTurnLog / consolidationTurnLogTools)
|
|
12
|
+
// 必须在两张名单里(本设计的回归锚点)。
|
|
13
|
+
// 实现取源码文本解析而非 import(enums 表未导出,且解析即守卫源码形态本身——
|
|
14
|
+
// 与 check-doc-drift / binding-diagnostics 的行号契约同款思路)。
|
|
15
|
+
import test from 'node:test'
|
|
16
|
+
import assert from 'node:assert/strict'
|
|
17
|
+
import fs from 'node:fs'
|
|
18
|
+
import path from 'node:path'
|
|
19
|
+
import { fileURLToPath } from 'node:url'
|
|
20
|
+
import { DEFAULT_SETTINGS } from '../lib/state.js'
|
|
21
|
+
|
|
22
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
|
23
|
+
const stateSrc = fs.readFileSync(path.join(HERE, '..', 'lib', 'state.js'), 'utf8')
|
|
24
|
+
const rpcSrc = fs.readFileSync(path.join(HERE, '..', 'lib', 'rpc.js'), 'utf8')
|
|
25
|
+
|
|
26
|
+
function enumBlock(src) {
|
|
27
|
+
const marker = src.indexOf('const enums = {')
|
|
28
|
+
assert.notEqual(marker, -1, 'state.js 的 enums 表必须存在(校验函数被移动后请更新本测试的定位标记)')
|
|
29
|
+
let depth = 0, end = -1
|
|
30
|
+
for (let i = marker; i < src.length; i++) {
|
|
31
|
+
if (src[i] === '{') depth += 1
|
|
32
|
+
else if (src[i] === '}') { depth -= 1; if (depth === 0) { end = i; break } }
|
|
33
|
+
}
|
|
34
|
+
assert.notEqual(end, -1, 'enums 表右括号配平失败')
|
|
35
|
+
return src.slice(marker, end + 1)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function extractEnumKeys(src) {
|
|
39
|
+
const keys = [...enumBlock(src).matchAll(/(?:^|[,{\s])([A-Za-z_][A-Za-z0-9_]*):\s*\[/g)].map((m) => m[1])
|
|
40
|
+
assert.ok(keys.length >= 10, `enums 表解析出 ${keys.length} 个键,明显过少——解析器或表结构变了`)
|
|
41
|
+
return keys
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function extractWhitelist(src, caseName, terminator) {
|
|
45
|
+
const label = `case '${caseName}'`
|
|
46
|
+
const start = src.indexOf(label)
|
|
47
|
+
assert.notEqual(start, -1, `rpc.js 缺少 case '${caseName}'(结构变了请更新本测试定位)`)
|
|
48
|
+
const stop = src.indexOf(terminator, start)
|
|
49
|
+
// 从 case 标签之后起切 + 剥离行注释——注释里的引号词(如 "'fork'")与标签本身不是名单项
|
|
50
|
+
let block = src.slice(start + label.length, stop === -1 ? src.length : stop)
|
|
51
|
+
block = block.replace(/\/\/[^\n]*/g, '')
|
|
52
|
+
const items = [...block.matchAll(/'([A-Za-z_][A-Za-z0-9_]*)'/g)].map((m) => m[1]).filter((k) => k !== caseName)
|
|
53
|
+
assert.ok(items.length >= 20, `${caseName} 白名单解析出 ${items.length} 项,明显过少`)
|
|
54
|
+
return new Set(items)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const enumKeys = extractEnumKeys(stateSrc)
|
|
58
|
+
const resetList = extractWhitelist(rpcSrc, 'resetSettings', "case 'setSettings'")
|
|
59
|
+
const setList = extractWhitelist(rpcSrc, 'setSettings', 'const clean = {}')
|
|
60
|
+
|
|
61
|
+
// 有意不走通用 setSettings 的枚举键(专用 RPC 路径,自带校验):
|
|
62
|
+
// vectorSource → setEmbeddingSource(memu-config.js,切源有副作用需专门处理,
|
|
63
|
+
// 源值校验在专用函数内:local|api,'remote'→'api' 归一化)。
|
|
64
|
+
// 新增豁免必须在此登记 + 注明专用路径,否则视为漂移。
|
|
65
|
+
const SET_WHITELIST_EXCEPTIONS = new Set(['vectorSource'])
|
|
66
|
+
|
|
67
|
+
test('enums 表的每个键都在 setSettings 白名单里(可设置,否则是死键;豁免见 SET_WHITELIST_EXCEPTIONS)', () => {
|
|
68
|
+
const missing = enumKeys.filter((k) => !setList.has(k) && !SET_WHITELIST_EXCEPTIONS.has(k))
|
|
69
|
+
assert.deepEqual(missing, [], `以下枚举键缺出 setSettings 白名单(既不在名单也不在豁免表):${missing.join(', ')}`)
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
test('resetSettings 名单的每个键都有 DEFAULT_SETTINGS 默认值(否则 reset 写入 undefined)', () => {
|
|
73
|
+
const missing = [...resetList].filter((k) => !(k in DEFAULT_SETTINGS))
|
|
74
|
+
assert.deepEqual(missing, [], `以下 reset 键缺默认值(重置会写 undefined):${missing.join(', ')}`)
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
test('每个枚举键的默认值都是该枚举的合法值', () => {
|
|
78
|
+
const block = enumBlock(stateSrc)
|
|
79
|
+
const problems = []
|
|
80
|
+
for (const key of enumKeys) {
|
|
81
|
+
const m = block.match(new RegExp(`${key}:\\s*\\[([^\\]]+)\\]`))
|
|
82
|
+
if (!m) continue
|
|
83
|
+
const values = [...m[1].matchAll(/'([^']+)'/g)].map((v) => v[1])
|
|
84
|
+
const def = DEFAULT_SETTINGS[key]
|
|
85
|
+
if (def !== undefined && values.length && !values.includes(def)) {
|
|
86
|
+
problems.push(`${key}: 默认 '${def}' 不在枚举 [${values.join(', ')}] 里`)
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
assert.deepEqual(problems, [], `默认值越界:\n${problems.join('\n')}`)
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
test('三个新键(runner/turnLog/turnLogTools)都在两张名单里(本设计回归锚点)', () => {
|
|
93
|
+
for (const key of ['consolidationRunner', 'consolidationTurnLog', 'consolidationTurnLogTools']) {
|
|
94
|
+
assert.ok(resetList.has(key), `${key} 缺出 resetSettings`)
|
|
95
|
+
assert.ok(setList.has(key), `${key} 缺出 setSettings`)
|
|
96
|
+
}
|
|
97
|
+
})
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Host `@deepseek-ai/dsh-session-query` stand-in for the external-append recovery tests.
|
|
2
|
+
// The real package is a host peer and is not installed in this repo. Tests put the cold
|
|
3
|
+
// log on the fake persistence object (`persistence.__coldLogs[sessionId]`), so the
|
|
4
|
+
// production `reconcilePersistedAhead` path can be exercised without the host.
|
|
5
|
+
export async function readColdSessionLog(persistence, sessionId) {
|
|
6
|
+
const log = persistence?.__coldLogs?.[String(sessionId)]
|
|
7
|
+
if (!log) {
|
|
8
|
+
const error = new Error(`session "${sessionId}" not found`)
|
|
9
|
+
error.name = 'SessionPersistenceNotFoundError'
|
|
10
|
+
throw error
|
|
11
|
+
}
|
|
12
|
+
return log
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function assertSessionHeadersCompatible(a, b) {
|
|
16
|
+
if (
|
|
17
|
+
a.id !== b.id
|
|
18
|
+
|| a.createdAt !== b.createdAt
|
|
19
|
+
|| a.cwd !== b.cwd
|
|
20
|
+
|| a.parentSession !== b.parentSession
|
|
21
|
+
|| a.isSeeded !== b.isSeeded
|
|
22
|
+
|| (a.delegationDepth ?? 0) !== (b.delegationDepth ?? 0)
|
|
23
|
+
) {
|
|
24
|
+
throw new Error(`session source headers conflict for session "${a.id}"`)
|
|
25
|
+
}
|
|
26
|
+
}
|