dsh-memu-memory 1.2.6 → 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.
@@ -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.6",
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
+ }
@@ -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 forkModel = await import('../lib/fork-model.js')
12
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)
@@ -123,6 +125,9 @@ function host({ live = false, whenIdle = null, parentOptions = { provider: 'test
123
125
  },
124
126
  }
125
127
  }
128
+ // 整理 fork 的模型选择(lib/fork-model.js)按需探测的宿主 llm service;
129
+ // 缺省没有 = custom 模式必须降级回 inherit 的宿主形态。
130
+ if (name === 'llm') return llm
126
131
  if (name === 'sessionQuery') {
127
132
  return {
128
133
  readSession: async () => ({
@@ -398,7 +403,7 @@ test('the seed keeps conversation only, renumbers from zero, and strips replay/s
398
403
  const msg = seed[2].data.message
399
404
  assert.equal(msg.content.some(block => block.type === 'reasoning'), false, 'reasoning is not evidence')
400
405
  assert.equal(msg.source.replayState, undefined, 'replay state duplicates the body')
401
- assert.equal(seed[2].data.stream, undefined, 'the raw chunk log is not the message')
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')
402
407
  assert.match(msg.content.find(block => block.type === 'tool-call').arguments, /已截断/)
403
408
  assert.match(seed[3].data.message.content[0].text, /已截断/)
404
409
  assert.match(seed[4].data.message.content[0].text, /与前面相同的工具输出/, 'identical tool output is deduped')
@@ -577,3 +582,115 @@ test('the consolidation wait budget scales with the transcript, not a fixed 180
577
582
  assert.equal(consolidationWaitBudget('not-a-number'), CONSOLIDATION_WAIT_POLICY.minMs)
578
583
  assert.ok(CONSOLIDATION_WAIT_POLICY.minMs <= CONSOLIDATION_WAIT_POLICY.maxMs)
579
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
+ })
@@ -202,7 +202,13 @@ test('>12 clusters are truncated by avg_score desc', () => {
202
202
  assert.equal(clusters.length, 12)
203
203
  const avgs = clusters.map((c) => c.avg_score)
204
204
  assert.deepEqual([...avgs].sort((a, b) => b - a), avgs, 'output stays avg_score-descending')
205
- 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
+ }
206
212
  })
207
213
 
208
214
  test('recentLimit cuts the pool to the most recent entries and flags truncation', () => {
@@ -22,8 +22,16 @@ test('tokenize: latin runs of >=2 chars keep ._ - joins, single chars drop', ()
22
22
  assert.deepEqual(tokenize('per-turn retry'), ['per-turn', 'retry'])
23
23
  })
24
24
 
25
- test('tokenize: CJK runs become overlapping bigrams, isolated chars stay single', () => {
26
- assert.deepEqual(tokenize('部署窗口'), ['部署', '署窗', '窗口'])
25
+ // P0-1 双轨切换(TOKENIZER_V2=true 默认):CJK 从「只出 bigram」升级为
26
+ // unigram+bigram+trigram 三层,4 字 run 另收完整串——断言按新口径更新,
27
+ // 「孤立单字保留、跨标点 run 独立」的意图不变。
28
+ test('tokenize: CJK runs become layered n-grams (V2), isolated chars stay single', () => {
29
+ assert.deepEqual(tokenize('部署窗口'), [
30
+ '部', '署', '窗', '口',
31
+ '部署', '署窗', '窗口',
32
+ '部署窗', '署窗口',
33
+ '部署窗口',
34
+ ])
27
35
  assert.deepEqual(tokenize('猫'), ['猫'])
28
36
  // two CJK runs separated by latin/punct stay separate runs
29
37
  assert.deepEqual(tokenize('猫。狗'), ['猫', '狗'])
@@ -31,7 +39,8 @@ test('tokenize: CJK runs become overlapping bigrams, isolated chars stay single'
31
39
 
32
40
  test('tokenize: NFKC folds full-width forms, lowercases, dedupes', () => {
33
41
  assert.deepEqual(tokenize('RISCV CACHE CACHE'), ['riscv', 'cache'])
34
- assert.deepEqual(tokenize('缓存 缓存'), ['缓存'])
42
+ // V2 去重后仍只保留一次出现;unigram 是新增层('缓存' bigram 依旧在)
43
+ assert.deepEqual(tokenize('缓存 缓存'), ['缓', '存', '缓存'])
35
44
  })
36
45
 
37
46
  // —— §4.1 buildCorpus + bm25 ——
@@ -173,7 +182,7 @@ function bigCorpus({ withTarget = true } = {}) {
173
182
  if (withTarget) {
174
183
  entries.push({ id: 'target', track: 'memory', domain: 'general', title: '缓存过期', content: 'Redis 缓存统一设置 30 秒过期,命中直接返回,不做全量。', appliesTo: ['deploy'], updatedAt: '2026-01-02T00:00:00.000Z' })
175
184
  entries.push({ id: 'title-only', track: 'memory', domain: 'general', title: '缓存过期', content: '完全不同的词汇组织起来的另一段内容。', updatedAt: '2026-01-03T00:00:00.000Z' })
176
- entries.push({ id: 'single-token', track: 'memory', domain: 'elsewhere', title: '项目排期', content: '安排下季度的路线图评审。', updatedAt: '2026-01-04T00:00:00.000Z' })
185
+ entries.push({ id: 'single-token', track: 'memory', domain: 'elsewhere', title: '咖啡豆', content: 'sync 每周补货一次。', updatedAt: '2026-01-04T00:00:00.000Z' })
177
186
  }
178
187
  return buildCorpus(entries)
179
188
  }
@@ -192,18 +201,20 @@ test('rankPairCandidates: blocking finds the shared-token target in a >300 corpu
192
201
 
193
202
  test('rankPairCandidates: exact-title entries enter even without shared tokens', () => {
194
203
  const corpus = bigCorpus()
195
- const proposal = { id: 'p', track: 'memory', domain: 'general', title: '缓存过期', content: '完全无重叠词元的新内容组合安排。', appliesTo: [] }
204
+ const proposal = { id: 'p', track: 'memory', domain: 'general', title: '缓存过期', content: '完全无重叠词元的新内容组合安排 sync。', appliesTo: [] }
196
205
  const found = rankPairCandidates({ corpus, proposal, limit: 20 })
197
206
  assert.ok(found.some((c) => c.id === 'title-only'))
198
207
  })
199
208
 
200
209
  test('rankPairCandidates: a one-shared-token candidate outside the proposal domain stays out', () => {
201
210
  const corpus = bigCorpus()
202
- const proposal = { id: 'p', track: 'memory', domain: 'general', title: '缓存过期', content: '完全无重叠词元的新内容组合安排。', appliesTo: [] }
211
+ const proposal = { id: 'p', track: 'memory', domain: 'general', title: '缓存过期', content: '完全无重叠词元的新内容组合安排 sync。', appliesTo: [] }
203
212
  const found = rankPairCandidates({ corpus, proposal, limit: 20 })
204
- // 'single-token' shares exactly one rare token (安排) with the proposal and
213
+ // 'single-token' shares exactly one rare token (sync) with the proposal and
205
214
  // sits in a different domain: blocking needs >=2 shared tokens and the
206
- // same-domain backfill never reaches a foreign domain.
215
+ // same-domain backfill never reaches a foreign domain. 共享词刻意选 latin——
216
+ // V2 分词会把 CJK 共享词拆出 unigram(安排 → 安排+安+排),latin token 不拆,
217
+ // 「只共享一个词不进候选」的意图在两种分词口径下都成立。
207
218
  assert.ok(!found.some((c) => c.id === 'single-token'))
208
219
  })
209
220
 
@@ -227,6 +238,39 @@ test('rankPairCandidates: deterministic — same input, same output', () => {
227
238
  assert.deepEqual(run1, run2)
228
239
  })
229
240
 
241
+ // —— §4.3 边界带(P0-1 回归修复的守卫):代理切分 → pairScore 真尺终选 ——
242
+ //
243
+ // 手算秩结构(可复现 fixture,文本两两相同造成 bm25/dice 精确并列,en 路由的
244
+ // containment tiebreak 由 cand-c/d 的逐字包含 0.92 垫高):
245
+ // cand-a: bm1, di1, en4 → rrf = 0.5/61 + 0.3/61 + 0.2/64 = 1.6240e-2(rank 1,切点)
246
+ // cand-b: bm2, di2, en1 → rrf = 0.5/62 + 0.3/62 + 0.2/61 = 1.6183e-2(rank 2,带内:
247
+ // 与切点差 (0.5+0.3)×(1/61−1/62) − 0.2×(1/61−1/64) = 5.78e-5 ≤ RRF_SLICE_BAND)
248
+ // cand-c/d: rrf 更低,带外(仅作 en 路由 containment 垫脚)。
249
+ // pairScore:cand-b 0.9894(entity 匹配)≫ cand-a 0.8394(appliesTo 不相交)。
250
+ // 修复前 pre-cut=limit=1 只评分 cand-a,返回 ['cand-a'];边界带把 cand-b 并入
251
+ // 评分集,真尺终选翻到 cand-b——准入从 RRF 代理换成 pairScore 真尺的直接证据。
252
+ test('rankPairCandidates: the slice boundary band admits a better-pairScore candidate the RRF proxy dropped', () => {
253
+ const twin = 'Redis 缓存统一设置 30 秒过期,命中直接返回。Redis 缓存统一设置 30 秒过期,命中直接返回。'
254
+ const tail = '。另有运维值班轮换表与告警升级路径的完整说明,这里补足长度让长度剪枝生效并保持逐字包含。'
255
+ const proposal = { title: '缓存过期', content: 'Redis 缓存统一设置 30 秒过期,命中直接返回。', appliesTo: ['deploy'], track: 'memory', domain: 'general' }
256
+ const corpus = buildCorpus([
257
+ { id: 'cand-a', title: '缓存过期', content: twin, appliesTo: [], track: 'memory', domain: 'general' },
258
+ { id: 'cand-b', title: '缓存过期', content: twin, appliesTo: ['deploy'], track: 'memory', domain: 'general' },
259
+ { id: 'cand-c', title: '缓存过期', content: proposal.content + tail, appliesTo: [], track: 'memory', domain: 'general' },
260
+ { id: 'cand-d', title: '缓存过期', content: proposal.content + tail, appliesTo: [], track: 'memory', domain: 'general' },
261
+ ])
262
+ const found = rankPairCandidates({ corpus, proposal, limit: 1 })
263
+ // 真尺终选:数量语义不变(≤max),赢家是带内 rescue 的高 pairScore 候选
264
+ assert.equal(found.length, 1)
265
+ assert.equal(found[0].id, 'cand-b')
266
+ // 赢家的 rrf 严格低于切点(cand-a 的手算 rrf)——证明它来自边界带而非 pre-cut
267
+ const cutRrf = 0.5 / (60 + 1) + 0.3 / (60 + 1) + 0.2 / (60 + 4)
268
+ assert.ok(found[0].rrf < cutRrf, `winner rrf ${found[0].rrf} must sit below the pre-cut line ${cutRrf}`)
269
+ // 被切掉的 cand-a 在真尺上确实更差(低 pairScore 者按 pairScore 出局)
270
+ const loserScore = pairScore(pairFeatures(proposal, corpus.docs.get('cand-a').entry))
271
+ assert.ok(found[0].score > loserScore, `band winner ${found[0].score} must beat the displaced candidate ${loserScore}`)
272
+ })
273
+
230
274
  // —— §4.8 全局冲突预筛 ——
231
275
 
232
276
  test('globalConflictCheck: same title + different body is same_title; negation flips conflict', () => {