dsh-memu-memory 1.2.5 → 1.2.7

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.
Files changed (56) hide show
  1. package/AGENTS.md +3 -1
  2. package/README.md +3 -3
  3. package/README.zh.md +3 -3
  4. package/docs/contributing.md +1 -1
  5. package/docs/env-and-commands.md +1 -0
  6. package/docs/host-adaptation.md +318 -0
  7. package/docs/host-api.md +29 -5
  8. package/docs/memory-semantics.md +12 -7
  9. package/docs/troubleshooting.md +15 -9
  10. package/lib/binding-diagnostics.js +2 -2
  11. package/lib/client.js +291 -37
  12. package/lib/consolidation-ledger.js +46 -1
  13. package/lib/consolidation-worker.js +1 -0
  14. package/lib/curator-policy.js +98 -0
  15. package/lib/cycle.js +51 -17
  16. package/lib/fork-model.js +312 -0
  17. package/lib/index.js +8 -0
  18. package/lib/memory.js +36 -12
  19. package/lib/memu.js +318 -3
  20. package/lib/private.js +352 -70
  21. package/lib/prompts/private-consolidation.mixed.md +1 -0
  22. package/lib/prompts/private-consolidation.rp.md +1 -0
  23. package/lib/prompts/private-policy.mixed.md +1 -0
  24. package/lib/prompts/private-policy.rp.md +1 -1
  25. package/lib/recall-cache.js +204 -0
  26. package/lib/rpc.js +48 -7
  27. package/lib/salient-wake.js +38 -2
  28. package/lib/state.js +46 -6
  29. package/lib/text-retrieval.js +221 -28
  30. package/lib/tokenizer-v2.js +295 -0
  31. package/lib/webui/standalone.css +17 -1
  32. package/package.json +1 -1
  33. package/scripts/bench-recall.mjs +142 -0
  34. package/scripts/check-seed-compat.mjs +118 -0
  35. package/tests/absorb-review.test.mjs +2 -1
  36. package/tests/backend-compensation.test.mjs +1 -1
  37. package/tests/consolidation-fork.test.mjs +199 -7
  38. package/tests/curator-absorb.test.mjs +2 -1
  39. package/tests/curator-clusters.test.mjs +9 -2
  40. package/tests/curator-commit.test.mjs +2 -1
  41. package/tests/curator-link.test.mjs +2 -1
  42. package/tests/curator-pairing.test.mjs +52 -8
  43. package/tests/curator-review-mode.test.mjs +2 -1
  44. package/tests/cycle.test.mjs +2 -2
  45. package/tests/dynamic-rrf.test.mjs +179 -0
  46. package/tests/fork-model.test.mjs +345 -0
  47. package/tests/loader.mjs +3 -0
  48. package/tests/managed-memory.test.mjs +1 -1
  49. package/tests/negation-polarity.test.mjs +135 -0
  50. package/tests/recall-cache.test.mjs +290 -0
  51. package/tests/recall-dedup.test.mjs +1 -1
  52. package/tests/salient-wake.test.mjs +28 -1
  53. package/tests/stubs/dsh-llm-pi-ai.js +13 -0
  54. package/tests/stubs/dsh-schedule.js +35 -0
  55. package/tests/tokenizer-v2.test.mjs +142 -0
  56. package/tests/ui-defaults.test.mjs +1 -1
