dsh-memu-memory 1.2.1 → 1.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +3 -1
- package/README.md +23 -8
- package/README.zh.md +16 -6
- package/docs/client-conventions.md +1 -0
- package/docs/contributing.md +18 -4
- package/docs/emotion-model-spec.md +2 -2
- package/docs/env-and-commands.md +20 -0
- package/docs/host-api.md +22 -1
- package/docs/memory-semantics.md +30 -2
- package/docs/troubleshooting.md +76 -5
- package/lib/activity-log.js +1 -1
- package/lib/backup.js +24 -2
- package/lib/binding-diagnostics.js +2 -2
- package/lib/client.js +1511 -153
- package/lib/consolidation-worker.js +30 -8
- package/lib/curator-evidence.js +131 -0
- package/lib/curator-policy.js +81 -0
- package/lib/curator.js +1252 -91
- package/lib/cycle.js +12 -1
- package/lib/embedding-download.js +39 -4
- package/lib/engine.js +6 -3
- package/lib/freshness.js +97 -0
- package/lib/global-graph.js +282 -0
- package/lib/graph.js +295 -11
- package/lib/inbound.js +19 -0
- package/lib/inject.js +396 -25
- package/lib/lexicon.js +1115 -0
- package/lib/local-vector-service.js +8 -6
- package/lib/managed-runtime.js +33 -2
- package/lib/memory.js +365 -34
- package/lib/memu.js +2 -2
- package/lib/migrate.js +83 -2
- package/lib/private-links.js +587 -0
- package/lib/private.js +32 -3
- package/lib/prompts/global-curator.md +76 -19
- package/lib/prompts/private-consolidation.coding.md +4 -1
- package/lib/prompts/private-consolidation.md +3 -1
- package/lib/prompts/private-consolidation.mixed.md +3 -1
- package/lib/prompts/private-consolidation.rp.md +3 -1
- package/lib/prompts.js +1 -1
- package/lib/rpc.js +589 -10
- package/lib/salient-wake.js +402 -0
- package/lib/state.js +95 -1
- package/lib/text-retrieval.js +661 -0
- package/lib/text-similarity.js +36 -18
- package/lib/tools.js +168 -10
- package/lib/webui/standalone.css +17 -0
- package/lib/webui/standalone.js +2 -0
- package/package.json +1 -1
- package/scripts/acceptance-local.mjs +8 -5
- package/scripts/curator-pair-calibrate.mjs +259 -0
- package/scripts/drive-session.mjs +853 -0
- package/scripts/lexicon-calibrate.mjs +230 -0
- package/scripts/lexicon-dedupe.mjs +318 -0
- package/scripts/mock-llm.mjs +903 -0
- package/tests/absorb-review.test.mjs +353 -0
- package/tests/appendix-b2.test.mjs +2 -2
- package/tests/client-export.test.mjs +520 -0
- package/tests/client-render.test.mjs +32 -4
- package/tests/consolidation-fork.test.mjs +14 -12
- package/tests/consolidation-snapshot.test.mjs +39 -0
- package/tests/curator-absorb.test.mjs +443 -0
- package/tests/curator-calibrate.test.mjs +173 -0
- package/tests/curator-clusters.test.mjs +281 -0
- package/tests/curator-commit.test.mjs +52 -5
- package/tests/curator-evidence.test.mjs +102 -0
- package/tests/curator-link.test.mjs +316 -0
- package/tests/curator-pairing.test.mjs +252 -0
- package/tests/curator-probe.test.mjs +15 -6
- package/tests/curator-review-mode.test.mjs +314 -0
- package/tests/disclosure.test.mjs +2 -1
- package/tests/entity-merge.test.mjs +261 -0
- package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -0
- package/tests/fixtures/lexicon-stub-hooks.mjs +15 -0
- package/tests/fixtures/lexicon-stub.mjs +284 -0
- package/tests/fixtures/mock-llm/reply.txt +1 -0
- package/tests/freshness.test.mjs +140 -0
- package/tests/graph-cascade.test.mjs +35 -2
- package/tests/graph.test.mjs +96 -0
- package/tests/help-page.test.mjs +415 -0
- package/tests/inbound.test.mjs +6 -3
- package/tests/inject-guide.test.mjs +28 -0
- package/tests/inject.test.mjs +157 -5
- package/tests/injection-chain.test.mjs +176 -0
- package/tests/lexicon-calibrate.test.mjs +48 -0
- package/tests/lexicon-dedupe.test.mjs +171 -0
- package/tests/lexicon-frequency.test.mjs +179 -0
- package/tests/lexicon-inject.test.mjs +410 -0
- package/tests/lexicon-perf.test.mjs +436 -0
- package/tests/lexicon-ui.test.mjs +547 -0
- package/tests/lexicon.test.mjs +922 -0
- package/tests/managed-runtime.test.mjs +32 -0
- package/tests/mock-llm.test.mjs +225 -0
- package/tests/open-loop-date.test.mjs +406 -0
- package/tests/private-links.test.mjs +445 -0
- package/tests/prompts.test.mjs +35 -0
- package/tests/recall-dedup.test.mjs +33 -4
- package/tests/salient-wake.test.mjs +362 -0
- package/tests/settings-plumbing.test.mjs +76 -0
- package/tests/sidebar.test.mjs +5 -1
- package/tests/stubs/dsh-schedule.js +105 -0
- package/tests/tool-schema.test.mjs +1 -1
- package/tests/tools.test.mjs +112 -3
- package/tests/webui-auth.test.mjs +352 -2
- package/tests/webui.test.mjs +188 -0
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// 词典频率先验(施工稿 §6.3 包 C):Wilson 下界、effective 因子进入 stableRank、
|
|
2
|
+
// hitCounts 写入 clamp、以及生命周期(active/archived)对频率证据的影响。所有断言
|
|
3
|
+
// 只依赖落盘数据,不依赖当前时间——排序的确定性在这里与 lexicon-inject 各钉一遍。
|
|
4
|
+
// 面板/卡片流(§2.4)的 UI 断言在 tests/lexicon-ui.test.mjs(G2b 重写),本文件只管
|
|
5
|
+
// 数据面:当前版本没有待审队列,所以这里也不再钉 pending 文案。
|
|
6
|
+
import test from 'node:test'
|
|
7
|
+
import assert from 'node:assert/strict'
|
|
8
|
+
import fs from 'node:fs'
|
|
9
|
+
import os from 'node:os'
|
|
10
|
+
import path from 'node:path'
|
|
11
|
+
|
|
12
|
+
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-lexicon-frequency-'))
|
|
13
|
+
process.env.DSH_MEMU_HOME = home
|
|
14
|
+
|
|
15
|
+
const paths = await import('../lib/paths.js')
|
|
16
|
+
const state = await import('../lib/state.js')
|
|
17
|
+
const lexicon = await import('../lib/lexicon.js')
|
|
18
|
+
|
|
19
|
+
test.after(() => {
|
|
20
|
+
try { state.flushState() } catch {}
|
|
21
|
+
try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
let serial = 0
|
|
25
|
+
function setupLibrary(name, { terms = [] } = {}) {
|
|
26
|
+
serial += 1
|
|
27
|
+
const binding = state.ensureSession(`freq-${name}-${serial}`, { cwd: path.join(home, `project-${name}-${serial}`), agentPreset: 'rp' })
|
|
28
|
+
for (const args of terms) lexicon.upsertLexiconTerm({ libraryId: binding.libraryId, ...args })
|
|
29
|
+
return binding
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function lexFile(libraryId) {
|
|
33
|
+
return path.join(home, 'lexicon', `${libraryId}.json`)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 直改磁盘上的词条字段(hitCounts/strength/updatedAt),靠 mtime 失效重建索引。 */
|
|
37
|
+
function patchTerm(libraryId, term, patch) {
|
|
38
|
+
const lex = lexicon.loadLexicon(libraryId)
|
|
39
|
+
const normalized = lexicon.normalizeLexeme(term)
|
|
40
|
+
const entry = Object.values(lex.terms).find(item => item.normalizedTerm === normalized)
|
|
41
|
+
assert.ok(entry, `term ${term} must exist`)
|
|
42
|
+
Object.assign(entry, patch)
|
|
43
|
+
paths.writeJson(lexFile(libraryId), lex)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function termIdOf(libraryId, term) {
|
|
47
|
+
const normalized = lexicon.normalizeLexeme(term)
|
|
48
|
+
const lex = lexicon.loadLexicon(libraryId)
|
|
49
|
+
return Object.entries(lex.terms).find(([, entry]) => entry.normalizedTerm === normalized)?.[0] || null
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// ---- 1-2. Wilson 下界公式 ----
|
|
53
|
+
|
|
54
|
+
test('usageLowerBound: n=0 is 0, success is clamped to n, output stays in [0,1]', () => {
|
|
55
|
+
assert.equal(lexicon.usageLowerBound({ candidate: 0, injection: 0, query: 0 }), 0, 'never-candidated terms carry no frequency evidence')
|
|
56
|
+
assert.equal(lexicon.usageLowerBound(undefined), 0)
|
|
57
|
+
assert.equal(lexicon.usageLowerBound(null), 0)
|
|
58
|
+
assert.equal(lexicon.usageLowerBound({}), 0)
|
|
59
|
+
assert.equal(lexicon.usageLowerBound({ candidate: -5, injection: 3 }), 0, 'negative denominator is treated as zero')
|
|
60
|
+
// success 被 min(n, ...) 钳住:脏数据 injection > candidate 也不会把 p 抬过 1。
|
|
61
|
+
const bounded = lexicon.usageLowerBound({ candidate: 10, injection: 50, query: 0 })
|
|
62
|
+
const maxed = lexicon.usageLowerBound({ candidate: 10, injection: 10, query: 0 })
|
|
63
|
+
assert.equal(bounded, maxed, 'success above n is clamped to n')
|
|
64
|
+
for (const value of [bounded, maxed]) assert.ok(value >= 0 && value <= 1, 'the bound stays in [0,1]')
|
|
65
|
+
// 1/1 的 Wilson 下界 ≈ 0.207:一次偶发命中拿不到多少先验。
|
|
66
|
+
const single = lexicon.usageLowerBound({ candidate: 1, injection: 1, query: 0 })
|
|
67
|
+
assert.ok(Math.abs(single - 0.207) < 0.01, `1/1 lower bound should be ~0.207, got ${single}`)
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
test('usageLowerBound: 10/9 ranks above 10/1 — a high miss rate is punished', () => {
|
|
71
|
+
const good = lexicon.usageLowerBound({ candidate: 10, injection: 9, query: 0 })
|
|
72
|
+
const bad = lexicon.usageLowerBound({ candidate: 10, injection: 1, query: 0 })
|
|
73
|
+
assert.ok(good > bad, `9/10 (${good}) must beat 1/10 (${bad})`)
|
|
74
|
+
// 大样本的稳定命中率高于小样本的同比率(Wilson 下界的意义所在)。
|
|
75
|
+
const big = lexicon.usageLowerBound({ candidate: 120, injection: 100, query: 0 })
|
|
76
|
+
const small = lexicon.usageLowerBound({ candidate: 10, injection: 8, query: 0 })
|
|
77
|
+
assert.ok(big > small, '100/120 must exceed 8/10 despite the same ratio')
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
// ---- 3. 高 strength 零计数仍压过低 strength 高计数 ----
|
|
81
|
+
|
|
82
|
+
test('effective factor: high strength with zero hits still outranks low strength with heavy usage', () => {
|
|
83
|
+
const binding = setupLibrary('strength-first', { terms: [
|
|
84
|
+
{ term: '强词先', kind: 'term', meaning: '强权重零计数' },
|
|
85
|
+
{ term: '弱词后', kind: 'term', meaning: '弱权重高计数' },
|
|
86
|
+
] })
|
|
87
|
+
const lib = binding.libraryId
|
|
88
|
+
patchTerm(lib, '强词先', { strength: 0.9, confidence: 0.8, updatedAt: '2026-01-01T00:00:00.000Z' })
|
|
89
|
+
patchTerm(lib, '弱词后', { strength: 0.2, confidence: 0.8, updatedAt: '2026-01-01T00:00:00.000Z',
|
|
90
|
+
hitCounts: { candidate: 1000, injection: 1000, query: 0 } })
|
|
91
|
+
const hits = lexicon.matchLexiconHits(lib, '强词先和弱词后都出现在这句话里', binding.memoryContext)
|
|
92
|
+
assert.equal(hits.length, 2)
|
|
93
|
+
assert.equal(hits[0].term, '强词先', 'a bounded [0.85,1.00] prior must never overturn strength')
|
|
94
|
+
assert.equal(hits[0].hitCounts.candidate, 0, 'the winner indeed has zero usage')
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
// ---- 4. 同 strength/confidence,注入率高的排前面 ----
|
|
98
|
+
|
|
99
|
+
test('effective factor: same strength and confidence, the heavily injected term ranks first', () => {
|
|
100
|
+
const binding = setupLibrary('usage-first', { terms: [
|
|
101
|
+
{ term: '高频入', kind: 'term', meaning: '十次候选十次注入' },
|
|
102
|
+
{ term: '低频入', kind: 'term', meaning: '十次候选一次注入' },
|
|
103
|
+
] })
|
|
104
|
+
const lib = binding.libraryId
|
|
105
|
+
patchTerm(lib, '高频入', { strength: 0.5, confidence: 0.5, updatedAt: '2026-01-01T00:00:00.000Z',
|
|
106
|
+
hitCounts: { candidate: 10, injection: 10, query: 0 } })
|
|
107
|
+
patchTerm(lib, '低频入', { strength: 0.5, confidence: 0.5, updatedAt: '2026-01-01T00:00:00.000Z',
|
|
108
|
+
hitCounts: { candidate: 10, injection: 1, query: 0 } })
|
|
109
|
+
const hits = lexicon.matchLexiconHits(lib, '高频入和低频入都出现在这句话里', binding.memoryContext)
|
|
110
|
+
assert.equal(hits.length, 2)
|
|
111
|
+
assert.equal(hits[0].term, '高频入', 'Wilson lower bound lifts the term that really gets injected')
|
|
112
|
+
assert.equal(hits[1].term, '低频入')
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
// ---- 5. 排序稳定:纯函数,与当前时间/调用次数无关 ----
|
|
116
|
+
|
|
117
|
+
test('ranking is a pure function of the stored data, stable across repeated calls', () => {
|
|
118
|
+
const binding = setupLibrary('stable', { terms: [
|
|
119
|
+
{ term: '稳定甲', kind: 'term', meaning: '一' },
|
|
120
|
+
{ term: '稳定乙', kind: 'term', meaning: '二' },
|
|
121
|
+
{ term: '稳定丙', kind: 'term', meaning: '三' },
|
|
122
|
+
] })
|
|
123
|
+
const lib = binding.libraryId
|
|
124
|
+
patchTerm(lib, '稳定甲', { strength: 0.6, confidence: 0.6, updatedAt: '2026-01-02T00:00:00.000Z',
|
|
125
|
+
hitCounts: { candidate: 4, injection: 1, query: 0 } })
|
|
126
|
+
patchTerm(lib, '稳定乙', { strength: 0.6, confidence: 0.6, updatedAt: '2026-01-01T00:00:00.000Z',
|
|
127
|
+
hitCounts: { candidate: 4, injection: 4, query: 0 } })
|
|
128
|
+
patchTerm(lib, '稳定丙', { strength: 0.6, confidence: 0.6, updatedAt: '2026-01-01T00:00:00.000Z',
|
|
129
|
+
hitCounts: { candidate: 4, injection: 4, query: 0 } })
|
|
130
|
+
const text = '稳定甲稳定乙稳定丙同时出现'
|
|
131
|
+
const first = lexicon.matchLexiconHits(lib, text, binding.memoryContext).map(hit => hit.term)
|
|
132
|
+
assert.equal(first.length, 3)
|
|
133
|
+
const second = lexicon.matchLexiconHits(lib, text, binding.memoryContext).map(hit => hit.term)
|
|
134
|
+
assert.deepEqual(second, first, 'the order never depends on the clock or iteration order')
|
|
135
|
+
// 稳定乙/丙同分同 updatedAt:并列对按 termId 字典序,稳定甲(低注入率)垫底。
|
|
136
|
+
const idA = termIdOf(lib, '稳定乙')
|
|
137
|
+
const idB = termIdOf(lib, '稳定丙')
|
|
138
|
+
const tiePair = idA.localeCompare(idB) < 0 ? ['稳定乙', '稳定丙'] : ['稳定丙', '稳定乙']
|
|
139
|
+
assert.deepEqual(first.slice(0, 2), tiePair, 'the tied pair falls back to the lexicographic termId')
|
|
140
|
+
assert.equal(first[2], '稳定甲', 'the weak injection rate stays behind on the same strength')
|
|
141
|
+
})
|
|
142
|
+
|
|
143
|
+
// ---- 6. hitCounts 写入 clamp 到 1,000,000 ----
|
|
144
|
+
|
|
145
|
+
test('lexiconRecordHits clamps hitCounts at HIT_COUNT_CAP and keeps the prior bounded', () => {
|
|
146
|
+
const binding = setupLibrary('clamp', { terms: [{ term: '爆表词', kind: 'term', meaning: '计数封顶' }] })
|
|
147
|
+
const lib = binding.libraryId
|
|
148
|
+
const id = termIdOf(lib, '爆表词')
|
|
149
|
+
assert.ok(id)
|
|
150
|
+
patchTerm(lib, '爆表词', { hitCounts: { candidate: 5_000_000, injection: 2_000_000, query: 3_000_000 } })
|
|
151
|
+
const { counts } = lexicon.lexiconRecordHits(lib, [id], 'candidate')
|
|
152
|
+
assert.equal(counts[id].candidate, lexicon.HIT_COUNT_CAP, 'candidate is clamped to 1,000,000 even after increment')
|
|
153
|
+
assert.equal(counts[id].injection, lexicon.HIT_COUNT_CAP, 'pre-existing out-of-range values are pulled back in')
|
|
154
|
+
assert.equal(counts[id].query, lexicon.HIT_COUNT_CAP)
|
|
155
|
+
const lb = lexicon.usageLowerBound(counts[id])
|
|
156
|
+
assert.ok(lb >= 0 && lb <= 1, `the factor input stays finite and bounded, got ${lb}`)
|
|
157
|
+
assert.ok(lexicon.usageLowerBound({ candidate: lexicon.HIT_COUNT_CAP, injection: lexicon.HIT_COUNT_CAP }) > 0.9999, 'a perfect huge sample bounds just under 1 (Wilson never quite reaches it)')
|
|
158
|
+
// 落盘值同样被封顶:下一次读取不会看到越界计数。
|
|
159
|
+
const stored = Object.values(lexicon.loadLexicon(lib).terms).find(entry => entry.termId === id || entry.term === '爆表词')
|
|
160
|
+
assert.equal(stored.hitCounts.candidate, lexicon.HIT_COUNT_CAP)
|
|
161
|
+
})
|
|
162
|
+
|
|
163
|
+
// ---- 7. 生命周期 × 频率先验(§2.1):归档词条不再参与匹配/注入 ----
|
|
164
|
+
|
|
165
|
+
test('archived terms stop accruing frequency evidence and keep their stored counts', () => {
|
|
166
|
+
const binding = setupLibrary('archived', { terms: [{ term: '归档频率词', kind: 'term', meaning: '归档后不再候选' }] })
|
|
167
|
+
const lib = binding.libraryId
|
|
168
|
+
const id = termIdOf(lib, '归档频率词')
|
|
169
|
+
lexicon.lexiconRecordHit(lib, id, 'candidate')
|
|
170
|
+
lexicon.lexiconRecordHit(lib, id, 'injection')
|
|
171
|
+
lexicon.archiveLexiconTerm({ libraryId: lib, termId: id })
|
|
172
|
+
// 归档后不再进匹配:没有 candidate/injection 可累积。
|
|
173
|
+
assert.deepEqual(lexicon.matchLexiconHits(lib, '归档频率词出现在这句话里', binding.memoryContext), [])
|
|
174
|
+
const stored = lexicon.loadLexicon(lib).terms[id]
|
|
175
|
+
assert.deepEqual(stored.hitCounts, { candidate: 1, injection: 1, query: 0 }, 'the audit counts survive archiving unchanged')
|
|
176
|
+
// 恢复后重新参与匹配(计数是历史,不是可见性开关)。
|
|
177
|
+
lexicon.restoreLexiconTerm({ libraryId: lib, termId: id })
|
|
178
|
+
assert.equal(lexicon.matchLexiconHits(lib, '归档频率词出现在这句话里', binding.memoryContext).length, 1)
|
|
179
|
+
})
|
|
@@ -0,0 +1,410 @@
|
|
|
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-lexicon-inject-'))
|
|
8
|
+
process.env.DSH_MEMU_HOME = home
|
|
9
|
+
|
|
10
|
+
const paths = await import('../lib/paths.js')
|
|
11
|
+
const state = await import('../lib/state.js')
|
|
12
|
+
const lexicon = await import('../lib/lexicon.js')
|
|
13
|
+
const inject = await import('../lib/inject.js')
|
|
14
|
+
const inbound = await import('../lib/inbound.js')
|
|
15
|
+
const { estTokens } = await import('../lib/budget.js')
|
|
16
|
+
|
|
17
|
+
test.after(() => {
|
|
18
|
+
try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
let serial = 0
|
|
22
|
+
function setupSession(name, { terms = [], memories = [] } = {}) {
|
|
23
|
+
serial += 1
|
|
24
|
+
const sessionId = `inject-${name}-${serial}`
|
|
25
|
+
const cwd = path.join(home, `project-${name}-${serial}`)
|
|
26
|
+
const binding = state.ensureSession(sessionId, { cwd, agentPreset: 'rp' })
|
|
27
|
+
if (memories.length) {
|
|
28
|
+
const index = state.loadPrivateIndex(binding.libraryId)
|
|
29
|
+
for (const { id, entry } of memories) index.entries[id] = entry
|
|
30
|
+
state.savePrivateIndex(binding.libraryId, index)
|
|
31
|
+
}
|
|
32
|
+
for (const args of terms) lexicon.upsertLexiconTerm({ libraryId: binding.libraryId, ...args })
|
|
33
|
+
// state.js 的 binding 不带 sessionId;测试里补上,方便把 binding/session 一起传。
|
|
34
|
+
return { ...binding, sessionId }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function agentFor(binding) {
|
|
38
|
+
return { session: { header: { id: binding.sessionId, cwd: path.join(home, 'cwd-' + binding.sessionId), agentPreset: 'rp', origin: 'user' } } }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function userMessage(id, text) {
|
|
42
|
+
return { id, role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text }] }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function pluginTexts(out) {
|
|
46
|
+
return out.messages
|
|
47
|
+
.filter(message => message?.source?.kind === 'plugin:dsh-memu-memory')
|
|
48
|
+
.map(message => Array.isArray(message.content) ? message.content.filter(b => b?.type === 'text').map(b => b.text).join('\n') : String(message.content || ''))
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function lexFile(libraryId) {
|
|
52
|
+
return path.join(home, 'lexicon', `${libraryId}.json`)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function setStrength(libraryId, term, strength) {
|
|
56
|
+
const lex = lexicon.loadLexicon(libraryId)
|
|
57
|
+
for (const entry of Object.values(lex.terms)) {
|
|
58
|
+
if (entry.normalizedTerm === lexicon.normalizeLexeme(term)) entry.strength = strength
|
|
59
|
+
}
|
|
60
|
+
paths.writeJson(lexFile(libraryId), lex)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ---- 匹配流水线(§3.1) ----
|
|
64
|
+
|
|
65
|
+
test('exact layer: term containment and whole-message equality both hit as exact-term', () => {
|
|
66
|
+
const binding = setupSession('exact', { terms: [{ term: '糖刀', kind: 'meme', meaning: '表面发糖、实际虐心' }] })
|
|
67
|
+
const hits = lexicon.matchLexiconHits(binding.libraryId, '这段太糖刀了', binding.memoryContext)
|
|
68
|
+
assert.equal(hits.length, 1)
|
|
69
|
+
assert.equal(hits[0].kindOfHit, 'exact-term')
|
|
70
|
+
assert.equal(hits[0].term, '糖刀')
|
|
71
|
+
assert.equal(hits[0].meaning, '表面发糖、实际虐心')
|
|
72
|
+
const whole = lexicon.matchLexiconHits(binding.libraryId, '糖刀', binding.memoryContext)
|
|
73
|
+
assert.equal(whole[0].kindOfHit, 'exact-term')
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
test('exact layer: aliases hit as exact-alias and fold onto the same term', () => {
|
|
77
|
+
const binding = setupSession('alias', { terms: [{ term: '糖刀', kind: 'meme', meaning: '表面发糖', aliases: ['糖里藏刀'] }] })
|
|
78
|
+
const hits = lexicon.matchLexiconHits(binding.libraryId, '这不就是糖里藏刀吗', binding.memoryContext)
|
|
79
|
+
assert.equal(hits.length, 1)
|
|
80
|
+
assert.equal(hits[0].kindOfHit, 'exact-alias')
|
|
81
|
+
assert.equal(hits[0].term, '糖刀')
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
test('dice fallback: a fuzzy variant inside the prefix bucket hits with score >= threshold; unrelated text does not', () => {
|
|
85
|
+
const binding = setupSession('dice', { terms: [{ term: '糖刀文学', kind: 'term', meaning: '又甜又虐的写法' }] })
|
|
86
|
+
const hits = lexicon.matchLexiconHits(binding.libraryId, '这段糖刀文雪啊', binding.memoryContext)
|
|
87
|
+
assert.equal(hits.length, 1, '糖刀文雪 vs 糖刀文学 shares the 糖刀 bucket and dices to 2/3')
|
|
88
|
+
assert.equal(hits[0].kindOfHit, 'dice')
|
|
89
|
+
assert.ok(hits[0].score >= lexicon.LEXICON_DICE_THRESHOLD)
|
|
90
|
+
assert.deepEqual(lexicon.matchLexiconHits(binding.libraryId, '今天天气不错', binding.memoryContext), [])
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
test('active and restored terms match; archived and rejected never match or search', () => {
|
|
94
|
+
const binding = setupSession('status', {})
|
|
95
|
+
const lib = binding.libraryId
|
|
96
|
+
// 用户写入直接 active(没有审核门)。
|
|
97
|
+
const archivedSeed = lexicon.upsertLexiconTerm({ libraryId: lib, term: '归档词', kind: 'term', meaning: '会被归档' })
|
|
98
|
+
assert.equal(archivedSeed.term.status, 'active')
|
|
99
|
+
assert.equal(lexicon.matchLexiconHits(lib, '来点归档词', binding.memoryContext).length, 1)
|
|
100
|
+
// 归档:退出匹配/注入/检索/锚点摘要。
|
|
101
|
+
lexicon.archiveLexiconTerm({ libraryId: lib, termId: archivedSeed.term.termId })
|
|
102
|
+
assert.deepEqual(lexicon.matchLexiconHits(lib, '来点归档词', binding.memoryContext), [], 'archived terms leave the matching pipeline')
|
|
103
|
+
assert.deepEqual(lexicon.searchLexicon({ libraryId: lib, query: '归档词', memoryContext: binding.memoryContext }), [], 'archived terms are not searchable')
|
|
104
|
+
assert.ok(!lexicon.visibleLexiconTerms(lib, binding.memoryContext).some(entry => entry.term === '归档词'))
|
|
105
|
+
assert.ok(!lexicon.lexiconAnchorSummary(lib, {}).lines.join('\n').includes('归档词'), 'archived terms stay out of the anchor summary')
|
|
106
|
+
// 恢复:重新参与注入与检索。
|
|
107
|
+
lexicon.restoreLexiconTerm({ libraryId: lib, termId: archivedSeed.term.termId })
|
|
108
|
+
assert.equal(lexicon.matchLexiconHits(lib, '来点归档词', binding.memoryContext).length, 1, 'restored terms rejoin injection')
|
|
109
|
+
assert.equal(lexicon.searchLexicon({ libraryId: lib, query: '归档词', memoryContext: binding.memoryContext }).length, 1)
|
|
110
|
+
// 模型提案同样直接 active,没有 pending / 审核步骤。
|
|
111
|
+
const proposal = lexicon.upsertLexiconTerm({ libraryId: lib, term: '提案词', kind: 'term', meaning: '直接生效', source: 'model-proposal' })
|
|
112
|
+
assert.equal(proposal.term.status, 'active', 'model proposals are active immediately')
|
|
113
|
+
assert.equal(lexicon.matchLexiconHits(lib, '来点提案词', binding.memoryContext).length, 1)
|
|
114
|
+
// rejected 是内部墓碑(没有公开 API 产出它):永不匹配、永不检索。
|
|
115
|
+
const tombstone = lexicon.upsertLexiconTerm({ libraryId: lib, term: '墓碑词', kind: 'term', meaning: '内部墓碑' })
|
|
116
|
+
const file = lexFile(lib)
|
|
117
|
+
const raw = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
118
|
+
raw.terms[tombstone.term.termId].status = 'rejected'
|
|
119
|
+
paths.writeJson(file, raw)
|
|
120
|
+
assert.deepEqual(lexicon.matchLexiconHits(lib, '来点墓碑词', binding.memoryContext), [], 'rejected tombstones never match')
|
|
121
|
+
assert.deepEqual(lexicon.searchLexicon({ libraryId: lib, query: '墓碑词', memoryContext: binding.memoryContext }), [], 'rejected tombstones never search')
|
|
122
|
+
assert.equal(lexicon.matchLexiconHits(lib, '来点归档词', binding.memoryContext).length, 1, 'the restored term still matches')
|
|
123
|
+
})
|
|
124
|
+
|
|
125
|
+
test('stableRank: sensitive trigger > exact term > dice, then strength×confidence, deterministic across runs', () => {
|
|
126
|
+
const binding = setupSession('rank', { terms: [
|
|
127
|
+
{ term: '敏感词甲', kind: 'trigger', meaning: '触发' }, // trigger 默认 sensitive
|
|
128
|
+
{ term: '普通词乙', kind: 'meme', meaning: '普通' },
|
|
129
|
+
{ term: '糖刀文学', kind: 'term', meaning: '模糊' },
|
|
130
|
+
] })
|
|
131
|
+
const lib = binding.libraryId
|
|
132
|
+
setStrength(lib, '敏感词甲', 0.1)
|
|
133
|
+
setStrength(lib, '普通词乙', 0.9)
|
|
134
|
+
setStrength(lib, '糖刀文学', 0.5)
|
|
135
|
+
const hits = lexicon.matchLexiconHits(lib, '敏感词甲和普通词乙加糖刀文雪', binding.memoryContext)
|
|
136
|
+
assert.deepEqual(hits.map(hit => hit.term), ['敏感词甲', '普通词乙', '糖刀文学'],
|
|
137
|
+
'sensitive trigger first, then exact by strength, dice last — despite strength order')
|
|
138
|
+
const again = lexicon.matchLexiconHits(lib, '敏感词甲和普通词乙加糖刀文雪', binding.memoryContext)
|
|
139
|
+
assert.deepEqual(again, hits, 'the ranking is a pure function of the data, not of time or iteration order')
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
test('stableRank: final tie-break is the lexicographic id, never the clock', () => {
|
|
143
|
+
const binding = setupSession('tie', { terms: [
|
|
144
|
+
{ term: '双生甲', kind: 'term', meaning: '同分一' },
|
|
145
|
+
{ term: '双生乙', kind: 'term', meaning: '同分二' },
|
|
146
|
+
] })
|
|
147
|
+
// 两个词条完全同分(strength/confidence/updatedAt 手工抹平):顺序只能由 termId 决定。
|
|
148
|
+
const lex = lexicon.loadLexicon(binding.libraryId)
|
|
149
|
+
for (const entry of Object.values(lex.terms)) {
|
|
150
|
+
entry.strength = 0.5
|
|
151
|
+
entry.confidence = 0.5
|
|
152
|
+
entry.updatedAt = '2026-01-01T00:00:00.000Z'
|
|
153
|
+
}
|
|
154
|
+
paths.writeJson(lexFile(binding.libraryId), lex)
|
|
155
|
+
const hits = lexicon.matchLexiconHits(binding.libraryId, '双生甲和双生乙都在这句话里', binding.memoryContext)
|
|
156
|
+
assert.equal(hits.length, 2)
|
|
157
|
+
assert.deepEqual(hits.map(hit => hit.termId), [...hits.map(hit => hit.termId)].sort((a, b) => a.localeCompare(b)))
|
|
158
|
+
const onceMore = lexicon.matchLexiconHits(binding.libraryId, '双生甲和双生乙都在这句话里', binding.memoryContext)
|
|
159
|
+
assert.deepEqual(onceMore.map(hit => hit.termId), hits.map(hit => hit.termId))
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
// ---- 冷却与回合预算(§3.3) ----
|
|
163
|
+
|
|
164
|
+
test('cooldownAndBudget: at most LEXICON_MAX_PER_TURN terms per turn, token budget respected', () => {
|
|
165
|
+
const binding = setupSession('budget', { terms: [
|
|
166
|
+
{ term: '预算词甲', kind: 'term', meaning: '甲' },
|
|
167
|
+
{ term: '预算词乙', kind: 'term', meaning: '乙' },
|
|
168
|
+
{ term: '预算词丙', kind: 'term', meaning: '丙' },
|
|
169
|
+
] })
|
|
170
|
+
setStrength(binding.libraryId, '预算词甲', 0.9)
|
|
171
|
+
setStrength(binding.libraryId, '预算词乙', 0.6)
|
|
172
|
+
setStrength(binding.libraryId, '预算词丙', 0.3)
|
|
173
|
+
lexicon.lexiconCooldownStore.clear()
|
|
174
|
+
const hits = lexicon.matchLexiconHits(binding.libraryId, '预算词甲预算词乙预算词丙', binding.memoryContext)
|
|
175
|
+
assert.equal(hits.length, 3)
|
|
176
|
+
const { selected, onCooldown } = lexicon.cooldownAndBudget(hits, binding.sessionId, 10_000)
|
|
177
|
+
assert.equal(selected.length, lexicon.LEXICON_MAX_PER_TURN)
|
|
178
|
+
assert.deepEqual(selected.map(hit => hit.term), ['预算词甲', '预算词乙'], 'highest strength first; the third waits for the next turn')
|
|
179
|
+
assert.deepEqual(onCooldown, [])
|
|
180
|
+
// 预算小到一行都放不下:一个都不选,hits 原样保留给 candidate 计数。
|
|
181
|
+
const squeezed = lexicon.cooldownAndBudget(hits, binding.sessionId, 3)
|
|
182
|
+
assert.deepEqual(squeezed.selected, [])
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
test('cooldown: within 30 minutes a term is counted as candidate but never injected again', () => {
|
|
186
|
+
const binding = setupSession('cooldown', { terms: [{ term: '冷却词', kind: 'term', meaning: '含义' }] })
|
|
187
|
+
lexicon.lexiconCooldownStore.clear()
|
|
188
|
+
const lib = binding.libraryId
|
|
189
|
+
// loadLexicon 返回原始 terms 表,termId 就是键名。
|
|
190
|
+
const entryId = () => Object.keys(lexicon.loadLexicon(lib).terms)[0]
|
|
191
|
+
|
|
192
|
+
const first = inject.injectLexiconTurn({ binding, sessionId: binding.sessionId, userTexts: ['这句话提到冷却词'], tokenBudget: 10_000 })
|
|
193
|
+
assert.equal(first.selected.length, 1)
|
|
194
|
+
inject.commitLexiconTurn({ libraryId: lib, sessionId: binding.sessionId, hits: first.hits, selected: first.selected })
|
|
195
|
+
assert.ok(lexicon.lexiconCooldownStore.get(binding.sessionId)?.has(entryId()), 'the cooldown store remembers the injection per binding')
|
|
196
|
+
|
|
197
|
+
const second = inject.injectLexiconTurn({ binding, sessionId: binding.sessionId, userTexts: ['冷却词又出现了'], tokenBudget: 10_000 })
|
|
198
|
+
assert.equal(second.text, '', 'no B-channel text while cooling down')
|
|
199
|
+
assert.equal(second.selected.length, 0)
|
|
200
|
+
assert.equal(second.onCooldown.length, 1)
|
|
201
|
+
inject.commitLexiconTurn({ libraryId: lib, sessionId: binding.sessionId, hits: second.hits, selected: second.selected })
|
|
202
|
+
|
|
203
|
+
const entry = lexicon.loadLexicon(lib).terms[entryId()]
|
|
204
|
+
assert.deepEqual(entry.hitCounts, { candidate: 2, injection: 1, query: 0 },
|
|
205
|
+
'cooldown suppresses injection only; the candidate still counts')
|
|
206
|
+
assert.ok(lexicon.lexiconOnCooldown(binding.sessionId, entryId()))
|
|
207
|
+
assert.equal(lexicon.LEXICON_RECALL_COOLDOWN_MINUTES, 30)
|
|
208
|
+
assert.equal(lexicon.LEXICON_MAX_PER_TURN, 2)
|
|
209
|
+
})
|
|
210
|
+
|
|
211
|
+
test('cooldown does not leak across bindings', () => {
|
|
212
|
+
const binding = setupSession('cooldown-scope', { terms: [{ term: '跨会话词', kind: 'term', meaning: '含义' }] })
|
|
213
|
+
lexicon.lexiconCooldownStore.clear()
|
|
214
|
+
const first = inject.injectLexiconTurn({ binding, sessionId: binding.sessionId, userTexts: ['跨会话词'], tokenBudget: 10_000 })
|
|
215
|
+
inject.commitLexiconTurn({ libraryId: binding.libraryId, sessionId: binding.sessionId, hits: first.hits, selected: first.selected })
|
|
216
|
+
const other = inject.injectLexiconTurn({ binding, sessionId: 'another-binding', userTexts: ['跨会话词'], tokenBudget: 10_000 })
|
|
217
|
+
assert.equal(other.selected.length, 1, 'another session has its own cooldown window')
|
|
218
|
+
})
|
|
219
|
+
|
|
220
|
+
// ---- 锚点摘要(通道 A) ----
|
|
221
|
+
|
|
222
|
+
test('buildLexiconAnchor packs to the 300-token hard cap and drops the weakest lines first', () => {
|
|
223
|
+
const terms = []
|
|
224
|
+
for (let i = 0; i < 9; i++) terms.push({ term: `词条甲乙丙${i}`, kind: 'term', meaning: '长'.repeat(400) })
|
|
225
|
+
const binding = setupSession('anchor-cap', { terms })
|
|
226
|
+
const lib = binding.libraryId
|
|
227
|
+
const lex = lexicon.loadLexicon(lib)
|
|
228
|
+
const ids = Object.keys(lex.terms)
|
|
229
|
+
ids.forEach((id, i) => { lex.terms[id].strength = (i + 1) / ids.length })
|
|
230
|
+
paths.writeJson(lexFile(lib), lex)
|
|
231
|
+
|
|
232
|
+
// 300 硬上限:8 条上限 + 超预算丢尾部(最弱的一条先丢)。每条 meaning 截到
|
|
233
|
+
// 80 字 ≈ 86 token,300 的预算装得下 3 条。
|
|
234
|
+
const full = inject.buildLexiconAnchor(binding, binding.sessionId, 300)
|
|
235
|
+
assert.ok(full.text.length > 0)
|
|
236
|
+
assert.ok(estTokens(full.text) <= 300, `anchor section must fit 300 tokens, got ${estTokens(full.text)}`)
|
|
237
|
+
assert.ok(!full.text.includes('词条甲乙丙0'), 'the weakest term is the first dropped')
|
|
238
|
+
const summary = lexicon.lexiconAnchorSummary(lib, {})
|
|
239
|
+
assert.equal(summary.lines.length, 8, 'at most 8 summary lines even with 9 candidates')
|
|
240
|
+
assert.match(summary.lines[0], /词条甲乙丙8/, 'strongest first')
|
|
241
|
+
|
|
242
|
+
// 更小的预算:只有最强的几行能留下。
|
|
243
|
+
const tight = inject.buildLexiconAnchor(binding, binding.sessionId, 200)
|
|
244
|
+
assert.ok(estTokens(tight.text) <= 200, `tight section must fit 200 tokens, got ${estTokens(tight.text)}`)
|
|
245
|
+
assert.ok(tight.text.includes('词条甲乙丙8'))
|
|
246
|
+
assert.ok(!tight.text.includes('词条甲乙丙2'))
|
|
247
|
+
// 预算为 0:整节放弃,不挤占记忆预算。
|
|
248
|
+
assert.deepEqual(inject.buildLexiconAnchor(binding, binding.sessionId, 0), { text: '', ids: [] })
|
|
249
|
+
})
|
|
250
|
+
|
|
251
|
+
test('the anchor section lists sensitive triggers separately with cap 2', () => {
|
|
252
|
+
const terms = []
|
|
253
|
+
for (let i = 0; i < 4; i++) terms.push({ term: `触发词组${i}`, kind: 'trigger', meaning: `触发${i}` })
|
|
254
|
+
terms.push({ term: '普通展示词', kind: 'term', meaning: '普通' })
|
|
255
|
+
const binding = setupSession('anchor-sensitive', { terms })
|
|
256
|
+
const lib = binding.libraryId
|
|
257
|
+
const lex = lexicon.loadLexicon(lib)
|
|
258
|
+
// 拉开梯度,避免同分 tie-break 让"前两名"变成随机对。
|
|
259
|
+
const strengths = { 触发词组0: 0.9, 触发词组1: 0.8, 触发词组2: 0.7, 触发词组3: 0.6, 普通展示词: 0.1 }
|
|
260
|
+
for (const entry of Object.values(lex.terms)) entry.strength = strengths[entry.term] ?? 0.5
|
|
261
|
+
paths.writeJson(lexFile(lib), lex)
|
|
262
|
+
const section = inject.buildLexiconAnchor(binding, binding.sessionId, 300)
|
|
263
|
+
assert.match(section.text, /\[lexicon · 敏感词\]/)
|
|
264
|
+
const sensitivePart = section.text.split('[lexicon · 敏感词]')[1] || ''
|
|
265
|
+
assert.ok(sensitivePart.includes('触发词组0') && sensitivePart.includes('触发词组1'))
|
|
266
|
+
assert.ok(!sensitivePart.includes('触发词组2'), 'at most 2 sensitive triggers in the anchor')
|
|
267
|
+
assert.ok(section.text.includes('普通展示词'), 'normal terms still appear in the main lines')
|
|
268
|
+
})
|
|
269
|
+
|
|
270
|
+
// ---- 端到端:injectForStep(原生用户消息路径) ----
|
|
271
|
+
|
|
272
|
+
test('injectForStep appends the anchor lexicon summary and the B-channel hit block', async () => {
|
|
273
|
+
const binding = setupSession('e2e', {
|
|
274
|
+
terms: [
|
|
275
|
+
{ term: '糖刀', kind: 'meme', meaning: '表面发糖、实际虐心' },
|
|
276
|
+
{ term: '锚点常驻词', kind: 'term', meaning: '常驻含义' },
|
|
277
|
+
],
|
|
278
|
+
memories: [{
|
|
279
|
+
id: 'mem-pin',
|
|
280
|
+
entry: {
|
|
281
|
+
track: 'memory', layer: 'must_remember', title: '凉茶', content: '今天他走的时候没看我。',
|
|
282
|
+
status: 'active', pinSource: 'user_explicit', pinReason: '记得', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
|
|
283
|
+
},
|
|
284
|
+
}],
|
|
285
|
+
})
|
|
286
|
+
const agent = agentFor(binding)
|
|
287
|
+
// 真实用户消息先走 inbound journal(与宿主事件路径同构),再进入决策消息。
|
|
288
|
+
inbound.ingestInboundBatch({
|
|
289
|
+
sessionId: binding.sessionId, session: agent.session, ctx: null,
|
|
290
|
+
batch: { type: inbound.INBOUND_TYPE, version: 1, producer: 'host.user', batchId: 'user:u1',
|
|
291
|
+
messages: [{ id: 'u1', role: 'user', context: {}, content: [{ type: 'text', text: '这段太糖刀了' }] }] },
|
|
292
|
+
})
|
|
293
|
+
const decision = { kind: 'enter', messages: [userMessage('u1', '这段太糖刀了')] }
|
|
294
|
+
const out = await inject.injectForStep({ agent, decision, turn: 1, step: 1, signal: { aborted: false }, log: () => {}, ctx: null })
|
|
295
|
+
const texts = pluginTexts(out)
|
|
296
|
+
assert.equal(texts.length, 1, 'one plugin message carries anchor + lexicon')
|
|
297
|
+
assert.match(texts[0], /===== memory anchor/)
|
|
298
|
+
assert.match(texts[0], /凉茶/, 'memory recall itself is untouched')
|
|
299
|
+
assert.match(texts[0], /\[lexicon · 词典\]/, 'anchor lexicon summary rides the anchor block')
|
|
300
|
+
assert.match(texts[0], /锚点常驻词/)
|
|
301
|
+
assert.match(texts[0], /<memory-lexicon>/, 'the B-channel hit block is in the same message')
|
|
302
|
+
assert.match(texts[0], /糖刀」:表面发糖、实际虐心/)
|
|
303
|
+
|
|
304
|
+
// 注入记账:candidate + injection 各一次,冷却已记。
|
|
305
|
+
const lib = binding.libraryId
|
|
306
|
+
const [entryId, entry] = Object.entries(lexicon.loadLexicon(lib).terms).find(([, t]) => t.normalizedTerm === '糖刀')
|
|
307
|
+
assert.deepEqual(entry.hitCounts, { candidate: 1, injection: 1, query: 0 })
|
|
308
|
+
assert.ok(lexicon.lexiconOnCooldown(binding.sessionId, entryId))
|
|
309
|
+
})
|
|
310
|
+
|
|
311
|
+
test('the second turn inside the cooldown window injects no lexicon block but still counts candidates', async () => {
|
|
312
|
+
const binding = setupSession('e2e-cooldown', { terms: [{ term: '冷却验证词', kind: 'term', meaning: '含义' }] })
|
|
313
|
+
const agent = agentFor(binding)
|
|
314
|
+
const send = async (id, text, turn) => {
|
|
315
|
+
inbound.ingestInboundBatch({
|
|
316
|
+
sessionId: binding.sessionId, session: agent.session, ctx: null,
|
|
317
|
+
batch: { type: inbound.INBOUND_TYPE, version: 1, producer: 'host.user', batchId: `user:${id}`,
|
|
318
|
+
messages: [{ id, role: 'user', context: {}, content: [{ type: 'text', text }] }] },
|
|
319
|
+
})
|
|
320
|
+
return inject.injectForStep({ agent, decision: { kind: 'enter', messages: [userMessage(id, text)] }, turn, step: 1, signal: { aborted: false }, log: () => {}, ctx: null })
|
|
321
|
+
}
|
|
322
|
+
await send('c1', '关于冷却验证词', 1)
|
|
323
|
+
const second = await send('c2', '再说一次冷却验证词', 2)
|
|
324
|
+
const texts = pluginTexts(second)
|
|
325
|
+
assert.ok(!texts.some(text => text.includes('<memory-lexicon>')), 'cooldown blocks the repeat injection')
|
|
326
|
+
const entry = Object.values(lexicon.loadLexicon(binding.libraryId).terms)[0]
|
|
327
|
+
assert.deepEqual(entry.hitCounts, { candidate: 2, injection: 1, query: 0 })
|
|
328
|
+
})
|
|
329
|
+
|
|
330
|
+
// ---- 端到端:inbound 批次路径(桥接 producer,无原生用户消息的回合) ----
|
|
331
|
+
|
|
332
|
+
test('the B channel also rides the real inbound batch path', async () => {
|
|
333
|
+
const binding = setupSession('e2e-bridge', { terms: [{ term: '糖刀', kind: 'meme', meaning: '表面发糖、实际虐心' }] })
|
|
334
|
+
const agent = agentFor(binding)
|
|
335
|
+
inbound.ingestInboundBatch({
|
|
336
|
+
sessionId: binding.sessionId, session: agent.session, ctx: null,
|
|
337
|
+
batch: { type: inbound.INBOUND_TYPE, version: 1, producer: 'friend-app', batchId: 'bridge:1',
|
|
338
|
+
messages: [{ id: 'bridge-1', role: 'user', context: {}, content: [{ type: 'text', text: '这段太糖刀了' }] }] },
|
|
339
|
+
})
|
|
340
|
+
const out = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: [] }, turn: 1, step: 1, signal: { aborted: false }, log: () => {}, ctx: null })
|
|
341
|
+
const texts = pluginTexts(out)
|
|
342
|
+
assert.equal(texts.length, 1)
|
|
343
|
+
assert.match(texts[0], /<memory-lexicon>/)
|
|
344
|
+
assert.match(texts[0], /表面发糖、实际虐心/)
|
|
345
|
+
const entry = Object.values(lexicon.loadLexicon(binding.libraryId).terms)[0]
|
|
346
|
+
assert.deepEqual(entry.hitCounts, { candidate: 1, injection: 1, query: 0 })
|
|
347
|
+
})
|
|
348
|
+
|
|
349
|
+
test('plugin notices, tool results and assistant text are not lexicon text sources', async () => {
|
|
350
|
+
const binding = setupSession('e2e-sources', { terms: [{ term: '糖刀', kind: 'meme', meaning: '表面发糖' }] })
|
|
351
|
+
const agent = agentFor(binding)
|
|
352
|
+
// 决策消息里只有插件消息与 assistant 自言自语;没有真实用户消息。
|
|
353
|
+
const pluginNotice = {
|
|
354
|
+
id: 'notice-1', role: 'user', source: { kind: 'plugin:dsh-memu-memory' },
|
|
355
|
+
content: [{ type: 'text', text: '糖刀糖刀糖刀' }],
|
|
356
|
+
}
|
|
357
|
+
const assistant = {
|
|
358
|
+
id: 'a1', role: 'assistant', content: [{ type: 'text', text: '我自己提到了糖刀' }],
|
|
359
|
+
}
|
|
360
|
+
const out = await inject.injectForStep({ agent, decision: { kind: 'enter', messages: [pluginNotice, assistant] }, turn: 1, step: 1, signal: { aborted: false }, log: () => {}, ctx: null })
|
|
361
|
+
const texts = pluginTexts(out)
|
|
362
|
+
assert.ok(!texts.some(text => text.includes('<memory-lexicon>')), 'no lexicon hit may come from non-user text')
|
|
363
|
+
const entry = Object.values(lexicon.loadLexicon(binding.libraryId).terms)[0]
|
|
364
|
+
assert.deepEqual(entry.hitCounts, { candidate: 0, injection: 0, query: 0 })
|
|
365
|
+
})
|
|
366
|
+
|
|
367
|
+
// ---- fail-open(§3.3) ----
|
|
368
|
+
|
|
369
|
+
test('a broken lexicon degrades with logger.warn + lastRecallError and never blocks memory recall', async () => {
|
|
370
|
+
const binding = setupSession('failopen', {
|
|
371
|
+
terms: [{ term: '糖刀', kind: 'meme', meaning: '表面发糖' }],
|
|
372
|
+
memories: [{
|
|
373
|
+
id: 'mem-pin',
|
|
374
|
+
entry: {
|
|
375
|
+
track: 'memory', layer: 'must_remember', title: '凉茶', content: '今天他走的时候没看我。',
|
|
376
|
+
status: 'active', pinSource: 'user_explicit', pinReason: '记得', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
|
|
377
|
+
},
|
|
378
|
+
}],
|
|
379
|
+
})
|
|
380
|
+
// 词典文件损坏:loadLexicon 抛 LEXICON_CORRUPT,注入链必须吞掉并继续。
|
|
381
|
+
fs.writeFileSync(lexFile(binding.libraryId), '{ this is not json')
|
|
382
|
+
const warnings = []
|
|
383
|
+
const agent = agentFor(binding)
|
|
384
|
+
inbound.ingestInboundBatch({
|
|
385
|
+
sessionId: binding.sessionId, session: agent.session, ctx: null,
|
|
386
|
+
batch: { type: inbound.INBOUND_TYPE, version: 1, producer: 'host.user', batchId: 'user:u1',
|
|
387
|
+
messages: [{ id: 'u1', role: 'user', context: {}, content: [{ type: 'text', text: '这段太糖刀了' }] }] },
|
|
388
|
+
})
|
|
389
|
+
const out = await inject.injectForStep({
|
|
390
|
+
agent, decision: { kind: 'enter', messages: [userMessage('u1', '这段太糖刀了')] },
|
|
391
|
+
turn: 1, step: 1, signal: { aborted: false },
|
|
392
|
+
log: (message) => warnings.push(String(message)), ctx: null,
|
|
393
|
+
})
|
|
394
|
+
const texts = pluginTexts(out)
|
|
395
|
+
assert.equal(texts.length, 1, 'the plugin message still exists')
|
|
396
|
+
assert.match(texts[0], /===== memory anchor/, 'memory recall output survived')
|
|
397
|
+
assert.match(texts[0], /凉茶/, 'the pinned memory is still injected')
|
|
398
|
+
assert.ok(!texts[0].includes('<memory-lexicon>'), 'no lexicon block when the lexicon is broken')
|
|
399
|
+
assert.ok(warnings.some(w => /lexicon degraded/.test(w)), 'the failure is logged, not swallowed silently')
|
|
400
|
+
const current = state.getSessionBinding(binding.sessionId)
|
|
401
|
+
assert.match(String(current.lastRecallError || ''), /lexicon/, 'binding.lastRecallError records the degradation')
|
|
402
|
+
// 记忆召回的错误面没有被词典污染成"召回失败"。
|
|
403
|
+
assert.ok(!/private recall failed/.test(String(current.lastRecallError || '')))
|
|
404
|
+
})
|
|
405
|
+
|
|
406
|
+
test('a corrupt lexicon still surfaces a typed error for readers', () => {
|
|
407
|
+
const binding = setupSession('failopen-read', {})
|
|
408
|
+
fs.writeFileSync(lexFile(binding.libraryId), 'not json at all')
|
|
409
|
+
assert.throws(() => lexicon.loadLexicon(binding.libraryId), (error) => error.code === 'LEXICON_CORRUPT')
|
|
410
|
+
})
|