dsh-memu-memory 1.2.7 → 1.2.9
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 +1 -1
- package/CHANGELOG.md +472 -0
- package/README.md +10 -15
- package/README.zh.md +10 -15
- package/docs/memory-semantics.md +23 -3
- package/lib/backup.js +155 -26
- package/lib/binding-diagnostics.js +1 -2
- package/lib/budget.js +31 -9
- package/lib/client.js +221 -128
- package/lib/commitment.js +138 -0
- package/lib/consolidation-ledger.js +5 -2
- package/lib/consolidation-receipt.js +2 -0
- package/lib/consolidation-worker.js +3 -0
- package/lib/curator-policy.js +23 -0
- package/lib/cycle.js +8 -4
- package/lib/embedding-download.js +168 -28
- package/lib/embedding-runtime.js +76 -17
- package/lib/engine.js +0 -6
- package/lib/freshness.js +24 -0
- package/lib/graph.js +139 -11
- package/lib/index.js +71 -20
- package/lib/inject.js +167 -17
- package/lib/lexicon.js +62 -17
- package/lib/local-vector-service.js +25 -2
- package/lib/media.js +49 -12
- package/lib/memory.js +1202 -123
- package/lib/memu.js +4 -0
- package/lib/paths.js +0 -7
- package/lib/preset-scope.js +6 -1
- package/lib/private.js +50 -10
- package/lib/prompts/private-consolidation.mixed.md +2 -2
- package/lib/prompts/private-consolidation.rp.md +6 -1
- package/lib/prompts/private-policy.rp.md +4 -0
- package/lib/prompts/system-guide.rp.md +3 -0
- package/lib/prompts.js +0 -7
- package/lib/recall-cache.js +10 -2
- package/lib/rpc.js +104 -19
- package/lib/snippet.js +41 -0
- package/lib/state.js +109 -30
- package/lib/stats.js +2 -2
- package/lib/temporal.js +348 -0
- package/lib/text-retrieval.js +191 -44
- package/lib/text-similarity.js +205 -24
- package/lib/tokenizer-v2.js +0 -24
- package/lib/tools.js +81 -4
- package/lib/vector-migration.js +15 -0
- package/lib/vector-profile.js +81 -8
- package/lib/visibility.js +0 -4
- package/lib/webui/standalone.css +17 -22
- package/lib/webui/standalone.js +27 -9
- package/lib/webui.js +4 -4
- package/package.json +3 -2
- package/scripts/acceptance-local.mjs +2 -2
- package/scripts/bench-recall.mjs +2 -2
- package/scripts/check-all.mjs +3 -1
- package/scripts/check-i18n.mjs +35 -1
- package/scripts/check-seed-compat.mjs +1 -1
- package/scripts/migrate-visibility.mjs +3 -3
- package/scripts/prune-sessions.mjs +34 -0
- package/scripts/prune-vectors.mjs +24 -0
- package/tests/appendix-b.test.mjs +5 -4
- package/tests/audit-batch3.test.mjs +247 -0
- package/tests/audit-regression.test.mjs +2 -2
- package/tests/backup.test.mjs +85 -85
- package/tests/browser.test.mjs +6 -1
- package/tests/client-render.test.mjs +2 -2
- package/tests/commitment.test.mjs +144 -0
- package/tests/consolidation-fork.test.mjs +3 -3
- package/tests/curator-clusters.test.mjs +18 -0
- package/tests/curator-pairing.test.mjs +59 -16
- package/tests/disclosure.test.mjs +34 -17
- package/tests/dynamic-rrf.test.mjs +22 -19
- package/tests/dynamic-threshold.test.mjs +52 -0
- package/tests/fact-version.test.mjs +146 -0
- package/tests/fixtures/tokenizer-cases.mjs +27 -0
- package/tests/graph-cascade.test.mjs +29 -0
- package/tests/graph.test.mjs +45 -0
- package/tests/help-page.test.mjs +1 -1
- package/tests/inject-conflict.test.mjs +112 -0
- package/tests/inject-guide.test.mjs +5 -3
- package/tests/inject.test.mjs +2 -2
- package/tests/injection-intent-budget.test.mjs +92 -0
- package/tests/lexical-bm25.test.mjs +171 -0
- package/tests/lexicon-frequency.test.mjs +17 -1
- package/tests/lexicon-inject.test.mjs +21 -0
- package/tests/lexicon-perf.test.mjs +37 -9
- package/tests/lexicon-scope.test.mjs +2 -2
- package/tests/lexicon-ui.test.mjs +1 -1
- package/tests/managed-memory.test.mjs +19 -0
- package/tests/memory-chain.test.mjs +140 -0
- package/tests/memory-fields.test.mjs +134 -0
- package/tests/memu-resident.test.mjs +33 -0
- package/tests/ops-hardening.test.mjs +209 -0
- package/tests/package-shipping.test.mjs +4 -0
- package/tests/prompt-semantics.test.mjs +51 -0
- package/tests/query-decompose.test.mjs +62 -0
- package/tests/recall-cache.test.mjs +4 -2
- package/tests/recall-intent.test.mjs +123 -0
- package/tests/slot-similarity.test.mjs +153 -0
- package/tests/speaker-provenance.test.mjs +120 -0
- package/tests/state-gc.test.mjs +34 -0
- package/tests/state.test.mjs +2 -2
- package/tests/temporal.test.mjs +124 -0
- package/tests/tokenizer-v2.test.mjs +1 -1
- package/tests/vector-gc.test.mjs +37 -0
- package/tests/webui.test.mjs +27 -0
|
@@ -0,0 +1,144 @@
|
|
|
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-commitment-'))
|
|
8
|
+
process.env.DSH_MEMU_HOME = home
|
|
9
|
+
|
|
10
|
+
const state = await import('../lib/state.js')
|
|
11
|
+
const memory = await import('../lib/memory.js')
|
|
12
|
+
const inject = await import('../lib/inject.js')
|
|
13
|
+
const commitment = await import('../lib/commitment.js')
|
|
14
|
+
|
|
15
|
+
test.after(() => {
|
|
16
|
+
try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
const NOW = new Date('2026-11-06T12:00:00+08:00')
|
|
20
|
+
|
|
21
|
+
let seq = 0
|
|
22
|
+
function session(name, sceneTime = '2026-11-06T04:00:00.000Z') {
|
|
23
|
+
seq += 1
|
|
24
|
+
const cwd = path.join(home, 'ws', `${name}-${seq}`)
|
|
25
|
+
const sessionId = `${name}-${seq}`
|
|
26
|
+
state.ensureSession(sessionId, { cwd, agentPreset: 'rp' })
|
|
27
|
+
state.setSessionBinding(sessionId, { sceneTime })
|
|
28
|
+
return {
|
|
29
|
+
sessionId,
|
|
30
|
+
exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'rp' } } } },
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
test('an explicit commitment is normalized and kept in sync with open_loop', async () => {
|
|
35
|
+
const { exec } = session('commit-write')
|
|
36
|
+
const result = await memory.privateRemember({
|
|
37
|
+
exec, title: '答应帮林查机票', content: '我答应明天帮林查去冰岛的机票。',
|
|
38
|
+
sourceKind: 'assistant_said',
|
|
39
|
+
commitment: { counterparty: 'character:lin', action: '查去冰岛的机票', due_at: '2026-11-07', status: 'open' },
|
|
40
|
+
})
|
|
41
|
+
assert.equal(result.entry.openLoop, true)
|
|
42
|
+
assert.deepEqual(result.entry.commitment, {
|
|
43
|
+
counterparty: 'character:lin', action: '查去冰岛的机票', due_at: '2026-11-07',
|
|
44
|
+
status: 'open', closed_by: null, evidence_seq: null,
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
const done = await memory.privateUpdate({
|
|
48
|
+
exec, id: result.id,
|
|
49
|
+
commitment: { ...result.entry.commitment, status: 'done', closed_by: 'turn:12', evidence_seq: 12 },
|
|
50
|
+
})
|
|
51
|
+
assert.equal(done.entry.openLoop, false)
|
|
52
|
+
assert.equal(done.entry.commitment.status, 'done')
|
|
53
|
+
assert.equal(done.entry.commitment.closed_by, 'turn:12')
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
test('open_loop=true derives a commitment; close it through either field', async () => {
|
|
57
|
+
const { exec } = session('commit-legacy')
|
|
58
|
+
const opened = await memory.privateRemember({
|
|
59
|
+
exec, title: '答应回电话', content: '答应了昨天回电话。', openLoop: true,
|
|
60
|
+
salientDate: '2026-11-05',
|
|
61
|
+
})
|
|
62
|
+
assert.equal(opened.entry.commitment.status, 'open')
|
|
63
|
+
assert.equal(opened.entry.commitment.due_at, '2026-11-05')
|
|
64
|
+
assert.equal(opened.entry.commitment.action, '答应回电话')
|
|
65
|
+
|
|
66
|
+
const closed = await memory.privateUpdate({ exec, id: opened.id, openLoop: false })
|
|
67
|
+
assert.equal(closed.entry.commitment.status, 'done', 'the legacy boolean closes the authoritative object')
|
|
68
|
+
assert.equal(closed.entry.openLoop, false)
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
test('invalid commitments are refused before anything is written', async () => {
|
|
72
|
+
const { exec } = session('commit-invalid')
|
|
73
|
+
await assert.rejects(
|
|
74
|
+
() => memory.privateRemember({ exec, title: '坏承诺', content: '测试。', commitment: { action: 'x', status: 'later' } }),
|
|
75
|
+
/commitment\.status/,
|
|
76
|
+
)
|
|
77
|
+
await assert.rejects(
|
|
78
|
+
() => memory.privateRemember({ exec, title: '坏日期', content: '测试。', commitment: { action: 'x', due_at: '2026-02-30' } }),
|
|
79
|
+
/commitment\.due_at/,
|
|
80
|
+
)
|
|
81
|
+
await assert.rejects(
|
|
82
|
+
() => memory.privateRemember({ exec, title: '没动作', content: '测试。', commitment: { due_at: '2026-11-07' } }),
|
|
83
|
+
/commitment\.action/,
|
|
84
|
+
)
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
test('dueCommitments returns overdue, today and tomorrow only, ordered by due date', async () => {
|
|
88
|
+
const { exec, sessionId } = session('commit-due')
|
|
89
|
+
const overdue = await memory.privateRemember({
|
|
90
|
+
exec, title: '逾期的事', content: '欠着一件事。',
|
|
91
|
+
commitment: { counterparty: 'user', action: '回电话', due_at: '2026-11-04', status: 'open' },
|
|
92
|
+
})
|
|
93
|
+
const today = await memory.privateRemember({
|
|
94
|
+
exec, title: '今天到期', content: '今天要交周报。',
|
|
95
|
+
commitment: { counterparty: 'user', action: '交周报', due_at: '2026-11-06', status: 'open' },
|
|
96
|
+
})
|
|
97
|
+
const tomorrow = await memory.privateRemember({
|
|
98
|
+
exec, title: '明天到期', content: '明天要带伞。',
|
|
99
|
+
commitment: { counterparty: 'user', action: '带伞', due_at: '2026-11-07', status: 'open' },
|
|
100
|
+
})
|
|
101
|
+
const distant = await memory.privateRemember({
|
|
102
|
+
exec, title: '远期约定', content: '下个月再说。',
|
|
103
|
+
commitment: { counterparty: 'user', action: '下月见面', due_at: '2026-12-20', status: 'open' },
|
|
104
|
+
})
|
|
105
|
+
const done = await memory.privateRemember({
|
|
106
|
+
exec, title: '已经兑现', content: '已经做完了。',
|
|
107
|
+
commitment: { counterparty: 'user', action: '已经做完', due_at: '2026-11-04', status: 'done' },
|
|
108
|
+
})
|
|
109
|
+
const binding = state.getSessionBinding(sessionId)
|
|
110
|
+
const due = memory.dueCommitments({ libraryId: binding.libraryId, now: NOW.getTime(), sessionId, limit: 3 })
|
|
111
|
+
assert.deepEqual(due.map((item) => item.id), [overdue.id, today.id, tomorrow.id])
|
|
112
|
+
assert.deepEqual(due.map((item) => item.daysUntil), [-2, 0, 1])
|
|
113
|
+
assert.ok(!due.some((item) => item.id === distant.id), 'a distant promise does not spend the per-turn budget')
|
|
114
|
+
assert.ok(!due.some((item) => item.id === done.id), 'a done commitment is not a reminder')
|
|
115
|
+
|
|
116
|
+
const nudge = inject.buildCommitmentNudge(binding, state.getSettings(), sessionId, { now: NOW })
|
|
117
|
+
assert.match(nudge.text, /\[commitment\]/)
|
|
118
|
+
assert.match(nudge.text, /已逾期 2 天/)
|
|
119
|
+
assert.match(nudge.text, /今天到期/)
|
|
120
|
+
assert.match(nudge.text, /明天到期/)
|
|
121
|
+
assert.equal(nudge.ids.length, 3)
|
|
122
|
+
assert.equal(nudge.text.includes(distant.id), false)
|
|
123
|
+
})
|
|
124
|
+
|
|
125
|
+
test('commitment.status outranks the legacy open_loop flag in dueOpenLoops', async () => {
|
|
126
|
+
const { exec, sessionId } = session('commit-authority')
|
|
127
|
+
const { id } = await memory.privateRemember({
|
|
128
|
+
exec, title: '旧布尔值', content: '答应过的事。', openLoop: true, salientDate: '2026-11-01',
|
|
129
|
+
})
|
|
130
|
+
const binding = state.getSessionBinding(sessionId)
|
|
131
|
+
state.updatePrivateIndex(binding.libraryId, (index) => {
|
|
132
|
+
index.entries[id].openLoop = true
|
|
133
|
+
index.entries[id].commitment = {
|
|
134
|
+
counterparty: null, action: '答应过的事', due_at: '2026-11-01',
|
|
135
|
+
status: 'done', closed_by: 'turn:9', evidence_seq: 9,
|
|
136
|
+
}
|
|
137
|
+
})
|
|
138
|
+
const due = memory.dueOpenLoops({
|
|
139
|
+
libraryId: binding.libraryId, now: NOW.getTime(), days: 1, limit: 5,
|
|
140
|
+
includeOverdueDated: true, sessionId,
|
|
141
|
+
})
|
|
142
|
+
assert.equal(due.some((item) => item.id === id), false, 'a done commitment must not resurface as an overdue loop')
|
|
143
|
+
assert.equal(commitment.isOpenThread(state.loadPrivateIndex(binding.libraryId).entries[id]), false)
|
|
144
|
+
})
|
|
@@ -573,9 +573,9 @@ test('a non-PTC header without write tools still refuses to fork', async () => {
|
|
|
573
573
|
// 超时预算按范围大小推:935 条事件那次实测「180 s 到点只写了 3 条,退避重试 131 s 完成」,
|
|
574
574
|
// 约 0.14–0.2 s/事件;政策取 0.35 s/事件(≈2 倍余量)并夹在 [180 s, 600 s]。
|
|
575
575
|
test('the consolidation wait budget scales with the transcript, not a fixed 180 s', () => {
|
|
576
|
-
assert.equal(consolidationWaitBudget(0), CONSOLIDATION_WAIT_POLICY.minMs, 'an empty range still gets the
|
|
577
|
-
assert.equal(consolidationWaitBudget(100),
|
|
578
|
-
assert.equal(consolidationWaitBudget(200),
|
|
576
|
+
assert.equal(consolidationWaitBudget(0), CONSOLIDATION_WAIT_POLICY.minMs, 'an empty range still gets the floor')
|
|
577
|
+
assert.equal(consolidationWaitBudget(100), 420_000, 'small sessions get the slow-reasoning floor')
|
|
578
|
+
assert.equal(consolidationWaitBudget(200), 420_000)
|
|
579
579
|
assert.equal(consolidationWaitBudget(935), 447_250, 'the session that timed out gets ~7.5 minutes')
|
|
580
580
|
assert.equal(consolidationWaitBudget(5_000), CONSOLIDATION_WAIT_POLICY.maxMs, 'a wedged fork still dies inside ten minutes')
|
|
581
581
|
assert.equal(consolidationWaitBudget(undefined), CONSOLIDATION_WAIT_POLICY.minMs)
|
|
@@ -4,6 +4,7 @@ import fs from 'node:fs'
|
|
|
4
4
|
import os from 'node:os'
|
|
5
5
|
import path from 'node:path'
|
|
6
6
|
import { registerHooks } from 'node:module'
|
|
7
|
+
import { performance } from 'node:perf_hooks'
|
|
7
8
|
|
|
8
9
|
// Candidate clusters (spec §4.4) + curator context packing (§4.5).
|
|
9
10
|
//
|
|
@@ -107,6 +108,23 @@ test('N=301 switches to inverted blocking: the same pair shares only 1 token and
|
|
|
107
108
|
assert.equal(clusters.length, 0, 'shared token count 1 < blockMinShared 2 keeps the pair out')
|
|
108
109
|
})
|
|
109
110
|
|
|
111
|
+
test('N=800 blocking with corpus-wide shared text stays well under 3s (dfCap prunes postings first)', () => {
|
|
112
|
+
// 复现 A-1 的病态形态:每条都带一段完全相同的中文闲聊,再各带一个独有的
|
|
113
|
+
// 后缀。旧实现把每个高频 bigram 的 posting 展开成 800²/2 个对,再对 32 万个
|
|
114
|
+
// 对跑 similarityDetail + 双向 BM25(实测 N=500 需 5.8s)。dfCap 在倒排层
|
|
115
|
+
// 跳过这些 posting,共享 token 预筛再挡掉 0 共享的对。
|
|
116
|
+
const chatter = '今晚的雾夜灯桥边茶铺霜露未散他忽然提起那些旧梗台词接得毫无痕迹我们笑作一团后来月影移过柳岸鹤鸣惊起溪桥下打盹的猫谁也没接话只是把茶续上'
|
|
117
|
+
const entries = []
|
|
118
|
+
for (let i = 0; i < 800; i += 1) {
|
|
119
|
+
entries.push(entryOf(`bulk-${i}`, 'x', `${chatter}第${i}号独有后缀`))
|
|
120
|
+
}
|
|
121
|
+
const started = performance.now()
|
|
122
|
+
const result = buildCandidateClusters(index(entries))
|
|
123
|
+
const elapsed = performance.now() - started
|
|
124
|
+
assert.equal(result.scanned, 800)
|
|
125
|
+
assert.ok(elapsed < 3000, `N=800 took ${elapsed.toFixed(0)}ms (regression bound 3000ms)`)
|
|
126
|
+
})
|
|
127
|
+
|
|
110
128
|
// —— all-pairs clique growth ——
|
|
111
129
|
|
|
112
130
|
// A-B ≈0.68, B-C ≈0.82, A-C ≈0.39: whichever edge seeds the cluster, the third
|
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
tokenize,
|
|
14
14
|
} from '../lib/text-retrieval.js'
|
|
15
15
|
import { similarityDetail, similarTexts, bigrams, dice } from '../lib/text-similarity.js'
|
|
16
|
+
import { RRF_K, RRF_W_BM25, RRF_W_DICE, RRF_W_ENTITY } from '../lib/curator-policy.js'
|
|
16
17
|
|
|
17
18
|
// —— §4.1 tokenize ——
|
|
18
19
|
|
|
@@ -82,6 +83,34 @@ test('bm25: queries wider than 64 terms keep the matching terms (junk never evic
|
|
|
82
83
|
assert.equal(bm25(query, corpus.docs.get('b'), corpus), bm25(hits, corpus.docs.get('b'), corpus))
|
|
83
84
|
assert.ok(bm25(hits, corpus.docs.get('b'), corpus) > 0)
|
|
84
85
|
})
|
|
86
|
+
test('bm25: a corpus-wide high-frequency character is dropped from the query instead of pulling the whole library in', () => {
|
|
87
|
+
const entries = []
|
|
88
|
+
for (let i = 1; i <= 40; i += 1) {
|
|
89
|
+
entries.push({
|
|
90
|
+
id: `freq-${i}`,
|
|
91
|
+
title: `记录 ${i}`,
|
|
92
|
+
content: `第 ${i} 条记录的内容里都带着这个高频字:的。${i === 1 ? '另外还有一个独角兽专属词。' : ''}`,
|
|
93
|
+
})
|
|
94
|
+
}
|
|
95
|
+
const corpus = buildCorpus(entries)
|
|
96
|
+
assert.ok(corpus.df.get('的') >= 40, 'the fixture must make 的 a corpus-wide term')
|
|
97
|
+
const doc = corpus.docs.get('freq-1')
|
|
98
|
+
// A-2:df > dfCap 的 term 整条不参与打分。旧实现给出一个很小的正数,于是
|
|
99
|
+
// 查「的」能把全库都拉进候选池;现在它不产生任何分数。
|
|
100
|
+
assert.equal(bm25(tokenize('的'), doc, corpus), 0)
|
|
101
|
+
// 真正的稀有 term 不受影响——闸门只剔高频词,不改正常词的分值口径。
|
|
102
|
+
assert.ok(bm25(tokenize('独角兽'), doc, corpus) > 0)
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
test('bm25: query term frequency is preserved (qtf multiplies that term\'s contribution)', () => {
|
|
106
|
+
const corpus = corpusFor()
|
|
107
|
+
const doc = corpus.docs.get('b')
|
|
108
|
+
const once = bm25(['缓存'], doc, corpus)
|
|
109
|
+
const twice = bm25(['缓存', '缓存'], doc, corpus)
|
|
110
|
+
assert.ok(once > 0)
|
|
111
|
+
assert.ok(Math.abs(twice - 2 * once) < 1e-12, `qtf=2 must double the contribution: ${once} -> ${twice}`)
|
|
112
|
+
})
|
|
113
|
+
|
|
85
114
|
// —— §4.2 similarityDetail / pairFeatures / pairScore ——
|
|
86
115
|
|
|
87
116
|
test('similarityDetail: length-comparable pairs report dice, pruned pairs report the containment floor', () => {
|
|
@@ -240,37 +269,51 @@ test('rankPairCandidates: deterministic — same input, same output', () => {
|
|
|
240
269
|
|
|
241
270
|
// —— §4.3 边界带(P0-1 回归修复的守卫):代理切分 → pairScore 真尺终选 ——
|
|
242
271
|
//
|
|
243
|
-
//
|
|
244
|
-
//
|
|
245
|
-
//
|
|
246
|
-
// cand-b: bm2, di2, en1
|
|
247
|
-
//
|
|
248
|
-
//
|
|
249
|
-
// pairScore:
|
|
250
|
-
//
|
|
251
|
-
// 评分集,真尺终选翻到 cand-b——准入从 RRF 代理换成 pairScore 真尺的直接证据。
|
|
272
|
+
// 手算秩结构(A-12 之后并列共享名次,fixture 不再靠 id tiebreak 制造分差):
|
|
273
|
+
// cand-a: 与 proposal 文本全同、appliesTo 不相交 → bm1, di1, en2
|
|
274
|
+
// rrf = 0.5/61 + 0.3/61 + 0.2/62(切点)
|
|
275
|
+
// cand-b: 文本只多一个词、appliesTo 相同 → bm2, di2, en1
|
|
276
|
+
// rrf = 0.5/62 + 0.3/62 + 0.2/61
|
|
277
|
+
// 差值 = 0.6×(1/61−1/62) = 1.58e-4 ≤ RRF_SLICE_BAND(2.5e-4),所以 b 落在带内。
|
|
278
|
+
// pairScore:b(entity 1.0)明显高于 a(entity 0)——pre-cut=limit=1 只评分 a,
|
|
279
|
+
// 边界带把 b 并入评分集后真尺终选翻到 b:准入从 RRF 代理换成 pairScore 真尺。
|
|
252
280
|
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
281
|
const proposal = { title: '缓存过期', content: 'Redis 缓存统一设置 30 秒过期,命中直接返回。', appliesTo: ['deploy'], track: 'memory', domain: 'general' }
|
|
256
282
|
const corpus = buildCorpus([
|
|
257
|
-
{ id: 'cand-a', title: '缓存过期', content:
|
|
258
|
-
{ id: 'cand-b', title: '缓存过期', content:
|
|
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' },
|
|
283
|
+
{ id: 'cand-a', title: '缓存过期', content: proposal.content, appliesTo: [], track: 'memory', domain: 'general' },
|
|
284
|
+
{ id: 'cand-b', title: '缓存过期', content: 'Redis 缓存统一设置 30 秒过期,命中直接返回数据。', appliesTo: ['deploy'], track: 'memory', domain: 'general' },
|
|
261
285
|
])
|
|
262
286
|
const found = rankPairCandidates({ corpus, proposal, limit: 1 })
|
|
263
287
|
// 真尺终选:数量语义不变(≤max),赢家是带内 rescue 的高 pairScore 候选
|
|
264
288
|
assert.equal(found.length, 1)
|
|
265
289
|
assert.equal(found[0].id, 'cand-b')
|
|
266
290
|
// 赢家的 rrf 严格低于切点(cand-a 的手算 rrf)——证明它来自边界带而非 pre-cut
|
|
267
|
-
const cutRrf =
|
|
291
|
+
const cutRrf = (RRF_W_BM25 + RRF_W_DICE) / (RRF_K + 1) + RRF_W_ENTITY / (RRF_K + 2)
|
|
268
292
|
assert.ok(found[0].rrf < cutRrf, `winner rrf ${found[0].rrf} must sit below the pre-cut line ${cutRrf}`)
|
|
293
|
+
assert.ok(cutRrf - found[0].rrf <= 2.5e-4, 'and the gap must stay inside the slice band')
|
|
269
294
|
// 被切掉的 cand-a 在真尺上确实更差(低 pairScore 者按 pairScore 出局)
|
|
270
295
|
const loserScore = pairScore(pairFeatures(proposal, corpus.docs.get('cand-a').entry))
|
|
271
296
|
assert.ok(found[0].score > loserScore, `band winner ${found[0].score} must beat the displaced candidate ${loserScore}`)
|
|
272
297
|
})
|
|
273
298
|
|
|
299
|
+
// —— A-12:同分文档共享名次,RRF 贡献相等 ——
|
|
300
|
+
test('rankPairCandidates: two tied documents contribute the same RRF (competition ranking)', () => {
|
|
301
|
+
const text = 'Redis 缓存统一设置 30 秒过期,命中直接返回。'
|
|
302
|
+
const proposal = { title: '缓存过期', content: text, appliesTo: [], track: 'memory', domain: 'general' }
|
|
303
|
+
const corpus = buildCorpus([
|
|
304
|
+
{ id: 'twin-b', title: '缓存过期', content: text, appliesTo: [], track: 'memory', domain: 'general' },
|
|
305
|
+
{ id: 'twin-a', title: '缓存过期', content: text, appliesTo: [], track: 'memory', domain: 'general' },
|
|
306
|
+
])
|
|
307
|
+
const found = rankPairCandidates({ corpus, proposal, limit: 20 })
|
|
308
|
+
const a = found.find((item) => item.id === 'twin-a')
|
|
309
|
+
const b = found.find((item) => item.id === 'twin-b')
|
|
310
|
+
assert.ok(a && b)
|
|
311
|
+
// 三路全部并列 rank 1:rrf = (0.5+0.3+0.2)/(K+1)。旧实现给同分者 1/2 名,
|
|
312
|
+
// 两者的 rrf 会不相等(1/61 vs 1/62)。
|
|
313
|
+
assert.equal(a.rrf, b.rrf)
|
|
314
|
+
assert.ok(Math.abs(a.rrf - (RRF_W_BM25 + RRF_W_DICE + RRF_W_ENTITY) / (RRF_K + 1)) < 1e-15)
|
|
315
|
+
})
|
|
316
|
+
|
|
274
317
|
// —— §4.8 全局冲突预筛 ——
|
|
275
318
|
|
|
276
319
|
test('globalConflictCheck: same title + different body is same_title; negation flips conflict', () => {
|
|
@@ -34,25 +34,35 @@ function seedGlobal(id, patch) {
|
|
|
34
34
|
state.saveGlobalIndex(index)
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
test('disclosure
|
|
37
|
+
test('disclosure decides when a memory may surface, not just how it is worded', async () => {
|
|
38
38
|
const cwd = path.join(home, 'proj-tone')
|
|
39
39
|
const sessionId = 'tone-suffix'
|
|
40
40
|
state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
|
|
41
41
|
const exec = execFor(sessionId, cwd)
|
|
42
42
|
const settings = { ...state.getSettings(), relevanceThreshold: 0, privateTopK: 5 }
|
|
43
43
|
|
|
44
|
-
await memory.privateRemember({ exec, content: 'The ledger file lives in docs/ledger.md.', title: 'ledger file', disclosure: 'can_tell' })
|
|
45
|
-
await memory.privateRemember({ exec, content: 'The ledger file is generated by the old importer.', title: 'ledger importer', disclosure: 'only_if_asked' })
|
|
46
|
-
await memory.privateRemember({ exec, content: 'The ledger file was named after his father.', title: 'ledger name', disclosure: 'never_say' })
|
|
44
|
+
const open = await memory.privateRemember({ exec, content: 'The ledger file lives in docs/ledger.md.', title: 'ledger file', disclosure: 'can_tell' })
|
|
45
|
+
const ask = await memory.privateRemember({ exec, content: 'The ledger file is generated by the old importer.', title: 'ledger importer', disclosure: 'only_if_asked' })
|
|
46
|
+
const never = await memory.privateRemember({ exec, content: 'The ledger file was named after his father.', title: 'ledger name', disclosure: 'never_say' })
|
|
47
47
|
|
|
48
|
-
const
|
|
49
|
-
assert.deepEqual(
|
|
50
|
-
assert.ok(
|
|
51
|
-
assert.equal(
|
|
52
|
-
assert.equal(
|
|
48
|
+
const automatic = await inject.buildRecall(state.getSessionBinding(sessionId), 'ledger file', 1, settings, exec, sessionId)
|
|
49
|
+
assert.deepEqual(automatic.errors, [])
|
|
50
|
+
assert.ok(automatic.text.includes('ledger file'), 'a can_tell memory arrives as before')
|
|
51
|
+
assert.equal(automatic.text.includes(ask.id), false, 'only_if_asked waits for a direct question')
|
|
52
|
+
assert.equal(automatic.text.includes(never.id), false)
|
|
53
53
|
// The default case must stay silent: adding a suffix to every line would be noise.
|
|
54
|
-
const canTellLine =
|
|
54
|
+
const canTellLine = automatic.text.split('\n').find((line) => line.includes('ledger file ·') || line.includes('ledger file'))
|
|
55
55
|
assert.ok(canTellLine && !canTellLine.includes('对方不问') && !canTellLine.includes('别直接说出口'))
|
|
56
|
+
|
|
57
|
+
const explicit = await memory.privateRecall({ exec, query: 'ledger file', topK: 10, relevanceThreshold: 0 })
|
|
58
|
+
const explicitIds = explicit.files.map((file) => file.name)
|
|
59
|
+
assert.ok(explicitIds.includes(ask.id) && explicitIds.includes(never.id), 'an explicit recall can still read both')
|
|
60
|
+
|
|
61
|
+
const boundary = await inject.buildRecall(state.getSessionBinding(sessionId), 'ledger 的秘密是什么', 2, settings, exec, sessionId)
|
|
62
|
+
assert.deepEqual(boundary.errors, [])
|
|
63
|
+
assert.ok(boundary.text.includes(ask.id), 'a direct boundary question releases only_if_asked')
|
|
64
|
+
assert.equal(boundary.text.split('对方不问就别主动提').length - 1, 1, 'only_if_asked carries its suffix when released')
|
|
65
|
+
assert.equal(boundary.text.includes(never.id), false, 'never_say never auto-surfaces, even when asked')
|
|
56
66
|
})
|
|
57
67
|
|
|
58
68
|
test('a secret stays out of the anchor but is still reachable through recall', async () => {
|
|
@@ -98,25 +108,32 @@ test('a secret stays out of the anchor but is still reachable through recall', a
|
|
|
98
108
|
assert.ok(recalled.files.some((file) => file.name === sharedId))
|
|
99
109
|
})
|
|
100
110
|
|
|
101
|
-
test('
|
|
111
|
+
test('an unsayable short-term draft stays out of the anchor pointer', async () => {
|
|
102
112
|
const cwd = path.join(home, 'proj-pointer')
|
|
103
113
|
const sessionId = 'tone-pointer'
|
|
104
114
|
const binding = state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
|
|
105
115
|
const exec = execFor(sessionId, cwd)
|
|
106
116
|
|
|
107
|
-
const
|
|
117
|
+
const never = await memory.privateRemember({
|
|
108
118
|
exec,
|
|
109
|
-
content: 'BODY he was still deciding about the surgery.',
|
|
119
|
+
content: 'BODY-NEVER he was still deciding about the surgery.',
|
|
110
120
|
title: 'the surgery question',
|
|
111
121
|
layer: 'short_term',
|
|
112
122
|
disclosure: 'never_say',
|
|
113
123
|
})
|
|
124
|
+
const open = await memory.privateRemember({
|
|
125
|
+
exec,
|
|
126
|
+
content: 'BODY-OPEN the follow-up appointment is on Thursday.',
|
|
127
|
+
title: 'the follow-up',
|
|
128
|
+
layer: 'short_term',
|
|
129
|
+
})
|
|
114
130
|
const anchor = inject.buildAnchor(binding, { ...state.getSettings(), anchorTokens: 700 })
|
|
115
|
-
|
|
116
|
-
|
|
131
|
+
assert.equal(anchor.text.includes(never.id), false, 'never_say does not enter the automatic pointer list')
|
|
132
|
+
const line = anchor.text.split('\n').find((row) => row.includes(open.id))
|
|
133
|
+
assert.ok(line, 'an ordinary draft still gets a pointer')
|
|
117
134
|
assert.ok(line.includes('小时后过期'))
|
|
118
|
-
assert.
|
|
119
|
-
assert.equal(anchor.text.includes('BODY
|
|
135
|
+
assert.equal(anchor.text.includes('BODY-NEVER'), false)
|
|
136
|
+
assert.equal(anchor.text.includes('BODY-OPEN'), false)
|
|
120
137
|
})
|
|
121
138
|
|
|
122
139
|
test('owner prefixes only about_user, and the prefix is cheap', async () => {
|
|
@@ -119,34 +119,37 @@ function recentCorpus() {
|
|
|
119
119
|
])
|
|
120
120
|
}
|
|
121
121
|
|
|
122
|
-
test('recency
|
|
122
|
+
test('recency 查询下同分文档共享三路名次,recency 第四路成为唯一区分信号', () => {
|
|
123
123
|
const corpus = recentCorpus()
|
|
124
124
|
const proposal = { track: 'memory', domain: 'general', title: '缓存过期', content: '昨天 缓存过期提醒每日检查' }
|
|
125
125
|
const found = rankPairCandidates({ corpus, proposal, limit: 20 })
|
|
126
126
|
assert.equal(found.length, 2)
|
|
127
|
-
//
|
|
128
|
-
//
|
|
129
|
-
|
|
130
|
-
const
|
|
131
|
-
|
|
132
|
-
const
|
|
133
|
-
const
|
|
134
|
-
|
|
135
|
-
assert.ok(
|
|
136
|
-
assert.ok(
|
|
137
|
-
//
|
|
138
|
-
assert.ok(
|
|
139
|
-
|
|
140
|
-
assert.equal(found[
|
|
141
|
-
assert.equal(found[1].id, 'b-new')
|
|
127
|
+
// A-12:文本全同 → bm25/dice/entity 三路并列,竞赛排名下都取 rank 1(旧实现
|
|
128
|
+
// 用 idAsc 把它们拆成 rank 1/2,凭空制造分差)。recency 是唯一区分通道:
|
|
129
|
+
// b-new updatedAt 更新 → rank 1,a-old rank 2。
|
|
130
|
+
const w = computeRRFWeights(proposal, corpus)
|
|
131
|
+
assert.ok(w.recency != null, 'fixture must take the recency route')
|
|
132
|
+
const textRoutes = w.bm25 / (RRF_K + 1) + w.dice / (RRF_K + 1) + w.entity / (RRF_K + 1)
|
|
133
|
+
const rrfNew = textRoutes + w.recency / (RRF_K + 1)
|
|
134
|
+
const rrfOld = textRoutes + w.recency / (RRF_K + 2)
|
|
135
|
+
assert.ok(Math.abs(found.find((c) => c.id === 'b-new').rrf - rrfNew) < 1e-15)
|
|
136
|
+
assert.ok(Math.abs(found.find((c) => c.id === 'a-old').rrf - rrfOld) < 1e-15)
|
|
137
|
+
// 文本三路不提供任何区分,recency 足以把更新的文档推到前面。
|
|
138
|
+
assert.ok(rrfNew > rrfOld)
|
|
139
|
+
assert.equal(found[0].id, 'b-new')
|
|
140
|
+
assert.equal(found[1].id, 'a-old')
|
|
142
141
|
})
|
|
143
142
|
|
|
144
|
-
test('非近期查询下同一 corpus 不受 recency
|
|
143
|
+
test('非近期查询下同一 corpus 不受 recency 影响:同分同 rrf,输出按 id 稳定', () => {
|
|
145
144
|
const corpus = recentCorpus()
|
|
146
145
|
const proposal = { track: 'memory', domain: 'general', title: '缓存过期', content: '缓存过期提醒每日检查' }
|
|
147
146
|
const found = rankPairCandidates({ corpus, proposal, limit: 20 })
|
|
148
|
-
|
|
149
|
-
|
|
147
|
+
// 文本全同 → 三路并列 rank 1,A-12 后两条 rrf 相等(旧实现是 1/61 与 1/62)。
|
|
148
|
+
const tied = (RRF_W_BM25 + RRF_W_DICE + RRF_W_ENTITY) / (RRF_K + 1)
|
|
149
|
+
assert.equal(found[0].rrf, tied)
|
|
150
|
+
assert.equal(found[1].rrf, tied)
|
|
151
|
+
assert.equal(found[0].id, 'a-old', 'equal rrf falls back to idAsc')
|
|
152
|
+
assert.equal(found[1].id, 'b-new')
|
|
150
153
|
})
|
|
151
154
|
|
|
152
155
|
test('结果确定性:同输入两次 rankPairCandidates / computeRRFWeights 完全一致', () => {
|
|
@@ -0,0 +1,52 @@
|
|
|
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-percentile-'))
|
|
8
|
+
process.env.DSH_MEMU_HOME = home
|
|
9
|
+
|
|
10
|
+
const state = await import('../lib/state.js')
|
|
11
|
+
const memory = await import('../lib/memory.js')
|
|
12
|
+
|
|
13
|
+
test.after(() => {
|
|
14
|
+
delete process.env.DSH_MEMU_RECALL_PERCENTILE
|
|
15
|
+
try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
function fixture() {
|
|
19
|
+
const sessionId = 'percentile'
|
|
20
|
+
const cwd = path.join(home, 'ws-percentile')
|
|
21
|
+
state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
|
|
22
|
+
const binding = state.getSessionBinding(sessionId)
|
|
23
|
+
const index = state.loadPrivateIndex(binding.libraryId)
|
|
24
|
+
const now = new Date().toISOString()
|
|
25
|
+
const topics = ['预算', '排期', '招聘', '客户投诉', '机房迁移', '季度目标', '培训', '安全审计', '值班表', '产品路线']
|
|
26
|
+
for (const [i, topic] of topics.entries()) {
|
|
27
|
+
index.entries[`mem-p${i}`] = {
|
|
28
|
+
title: `会议记录 ${i}`,
|
|
29
|
+
content: `会议主要讨论${topic},结论是下周继续跟进,负责人单独确认。`,
|
|
30
|
+
status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
state.savePrivateIndex(binding.libraryId, index)
|
|
34
|
+
return { exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'coding' } } } } }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
test('percentile cut is off by default and never pads a minimum result count', async () => {
|
|
38
|
+
const { exec } = fixture()
|
|
39
|
+
delete process.env.DSH_MEMU_RECALL_PERCENTILE
|
|
40
|
+
const normal = await memory.privateRecall({ exec, query: '会议', topK: 10, relevanceThreshold: 0 })
|
|
41
|
+
assert.equal(normal.files.length, 10, 'default keeps the requested topK')
|
|
42
|
+
|
|
43
|
+
process.env.DSH_MEMU_RECALL_PERCENTILE = '1'
|
|
44
|
+
const narrowed = await memory.privateRecall({ exec, query: '会议', topK: 10, relevanceThreshold: 0 })
|
|
45
|
+
assert.ok(narrowed.files.length > 0 && narrowed.files.length < normal.files.length, 'percentile must narrow, not pad')
|
|
46
|
+
assert.equal(narrowed.files.length, Math.ceil(normal.files.length * 0.25))
|
|
47
|
+
assert.equal(narrowed.files[0].name, normal.files[0].name, 'the best hit is preserved')
|
|
48
|
+
delete process.env.DSH_MEMU_RECALL_PERCENTILE
|
|
49
|
+
|
|
50
|
+
const none = await memory.privateRecall({ exec, query: 'qqqqzzzz', topK: 10, relevanceThreshold: 0 })
|
|
51
|
+
assert.equal(none.files.length, 0, 'a no-match stays empty')
|
|
52
|
+
})
|