@@ -851,7 +851,8 @@ html[data-standalone] .dshm-root input[type="radio"] {
851
851
 
852
852
  /* The tuning form is a long single column in the host. On a desktop page it reads
853
853
  as a sparse list with half a card empty; two columns put the knobs side by side
854
- without splitting each row's label from its control. */
854
+ without splitting each row's label from its control. Rows share one min-height so
855
+ a 24px toggle or a bare checkbox lines up with a 32px input in the neighbour cell. */
855
856
  html[data-standalone] .dshm-settings-grid {
856
857
  display: grid;
857
858
  grid-template-columns: repeat(2, minmax(0, 1fr));
@@ -861,15 +862,30 @@ html[data-standalone] .dshm-settings-grid {
861
862
  html[data-standalone] .dshm-settings-grid > label {
862
863
  margin: 5px 0;
863
864
  min-width: 0;
865
+ min-height: 42px;
864
866
  }
865
867
  html[data-standalone] .dshm-settings-grid input:not([type="checkbox"]):not([type="radio"]),
866
868
  html[data-standalone] .dshm-settings-grid select {
867
869
  width: 100%;
868
870
  max-width: 280px;
869
871
  }
872
+ html[data-standalone] .dshm-settings-grid input[type="checkbox"] {
873
+ width: 15px;
874
+ height: 15px;
875
+ margin: 0;
876
+ flex: 0 0 auto;
877
+ }
878
+ /* The tool allowlist input arrives without S.input; give it the same height and
879
+ radius as its neighbours so the grid reads as one control size. */
880
+ html[data-standalone] .dshm-settings-grid .dshm-inbound-tools {
881
+ height: 32px;
882
+ padding: 0 10px;
883
+ border-radius: 9px;
884
+ }
870
885
  html[data-standalone] .dshm-settings-note {
871
886
  grid-column: 1 / -1;
872
887
  margin-top: 8px !important;
888
+ white-space: pre-line;
873
889
  }
874
890
  @media (max-width: 1250px) {
875
891
  html[data-standalone] .dshm-settings-grid {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-memu-memory",
3
3
  "icon": "./assets/icon.png",
4
- "version": "1.2.5",
4
+ "version": "1.2.7",
5
5
  "description": "面向长篇 RP 与陪伴对话的 DeepSeek Harness 记忆插件:三层记忆、逐轮召回、来源标注、关系图、图片附件与独立 WebUI。",
6
6
  "keywords": [
7
7
  "deepseek-harness",
@@ -0,0 +1,142 @@
1
+ // 召回基准台(1.3.0 P1-3):对比 HEAD 基线与施工后 lib 的检索质量与延迟。
2
+ //
3
+ // 用法:
4
+ // node scripts/bench-recall.mjs # 测当前仓库 lib
5
+ // node scripts/bench-recall.mjs --lib <路径>/lib # 测指定 lib(如 HEAD 基线 worktree)
6
+ //
7
+ // 设计:
8
+ // - 完全确定性:语料与查询由固定种子 LCG 生成,两次运行同输入同输出,前后版本可比。
9
+ // - 指标:rankPairCandidates 延迟(N=300 精确两两 / N=2000 blocking 两档)、
10
+ // buildCandidateClusters 延迟、Recall@10 / MRR(查询 → 目标条目是否进前 10)。
11
+ // - 不引入任何依赖;被测导出(buildCorpus/rankPairCandidates/buildCandidateClusters)
12
+ // 是 curator.js/global-graph.js 的既有公共面,任何施工都不应改动其签名。
13
+
14
+ import { pathToFileURL, fileURLToPath } from 'node:url'
15
+ import { performance } from 'node:perf_hooks'
16
+
17
+ function parseLibArg(argv) {
18
+ const i = argv.indexOf('--lib')
19
+ if (i >= 0 && argv[i + 1]) return String(argv[i + 1]).replace(/[\\/]+$/, '')
20
+ return fileURLToPath(new URL('../lib', import.meta.url)).replace(/[\\/]+$/, '')
21
+ }
22
+
23
+ // —— 确定性随机(mulberry32 风格,无 clock/全局态)——
24
+ function lcg(seed) {
25
+ let s = seed >>> 0
26
+ return () => {
27
+ s = (s + 0x6D2B79F5) >>> 0
28
+ let t = s
29
+ t = Math.imul(t ^ (t >>> 15), t | 1)
30
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
31
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
32
+ }
33
+ }
34
+
35
+ // —— 合成语料:中英混合的记忆条目 ——
36
+ const CN_TOPICS = ['缓存策略', '部署流程', '数据库备份', '通知偏好', '角色设定', '会话管理', '向量检索', '日志轮转', '权限边界', '情绪记忆']
37
+ const CN_DETAIL = ['统一走内存队列', '保留 14 天后轮转', '每天凌晨三点执行', '失败时只发一次告警', '按库串行化写入', '先回应当下再回扣过去', '召回前先查旧条目', '到期前升级为长期', '跨域只 link 不吸收', '冲突进入待复核']
38
+ const EN_TOKENS = ['redis', 'postgres', 'bm25', 'embedding', 'workspace', 'session', 'curator', 'checkpoint', 'rollback', 'throttle']
39
+ const DOMAINS = ['coding', 'rp', 'general']
40
+
41
+ function makeEntry(rand, id) {
42
+ const topic = CN_TOPICS[Math.floor(rand() * CN_TOPICS.length)]
43
+ const detail = CN_DETAIL[Math.floor(rand() * CN_DETAIL.length)]
44
+ const en = EN_TOKENS[Math.floor(rand() * EN_TOKENS.length)]
45
+ const domain = DOMAINS[Math.floor(rand() * DOMAINS.length)]
46
+ return {
47
+ id: `mem-${String(id).padStart(4, '0')}`,
48
+ title: `${topic}(${en})`,
49
+ content: `${topic}${detail},${en} 相关配置在 2026-0${1 + Math.floor(rand() * 9)}-1${Math.floor(rand() * 9)} 调整过,适用域 ${domain}。`,
50
+ track: 'memory',
51
+ domain,
52
+ appliesTo: rand() < 0.4 ? [`entity-${Math.floor(rand() * 8)}`] : [],
53
+ updatedAt: `2026-11-${String(1 + Math.floor(rand() * 27)).padStart(2, '0')}T10:00:00Z`,
54
+ status: 'active',
55
+ }
56
+ }
57
+
58
+ function buildEntries(n, seed = 20261106) {
59
+ const rand = lcg(seed)
60
+ return Array.from({ length: n }, (_, i) => makeEntry(rand, i))
61
+ }
62
+
63
+ // —— 评测查询:目标条目的换序改写(测试「换个说法还能不能找回」)——
64
+ function buildQueries(entries, rand) {
65
+ return entries.map((entry) => {
66
+ const en = (entry.title.match(/[a-z0-9]+/i) || ['memory'])[0]
67
+ const topic = entry.title.split(/(/)[0]
68
+ const query = rand() < 0.5
69
+ ? `之前关于${topic}和 ${en} 的那条记忆`
70
+ : `${en} ${topic} 是怎么定的来着`
71
+ return { query, target: entry.id }
72
+ })
73
+ }
74
+
75
+ function recallAtK(results, target, k = 10) {
76
+ return results.slice(0, k).some((r) => r.id === target) ? 1 : 0
77
+ }
78
+
79
+ function mrr(results, target) {
80
+ const i = results.findIndex((r) => r.id === target)
81
+ return i < 0 ? 0 : 1 / (i + 1)
82
+ }
83
+
84
+ function bench(name, fn, runs = 5) {
85
+ // 预热一次再计时,取中位数,避免首跑 JIT/IO 噪声。
86
+ fn()
87
+ const samples = []
88
+ for (let i = 0; i < runs; i++) {
89
+ const t0 = performance.now()
90
+ fn()
91
+ samples.push(performance.now() - t0)
92
+ }
93
+ samples.sort((a, b) => a - b)
94
+ return { name, median: samples[Math.floor(runs / 2)], min: samples[0] }
95
+ }
96
+
97
+ async function main() {
98
+ const libPath = parseLibArg(process.argv)
99
+ const mod = await import(pathToFileURL(`${libPath}/text-retrieval.js`).href)
100
+ const { buildCorpus, rankPairCandidates, buildCandidateClusters } = mod
101
+ console.log(`被测 lib: ${libPath}`)
102
+ if (typeof mod.tokenize === 'function') {
103
+ const probe = JSON.stringify([...new Set(mod.tokenize('向量检索与缓存策略'))])
104
+ console.log(`tokenize 探针: ${probe.slice(0, 120)}`)
105
+ }
106
+
107
+ // —— 延迟:N=300(精确两两档)与 N=2000(blocking 档)——
108
+ for (const n of [300, 2000]) {
109
+ const entries = buildEntries(n)
110
+ const corpus = buildCorpus(entries.map((e) => ({ ...e })))
111
+ const proposal = entries[Math.floor(n / 2)]
112
+ const r1 = bench(`rankPairCandidates N=${n}`, () => rankPairCandidates({ corpus, proposal, limit: 20 }))
113
+ console.log(`${r1.name.padEnd(34)} median=${r1.median.toFixed(2)}ms min=${r1.min.toFixed(2)}ms`)
114
+ }
115
+
116
+ // —— 延迟:候选簇(§4.4)——
117
+ {
118
+ const entries = buildEntries(500)
119
+ const index = Object.fromEntries(entries.map((e) => [e.id, e]))
120
+ const r2 = bench('buildCandidateClusters N=500', () => buildCandidateClusters(index), 3)
121
+ console.log(`${r2.name.padEnd(34)} median=${r2.median.toFixed(2)}ms min=${r2.min.toFixed(2)}ms`)
122
+ }
123
+
124
+ // —— 质量:Recall@10 / MRR ——
125
+ {
126
+ const entries = buildEntries(400)
127
+ const rand = lcg(99)
128
+ const queries = buildQueries(entries, rand)
129
+ const corpus = buildCorpus(entries.map((e) => ({ ...e })))
130
+ let hit10 = 0
131
+ let rrSum = 0
132
+ for (const { query, target } of queries) {
133
+ const results = rankPairCandidates({ corpus, proposal: { title: query, content: '', track: 'memory', domain: 'general' }, limit: 20 })
134
+ hit10 += recallAtK(results, target)
135
+ rrSum += mrr(results, target)
136
+ }
137
+ const n = queries.length
138
+ console.log(`Recall@10 = ${(hit10 / n).toFixed(4)} MRR = ${(rrSum / n).toFixed(4)} (queries=${n})`)
139
+ }
140
+ }
141
+
142
+ main().catch((error) => { console.error(error); process.exitCode = 1 })
@@ -0,0 +1,118 @@
1
+ // 种子兼容检查 — 验证本插件的整理 fork 种子能被目标宿主的 Session 校验接受。
2
+ //
3
+ // node scripts/check-seed-compat.mjs --session-pkg <@deepseek-ai/dsh-session/lib/index.js 路径>
4
+ //
5
+ // 背景(1.3.0 实测):DSH 0.2.2-rc.1 的种子校验(assertAssistantSettlementShape)
6
+ // 要求 assistant/message 的 data.stream 是数组,而插件曾直接 delete 该字段,导致
7
+ // 0.2.2-rc.1 上每个整理 fork 种子都被拒("invalid settlement fields")。修复后种子
8
+ // 携带空数组。本脚本把「compactSeedEvents 产物 → 宿主 Session.create」这一环固化成
9
+ // 可重复执行的真机检查:新宿主版本的适配检查表(docs/host-adaptation.md §5.4)应
10
+ // 先跑这一步,再跑完整整理作业。
11
+ //
12
+ // 退出码:0 = 种子被宿主接受;1 = 被拒或环境问题(错误里说明是哪一环)。
13
+
14
+ import { pathToFileURL } from 'node:url'
15
+ import fs from 'node:fs'
16
+ import os from 'node:os'
17
+ import path from 'node:path'
18
+ import { createRequire } from 'node:module'
19
+ import { registerHooks } from 'node:module'
20
+
21
+ // 插件 lib 的导入链里有宿主 peer(@deepseek-ai/*),脱离宿主运行时需要测试桩。
22
+ // 但桩必须**按导入方作用域**生效:被检查的宿主真包自己也 import @deepseek-ai/dsh-llm,
23
+ // 无条件映射会拦掉真包之间的依赖(实测报 does not provide an export named …)。
24
+ // 因此只有 parentURL 落在本仓库 lib/ 内的导入才映射到桩;宿主包相互导入走真解析。
25
+ const STUBS = {
26
+ '@deepseek-ai/dsh-tools': 'dsh-tools.js',
27
+ '@deepseek-ai/dsh-llm': 'dsh-llm.js',
28
+ '@deepseek-ai/dsh-session': 'dsh-session.js',
29
+ '@deepseek-ai/dsh-llm-pi-ai': 'dsh-llm-pi-ai.js',
30
+ }
31
+ registerHooks({
32
+ resolve(specifier, context, next) {
33
+ const parent = String(context.parentURL || '')
34
+ const stub = STUBS[specifier]
35
+ if (stub && parent.includes('/dsh-memu-memory/lib/')) {
36
+ return { url: new URL('../tests/stubs/' + stub, import.meta.url).href, shortCircuit: true }
37
+ }
38
+ return next(specifier, context)
39
+ },
40
+ })
41
+
42
+ function parseArgs(argv) {
43
+ const out = {}
44
+ for (let i = 2; i < argv.length; i++) {
45
+ if (argv[i] === '--session-pkg') out.sessionPkg = argv[++i]
46
+ }
47
+ return out
48
+ }
49
+
50
+ const args = parseArgs(process.argv)
51
+ if (!args.sessionPkg) {
52
+ console.error('用法: node scripts/check-seed-compat.mjs --session-pkg <…/node_modules/@deepseek-ai/dsh-session/lib/index.js>')
53
+ console.error('路径在启动器安装里通常是 versions/<版本>/node_modules/@deepseek-ai/dsh-session/lib/index.js(pnpm 树内用 find 定位)。')
54
+ process.exit(1)
55
+ }
56
+ if (!fs.existsSync(args.sessionPkg)) {
57
+ console.error('session 包不存在: ' + args.sessionPkg)
58
+ process.exit(1)
59
+ }
60
+
61
+ // compactSeedEvents 会写 consolidation.json 之外还可能触达插件状态面:隔离到临时目录,
62
+ // 与 npm run replay 同一手法。检查本身是纯内存的,这只是防御。
63
+ process.env.DSH_MEMU_MEMORY_HOME = process.env.DSH_MEMU_HOME =
64
+ fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-seed-compat-'))
65
+
66
+ const { Session, buildForkSeed } = await import(pathToFileURL(args.sessionPkg).href)
67
+ const { compactSeedEvents } = await import(new URL('../lib/private.js', import.meta.url).href)
68
+
69
+ // 真实形状的事件(字段取自 0.2.x 真机会话,正文已替换为探针文本):宿主校验只看
70
+ // 形状(id / source / turn / step / stream),不看内容。assistant 必须带 message.id
71
+ //(缺了会报 "lacks an identified message",那是事件形状问题,不是插件种子问题)。
72
+ const T = 1793700000000
73
+ const events = [
74
+ {
75
+ type: 'user/message', seq: 0, time: T,
76
+ data: { content: [{ type: 'text', text: '探针:请记住这件事。' }], source: { kind: 'user' }, role: 'user', id: 'probe-user-1' },
77
+ surfaceOp: 'append',
78
+ },
79
+ {
80
+ type: 'assistant/message', seq: 1, time: T,
81
+ data: {
82
+ message: {
83
+ id: 'probe-asst-1', role: 'assistant',
84
+ // source 必须是完整的 model 来源形状(provider/model 缺一不可——宿主校验
85
+ // "message must have model source"),replayState 会被 compactSeedEvents 摘除。
86
+ content: [{ type: 'text', text: '探针回复,正文不重要。' }],
87
+ source: { kind: 'model', provider: 'probe', model: 'probe-model' },
88
+ },
89
+ turn: 0, step: 0,
90
+ usage: {},
91
+ stream: [{ type: 'text', text: '探针回复,正文不重要。' }],
92
+ },
93
+ surfaceOp: 'append',
94
+ },
95
+ ]
96
+
97
+ let hostVersion = 'unknown'
98
+ try {
99
+ const require_ = createRequire(pathToFileURL(args.sessionPkg).href)
100
+ hostVersion = require_('@deepseek-ai/dsh-session/package.json')?.version || 'unknown'
101
+ } catch {}
102
+
103
+ const compacted = compactSeedEvents(events)
104
+ const streamShape = compacted.find(e => e.type === 'assistant/message')?.data?.stream
105
+ console.log(`宿主 dsh-session: ${hostVersion}`)
106
+ console.log(`compactSeedEvents 产出的 assistant data.stream: ${Array.isArray(streamShape) ? `数组(${streamShape.length} 项)` : JSON.stringify(streamShape)}`)
107
+
108
+ try {
109
+ const seed = buildForkSeed(compacted, compacted.length - 1)
110
+ const header = { version: 4, id: 'dsh-memu-seed-compat', createdAt: T, cwd: process.cwd(), isSeeded: true }
111
+ Session.create('dsh-memu-seed-compat', seed, header, compacted.length)
112
+ console.log('结果: PASS —— 整理 fork 种子被该宿主接受。')
113
+ process.exit(0)
114
+ } catch (error) {
115
+ console.error('结果: FAIL —— 种子被宿主拒绝:', error?.message || error)
116
+ console.error('排查方向: 宿主种子校验(assertAssistantSettlementShape 一类)与 lib/private.js compactSeedEvents 的事件形状假设出现漂移。')
117
+ process.exit(1)
118
+ }
@@ -48,7 +48,8 @@ globalThis.__curatorAbsorbReviewTest = {
48
48
 
49
49
  const memuSource = 'const bridge = globalThis.__curatorAbsorbReviewTest;'
50
50
  + 'export const commit = (args) => bridge.commit(args), forget = (args) => bridge.forget(args),'
51
- + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args);'
51
+ + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args),'
52
+ + 'closeMemuResident = () => 0, prewarmMemuResident = async () => false;'
52
53
  const hooks = registerHooks({
53
54
  resolve(specifier, context, nextResolve) {
54
55
  if (specifier === './memu.js') return { url: 'data:text/javascript,' + encodeURIComponent(memuSource), shortCircuit: true }
@@ -36,7 +36,7 @@ const backend = {
36
36
  }
37
37
 
38
38
  globalThis.__backendCompensationTest = backend
39
- const engineSource = 'const bridge = globalThis.__backendCompensationTest; export const commit = bridge.commit, retrieve = bridge.retrieve, forget = bridge.forget, listFiles = bridge.listFiles;'
39
+ const engineSource = 'const bridge = globalThis.__backendCompensationTest; export const commit = bridge.commit, retrieve = bridge.retrieve, forget = bridge.forget, listFiles = bridge.listFiles, closeMemuResident = () => 0, prewarmMemuResident = async () => false;'
40
40
  const hooks = registerHooks({
41
41
  resolve(specifier, context, nextResolve) {
42
42
  if (specifier === './memu.js') {
@@ -9,9 +9,11 @@ process.env.DSH_MEMU_HOME = home
9
9
 
10
10
  const state = await import('../lib/state.js')
11
11
  const activity = await import('../lib/activity-log.js')
12
- const { requestPrivateConsolidation, isConsolidating, consolidationWaitBudget, CONSOLIDATION_WAIT_POLICY } = await import('../lib/private.js')
12
+ const forkModel = await import('../lib/fork-model.js')
13
+ const { requestPrivateConsolidation, isConsolidating, consolidationWaitBudget, CONSOLIDATION_WAIT_POLICY, CONSOLIDATION_WINDOW_EVENTS, compactSeedEvents, selectConsolidationWindow, selectTailTurnWindow } = await import('../lib/private.js')
13
14
 
14
15
  test.after(() => {
16
+ forkModel.disposeConsolidationRoute()
15
17
  try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
16
18
  })
17
19
 
@@ -53,7 +55,7 @@ function assertHostCreateAccepts(spec = {}) {
53
55
  }
54
56
  }
55
57
 
56
- function host({ live = false, whenIdle = null, parentOptions = { provider: 'test-provider', model: 'test-model' }, requestConfig = null, extraEvents = [], transcriptSize = 0, turnReason = { kind: 'completed' }, emitTurnEnd = true, headerTools = null, childCtxFactory = null } = {}) {
58
+ function host({ live = false, whenIdle = null, parentOptions = { provider: 'test-provider', model: 'test-model' }, requestConfig = null, extraEvents = [], transcriptSize = 0, turnReason = { kind: 'completed' }, emitTurnEnd = true, headerTools = null, childCtxFactory = null, llm = null } = {}) {
57
59
  const rec = { liveFollowups: [], created: [], forkFollowups: [], disposed: [], sessionHandlers: [], workerToolRegistrations: [], workerToolDisposals: [] }
58
60
  const childContexts = new Map()
59
61
  const tick = String.fromCharCode(96)
@@ -100,9 +102,15 @@ function host({ live = false, whenIdle = null, parentOptions = { provider: 'test
100
102
  rec.forkFollowups.push({ child: spec.sessionId, message })
101
103
  if (emitTurnEnd) {
102
104
  if (turnReason?.kind === 'completed') {
103
- const throughSeq = 2 + extraEvents.length + padding
105
+ // The worker receipt must match the window the fork was seeded
106
+ // with, not the whole parent transcript.
107
+ const child = state.getSessionBinding(spec.sessionId)
108
+ const fromSeq = Number.isSafeInteger(child?.snapshotFromSeq) ? child.snapshotFromSeq : 0
109
+ const throughSeq = Number.isSafeInteger(child?.snapshotThroughSeq)
110
+ ? child.snapshotThroughSeq
111
+ : 2 + extraEvents.length + padding
104
112
  for (const handler of rec.sessionHandlers) {
105
- handler(childSession, { type: 'assistant/message', seq: 99, data: { message: { content: [{ type: 'text', text: receiptFence({ fromSeq: 0, throughSeq }, state.getSessionBinding(spec.sessionId)) }] } } })
113
+ handler(childSession, { type: 'assistant/message', seq: 99, data: { message: { content: [{ type: 'text', text: receiptFence({ fromSeq, throughSeq }, child) }] } } })
106
114
  }
107
115
  }
108
116
  for (const handler of rec.sessionHandlers) {
@@ -117,6 +125,9 @@ function host({ live = false, whenIdle = null, parentOptions = { provider: 'test
117
125
  },
118
126
  }
119
127
  }
128
+ // 整理 fork 的模型选择(lib/fork-model.js)按需探测的宿主 llm service;
129
+ // 缺省没有 = custom 模式必须降级回 inherit 的宿主形态。
130
+ if (name === 'llm') return llm
120
131
  if (name === 'sessionQuery') {
121
132
  return {
122
133
  readSession: async () => ({
@@ -213,7 +224,7 @@ test('a closed session inherits the last request/header event', async () => {
213
224
  const result = await requestPrivateConsolidation(ctx, 'fork-closed')
214
225
  assert.equal(result.ok, true)
215
226
  const spec = ctx.rec.created[0]
216
- assert.equal(spec.inheritedEventCount, 5, 'the header events are part of the inherited log')
227
+ assert.equal(spec.inheritedEventCount, 3, 'only conversation events are seeded; request/header is noise')
217
228
  assert.deepEqual(spec.agentOptions, { provider: 'latest', model: 'latest-model', reasoningEffort: 'low', maxTokens: 4096 })
218
229
  })
219
230
 
@@ -349,9 +360,9 @@ test('a large transcript with nothing new since the cursor does not refork', asy
349
360
  const result = await requestPrivateConsolidation(ctx, 'fork-large-thin')
350
361
  assert.equal(result.ok, true)
351
362
  assert.equal(result.skipped, 'no-human-turn', 'the increment carries no human turn to consolidate')
352
- assert.equal(result.settled, false, 'nothing was consolidated, so the cursor must not move')
363
+ assert.equal(result.settled, true, 'a policy skip is terminal: the idle sweep stops re-reading the same greetings')
353
364
  assert.equal(ctx.rec.created.length, 0, 'no fork when the pending increment has no evidence')
354
- assert.equal(state.getSessionBinding('fork-large-thin').lastSleepSeq, 5905, 'the cursor must not advance')
365
+ assert.equal(state.getSessionBinding('fork-large-thin').lastSleepSeq, 5912, 'a terminal policy skip advances the coarse cursor so the same thin tail is not rescanned')
355
366
  })
356
367
 
357
368
  test('a large transcript that was never consolidated does fork, because the backlog is real', async () => {
@@ -365,6 +376,75 @@ test('a large transcript that was never consolidated does fork, because the back
365
376
  assert.equal(result.ok, true, 'the backlog bound lets this one through')
366
377
  assert.equal(ctx.rec.created.length, 1, 'a large unconsolidated backlog is worth exactly one fork')
367
378
  })
379
+ // ---------------------------------------------------------------- window & seed
380
+ test('the seed keeps conversation only, renumbers from zero, and strips replay/stream noise', () => {
381
+ const plugin = { seq: 0, type: 'user/message', data: { source: { kind: 'plugin:dsh-memu-memory', form: 'recall' }, content: [{ type: 'text', text: '旧召回' }] } }
382
+ const runtime = { seq: 1, type: 'user/message', data: { source: { kind: 'runtime-context', form: 'snapshot' }, content: [{ type: 'text', text: '运行时快照' }] } }
383
+ const header = { seq: 2, type: 'request/header', data: { header: {} } }
384
+ const user = { seq: 3, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '记住:我不吃香菜' }] } }
385
+ const assistant = { seq: 4, type: 'assistant/message', data: {
386
+ message: {
387
+ source: { provider: 'p', model: 'm', replayState: { huge: 'x'.repeat(400) } },
388
+ content: [{ type: 'reasoning', text: '思考过程' }, { type: 'text', text: '好的' }, { type: 'tool-call', name: 'read', arguments: 'x'.repeat(2000) }],
389
+ },
390
+ stream: { blob: 'y'.repeat(400) },
391
+ } }
392
+ const repeated = 'R'.repeat(4000)
393
+ const tool1 = { seq: 5, type: 'tool/result', data: { message: { content: [{ type: 'text', text: repeated }] } } }
394
+ const tool2 = { seq: 6, type: 'tool/result', data: { message: { content: [{ type: 'text', text: repeated }] } } }
395
+ const catalog = {
396
+ type: 'user/message', seq: 0, time: 1, surfaceOp: 'append',
397
+ data: { role: 'user', source: { kind: 'plugin:dsh-memu-memory', form: 'notice' }, content: [{ type: 'text', text: '已有记忆目录' }] },
398
+ }
399
+ const seed = compactSeedEvents([plugin, runtime, header, user, assistant, tool1, tool2], catalog)
400
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2, 3, 4], 'contiguous from zero, catalog at 0')
401
+ assert.match(seed[0].data.content[0].text, /已有记忆目录/)
402
+ assert.equal(seed[1].data.source.kind, 'user', 'only real user messages survive')
403
+ const msg = seed[2].data.message
404
+ assert.equal(msg.content.some(block => block.type === 'reasoning'), false, 'reasoning is not evidence')
405
+ assert.equal(msg.source.replayState, undefined, 'replay state duplicates the body')
406
+ assert.deepEqual(seed[2].data.stream, [], 'the raw chunk log is emptied, not deleted — 0.2.2-rc.1 seed validation requires the array')
407
+ assert.match(msg.content.find(block => block.type === 'tool-call').arguments, /已截断/)
408
+ assert.match(seed[3].data.message.content[0].text, /已截断/)
409
+ assert.match(seed[4].data.message.content[0].text, /与前面相同的工具输出/, 'identical tool output is deduped')
410
+ })
411
+
412
+ test('a long tail is cut to one closed-turn window with a remainder', () => {
413
+ const events = Array.from({ length: CONSOLIDATION_WINDOW_EVENTS + 180 }, (_, seq) => ({ seq, type: 'todo/write', data: {} }))
414
+ const window = selectConsolidationWindow(events)
415
+ assert.equal(window.fromSeq, 0)
416
+ assert.ok(window.events.length <= CONSOLIDATION_WINDOW_EVENTS, 'the window stays bounded')
417
+ assert.ok(window.remaining > 0, 'the rest is left for the next sweep')
418
+ assert.ok(window.throughSeq < events.length - 1)
419
+ })
420
+
421
+ test('a manual re-check starts at a complete turn instead of mid-step', () => {
422
+ const events = [
423
+ { seq: 0, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '旧回答' }] } } },
424
+ { seq: 1, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '最后一问' }] } },
425
+ { seq: 2, type: 'turn/start', data: { turn: 2 } },
426
+ { seq: 3, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '最后回答' }] } } },
427
+ { seq: 4, type: 'turn/end', data: { turn: 2, reason: { kind: 'completed' } } },
428
+ ]
429
+ const window = selectTailTurnWindow(events)
430
+ assert.equal(window.fromSeq, 1, 'the user message that opened the turn is included')
431
+ assert.equal(window.throughSeq, 4, 'the window ends on a closed turn')
432
+ })
433
+
434
+ test('the same failed snapshot stops re-forking after the failure cap', async () => {
435
+ state.ensureSession('fork-failcap', { cwd: path.join(home, 'proj-failcap'), agentPreset: 'coding' })
436
+ const ctx = host({ live: true, turnReason: { kind: 'error', error: { message: 'provider refused' } } })
437
+ const first = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
438
+ const second = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
439
+ assert.equal(first.ok, false)
440
+ assert.equal(second.ok, false)
441
+ assert.equal(ctx.rec.created.length, 2, 'two real attempts happen')
442
+ const third = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
443
+ assert.equal(third.ok, true)
444
+ assert.equal(third.skipped, 'snapshot-failed')
445
+ assert.equal(ctx.rec.created.length, 2, 'the third call does not pay for the same snapshot again')
446
+ })
447
+
368
448
  // ---------------------------------------------------------------- PTC 兼容
369
449
  // 现场(2026-10-31,yuike-ptc 会话):PTC 模式下 request/header 的工具表只有 run_code,
370
450
  // probe 曾据此判 unavailable(worker-tools-ptc-only),PTC 会话永远不被整理。宿主的
@@ -502,3 +582,115 @@ test('the consolidation wait budget scales with the transcript, not a fixed 180
502
582
  assert.equal(consolidationWaitBudget('not-a-number'), CONSOLIDATION_WAIT_POLICY.minMs)
503
583
  assert.ok(CONSOLIDATION_WAIT_POLICY.minMs <= CONSOLIDATION_WAIT_POLICY.maxMs)
504
584
  })
585
+
586
+ // ---------------------------------------------------------------- 整理 fork 的模型选择(三模式接线)
587
+ // lib/fork-model.js 的解析与 route 生命周期在 fork-model.test.mjs 单测;这里钉住接线行为:
588
+ // fork 真正拿到的 agentOptions、被拒时的 reasonCode、以及 inherit 模式与旧路径逐字节一致。
589
+
590
+ function servingLlm() {
591
+ const llm = {
592
+ registerAdapter: (routes) => {
593
+ const handle = () => {}
594
+ handle.replace = () => {}
595
+ return handle
596
+ },
597
+ listModels: async (provider) => [{ provider, id: 'any', name: 'route serves models', inputModalities: ['text'] }],
598
+ }
599
+ return llm
600
+ }
601
+
602
+ const CUSTOM = {
603
+ consolidationModelMode: 'custom',
604
+ consolidationCustomBaseURL: 'http://127.0.0.1:9100/v1',
605
+ consolidationCustomModel: 'gateway-model',
606
+ consolidationCustomApiKey: '',
607
+ }
608
+
609
+ function restoreSettings() {
610
+ state.updateSettings({
611
+ consolidationModelMode: 'inherit',
612
+ consolidationModel: null,
613
+ consolidationCustomBaseURL: '',
614
+ consolidationCustomApiKey: '',
615
+ consolidationCustomModel: '',
616
+ consolidationCustomApi: 'openai-completions',
617
+ })
618
+ }
619
+
620
+ test('custom mode puts the fork on the registered dsh-memu-custom route', async () => {
621
+ state.updateSettings(CUSTOM)
622
+ try {
623
+ state.ensureSession('fork-mode-custom', { cwd: path.join(home, 'proj-mode-custom'), agentPreset: 'coding' })
624
+ const ctx = host({ live: true, llm: servingLlm() })
625
+ const result = await requestPrivateConsolidation(ctx, 'fork-mode-custom')
626
+ assert.equal(result.ok, true, String(result.error || ''))
627
+ assert.equal(result.settled, true)
628
+ assert.equal(ctx.rec.created.length, 1)
629
+ assert.deepEqual(ctx.rec.created[0].agentOptions, { provider: 'dsh-memu-custom', model: 'gateway-model' }, 'the fork names the plugin-owned custom route')
630
+ const started = startedEntryFor(ctx, 'fork-mode-custom')
631
+ assert.equal(started.detail.modelMode, 'custom')
632
+ } finally {
633
+ forkModel.disposeConsolidationRoute()
634
+ restoreSettings()
635
+ }
636
+ })
637
+
638
+ test('custom mode falls back to the inherited route when the host cannot serve the custom route', async () => {
639
+ state.updateSettings(CUSTOM)
640
+ try {
641
+ state.ensureSession('fork-mode-fallback', { cwd: path.join(home, 'proj-mode-fallback'), agentPreset: 'coding' })
642
+ // 没有 llm service 的宿主:custom 不可用,降级回父会话 route,整理照常完成。
643
+ const ctx = host({ live: true, parentOptions: { provider: 'fallback-prov', model: 'fallback-model' } })
644
+ const result = await requestPrivateConsolidation(ctx, 'fork-mode-fallback')
645
+ assert.equal(result.ok, true, String(result.error || ''))
646
+ assert.deepEqual(ctx.rec.created[0].agentOptions, { provider: 'fallback-prov', model: 'fallback-model' }, 'the fork falls back to the parent route instead of dying')
647
+ const started = startedEntryFor(ctx, 'fork-mode-fallback')
648
+ assert.equal(started.detail.modelMode, 'inherit-fallback')
649
+ } finally {
650
+ restoreSettings()
651
+ }
652
+ })
653
+
654
+ test('custom mode without a usable custom route and without a parent route is refused', async () => {
655
+ state.updateSettings(CUSTOM)
656
+ try {
657
+ state.ensureSession('fork-mode-custom-dead', { cwd: path.join(home, 'proj-mode-dead'), agentPreset: 'coding' })
658
+ const ctx = host({ live: true, parentOptions: null })
659
+ const result = await requestPrivateConsolidation(ctx, 'fork-mode-custom-dead')
660
+ assert.equal(result.ok, false)
661
+ assert.equal(result.reasonCode, 'custom-route-unavailable')
662
+ assert.match(result.error, /custom consolidation route is unavailable/)
663
+ assert.equal(ctx.rec.created.length, 0)
664
+ } finally {
665
+ restoreSettings()
666
+ }
667
+ })
668
+
669
+ test('host mode resolves consolidationModel the same way the curator does', async () => {
670
+ state.updateSettings({ consolidationModelMode: 'host', consolidationModel: 'host-prov/host-model/nested' })
671
+ try {
672
+ state.ensureSession('fork-mode-host', { cwd: path.join(home, 'proj-mode-host'), agentPreset: 'coding' })
673
+ const ctx = host({ live: true, parentOptions: { provider: 'other', model: 'other-model' } })
674
+ const result = await requestPrivateConsolidation(ctx, 'fork-mode-host')
675
+ assert.equal(result.ok, true, String(result.error || ''))
676
+ assert.deepEqual(ctx.rec.created[0].agentOptions, { provider: 'host-prov', model: 'host-model/nested' }, 'everything after the first slash is the model id')
677
+ assert.equal(startedEntryFor(ctx, 'fork-mode-host').detail.modelMode, 'host')
678
+ } finally {
679
+ restoreSettings()
680
+ }
681
+ })
682
+
683
+ test('a bad host consolidationModel is refused with its own reason, not the parent one', async () => {
684
+ state.updateSettings({ consolidationModelMode: 'host', consolidationModel: 'no-slash' })
685
+ try {
686
+ state.ensureSession('fork-mode-host-bad', { cwd: path.join(home, 'proj-mode-host-bad'), agentPreset: 'coding' })
687
+ const ctx = host({ live: true })
688
+ const result = await requestPrivateConsolidation(ctx, 'fork-mode-host-bad')
689
+ assert.equal(result.ok, false)
690
+ assert.equal(result.reasonCode, 'invalid-consolidation-model')
691
+ assert.match(result.error, /consolidation model \(/, 'the new reasons name the bad configuration face, not the parent route')
692
+ assert.equal(ctx.rec.created.length, 0)
693
+ } finally {
694
+ restoreSettings()
695
+ }
696
+ })
@@ -51,7 +51,8 @@ globalThis.__curatorAbsorbTest = {
51
51
 
52
52
  const memuSource = 'const bridge = globalThis.__curatorAbsorbTest;'
53
53
  + 'export const commit = (args) => bridge.commit(args), forget = (args) => bridge.forget(args),'
54
- + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args);'
54
+ + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args),'
55
+ + 'closeMemuResident = () => 0, prewarmMemuResident = async () => false;'
55
56
  const hooks = registerHooks({
56
57
  resolve(specifier, context, nextResolve) {
57
58
  if (specifier === './memu.js') return { url: 'data:text/javascript,' + encodeURIComponent(memuSource), shortCircuit: true }
@@ -24,7 +24,8 @@ globalThis.__curatorClusterTest = {
24
24
  }
25
25
  const memuSource = 'const bridge = globalThis.__curatorClusterTest;'
26
26
  + 'export const commit = (args) => bridge.commit(args), forget = (args) => bridge.forget(args),'
27
- + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args);'
27
+ + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args),'
28
+ + 'closeMemuResident = () => 0, prewarmMemuResident = async () => false;'
28
29
  const hooks = registerHooks({
29
30
  resolve(specifier, context, nextResolve) {
30
31
  if (specifier === './memu.js') return { url: 'data:text/javascript,' + encodeURIComponent(memuSource), shortCircuit: true }
@@ -201,7 +202,13 @@ test('>12 clusters are truncated by avg_score desc', () => {
201
202
  assert.equal(clusters.length, 12)
202
203
  const avgs = clusters.map((c) => c.avg_score)
203
204
  assert.deepEqual([...avgs].sort((a, b) => b - a), avgs, 'output stays avg_score-descending')
204
- for (const cluster of clusters) assert.equal(cluster.suggested_op, 'link')
205
+ // P0-1 分数漂移:pair-1 与 pair-11(仅数字位数不同的变体)在 V2 的 unigram
206
+ // 层下 tokenJaccard 升高,跨对分数过 0.82 合法并簇(charDice 主导的真相似,
207
+ // 不是噪声)→「15 对收成 12 簇、avg 降序截断」的意图不变;op 断言放宽为
208
+ // 「link 或更好」。
209
+ for (const cluster of clusters) {
210
+ assert.ok(['link', 'absorb'].includes(cluster.suggested_op), `cluster in link-or-better band, got ${cluster.suggested_op}`)
211
+ }
205
212
  })
206
213
 
207
214
  test('recentLimit cuts the pool to the most recent entries and flags truncation', () => {
@@ -50,7 +50,8 @@ const realStateUrl = new URL('../lib/state.js', import.meta.url).href
50
50
  const realMemuUrl = new URL('../lib/memu.js', import.meta.url).href
51
51
  const memuSource = 'const bridge = globalThis.__curatorCommitTest;'
52
52
  + 'export const commit = (args) => bridge.commit(args), forget = (args) => bridge.forget(args),'
53
- + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args);'
53
+ + 'retrieve = (args) => bridge.retrieve(args), listFiles = (args) => bridge.listFiles(args),'
54
+ + 'closeMemuResident = () => 0, prewarmMemuResident = async () => false;'
54
55
  const stateSource = [
55
56
  `import * as real from ${JSON.stringify(realStateUrl)}`,
56
57
  'const hook = globalThis.__curatorIndexHook',