dsh-memu-memory 1.4.4 → 1.4.5
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/CHANGELOG.md +11 -0
- package/README.md +33 -14
- package/README.zh.md +34 -12
- package/assets/screenshots/drawer.jpg +0 -0
- package/assets/screenshots/libraries.jpg +0 -0
- package/assets/screenshots/mobile.jpg +0 -0
- package/assets/screenshots/relations.jpg +0 -0
- package/assets/screenshots/settings.jpg +0 -0
- package/assets/screenshots/webui-dark.jpg +0 -0
- package/assets/screenshots/webui-memory.jpg +0 -0
- package/docs/client-conventions.md +19 -3
- package/docs/contributing.md +4 -2
- package/docs/env-and-commands.md +9 -1
- package/docs/graph-scale.md +214 -0
- package/docs/lexicon-recall.md +100 -0
- package/docs/mcp-porting.md +8 -6
- package/docs/memory-semantics.md +35 -3
- package/docs/pending-work.md +3 -1
- package/docs/retention.md +83 -0
- package/docs/rt-index.md +452 -0
- package/docs/scale-performance.md +101 -0
- package/docs/token-budget.md +92 -0
- package/docs/troubleshooting.md +50 -11
- package/lib/auto-link/apply.js +7 -2
- package/lib/auto-link/candidates.js +32 -10
- package/lib/backup.js +67 -32
- package/lib/binding-diagnostics.js +1 -1
- package/lib/bounded-cache.js +80 -0
- package/lib/client.js +2096 -409
- package/lib/consolidation-ledger.js +21 -4
- package/lib/consolidation-worker.js +14 -1
- package/lib/cycle.js +16 -11
- package/lib/diagnostic-context.js +372 -0
- package/lib/diagnostics.js +147 -61
- package/lib/embedding-download.js +7 -8
- package/lib/engine-sources.js +286 -0
- package/lib/engine.js +23 -10
- package/lib/entity-repair.js +43 -13
- package/lib/entity-review.js +64 -0
- package/lib/environment-check.js +348 -36
- package/lib/feedback.js +25 -0
- package/lib/global-graph.js +46 -2
- package/lib/graph-adjacency-index.js +525 -0
- package/lib/graph-overview.js +293 -0
- package/lib/graph.js +658 -105
- package/lib/inbound.js +44 -15
- package/lib/index-pages.js +57 -0
- package/lib/index.js +44 -6
- package/lib/inject.js +119 -50
- package/lib/lexicon-rt-source.js +25 -0
- package/lib/lexicon-rt-worker.js +26 -0
- package/lib/lexicon-rt.js +224 -0
- package/lib/lexicon-scope.js +56 -5
- package/lib/lexicon.js +143 -54
- package/lib/local-vector-service.js +3 -0
- package/lib/maintenance-ledger.js +542 -12
- package/lib/managed-runtime.js +260 -80
- package/lib/media.js +1 -1
- package/lib/memory.js +564 -131
- package/lib/port-surface.js +96 -11
- package/lib/private.js +47 -21
- package/lib/recall-cache.js +20 -34
- package/lib/retention.js +173 -0
- package/lib/rpc.js +135 -52
- package/lib/rt-index/builder.js +209 -0
- package/lib/rt-index/format.js +231 -0
- package/lib/rt-index/manifest.js +105 -0
- package/lib/rt-index/reader.js +673 -0
- package/lib/rt-index-retention.js +151 -0
- package/lib/rt-index-service.js +283 -0
- package/lib/rt-index-worker.js +21 -0
- package/lib/salient-wake.js +55 -4
- package/lib/state.js +195 -24
- package/lib/temporal.js +39 -13
- package/lib/token-measurement.js +126 -0
- package/lib/tools.js +101 -6
- package/lib/turn-log.js +108 -3
- package/lib/webui/graph-layout-worker.js +68 -0
- package/lib/webui/graph-local-physics.js +390 -0
- package/lib/webui/graph-spatial-grid.js +64 -0
- package/lib/webui/graph-view.bundle.js +6 -1
- package/lib/webui/graph-view.js +478 -135
- package/lib/webui/graph-webgl-renderer.js +74 -0
- package/lib/webui/standalone.js +1 -1
- package/lib/worker-pool.js +30 -4
- package/package.json +3 -2
- package/scripts/acceptance-local.mjs +4 -10
- package/scripts/bench-all-libraries.mjs +47 -0
- package/scripts/check-classic-graph-browser.mjs +189 -0
- package/scripts/check-client-browser.mjs +929 -0
- package/scripts/check-graph-browser.mjs +6 -0
- package/scripts/check-graph-elastic-browser.mjs +139 -0
- package/scripts/check-memory-review-browser.mjs +124 -0
- package/scripts/entity-dedupe.mjs +19 -3
- package/scripts/graph-artifact-provenance.mjs +30 -0
- package/scripts/graph-freeze-manifest.mjs +129 -0
- package/scripts/graph-geometry-fixture.mjs +40 -0
- package/scripts/graph-physics-bench.mjs +218 -0
- package/scripts/graph-scale-bench.mjs +213 -0
- package/scripts/graph-scale-memory.mjs +48 -0
- package/scripts/graph-service-bench.mjs +72 -0
- package/scripts/make-readme-shots.mjs +17 -5
- package/scripts/preview.mjs +1 -0
- package/scripts/rebuild-rt.mjs +18 -0
- package/scripts/scale-bench.mjs +183 -0
- package/scripts/simulate-injection.mjs +47 -8
- package/scripts/verify-host-fixtures.mjs +108 -0
- package/scripts/verify-host-recovery.mjs +565 -0
- package/scripts/verify-vector-recovery.mjs +740 -0
- package/tests/auto-link-candidates.test.mjs +20 -0
- package/tests/browser.test.mjs +16 -2
- package/tests/client-export.test.mjs +16 -1
- package/tests/client-pagination.test.mjs +1495 -0
- package/tests/client-render.test.mjs +223 -28
- package/tests/consolidation-fork.test.mjs +93 -10
- package/tests/consolidation-ledger.test.mjs +17 -1
- package/tests/diagnostic-entity-candidates.test.mjs +54 -0
- package/tests/diagnostic-report.test.mjs +429 -0
- package/tests/diagnostic-wiring.test.mjs +88 -0
- package/tests/diagnostics.test.mjs +27 -0
- package/tests/embedding-download.test.mjs +44 -0
- package/tests/engine-source-settings.test.mjs +69 -0
- package/tests/engine-sources.test.mjs +145 -0
- package/tests/entity-dedupe.test.mjs +143 -0
- package/tests/entity-merge-review.test.mjs +363 -0
- package/tests/entity-merge.test.mjs +12 -4
- package/tests/entity-review.test.mjs +87 -0
- package/tests/environment-check.test.mjs +51 -1
- package/tests/feedback.test.mjs +95 -0
- package/tests/graph-adjacency-index.test.mjs +536 -0
- package/tests/graph-cascade.test.mjs +229 -0
- package/tests/graph-import-diagnostic.test.mjs +25 -0
- package/tests/graph-overview.test.mjs +709 -0
- package/tests/graph-session-authorization.test.mjs +419 -0
- package/tests/graph-view-geometry.test.mjs +426 -0
- package/tests/graph-view-scale.test.mjs +88 -0
- package/tests/graph-view.test.mjs +444 -5
- package/tests/graph.test.mjs +43 -0
- package/tests/help-page.test.mjs +128 -54
- package/tests/inbound.test.mjs +19 -0
- package/tests/index-pagination.test.mjs +113 -0
- package/tests/index-read-view.test.mjs +212 -0
- package/tests/inject-guide.test.mjs +9 -0
- package/tests/injection-dedupe.test.mjs +213 -0
- package/tests/lexicon-recall.test.mjs +641 -0
- package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
- package/tests/lexicon-rt.test.mjs +468 -0
- package/tests/local-embedding-worker.test.mjs +38 -0
- package/tests/local-vector-service.test.mjs +32 -3
- package/tests/maintenance-compat.test.mjs +128 -0
- package/tests/maintenance-settlement.test.mjs +1003 -0
- package/tests/managed-memory.test.mjs +39 -11
- package/tests/managed-runtime.test.mjs +109 -0
- package/tests/memory-fields.test.mjs +24 -12
- package/tests/observed-evidence.test.mjs +52 -0
- package/tests/port-surface.test.mjs +93 -1
- package/tests/recall-cache.test.mjs +56 -3
- package/tests/recall-dedup.test.mjs +63 -2
- package/tests/retention.test.mjs +260 -0
- package/tests/rt-index-cross-library.test.mjs +230 -0
- package/tests/rt-index-integration.test.mjs +194 -0
- package/tests/rt-index-retention.test.mjs +552 -0
- package/tests/rt-index-scale.test.mjs +204 -0
- package/tests/rt-index.test.mjs +705 -0
- package/tests/salient-date-boundaries.test.mjs +121 -0
- package/tests/salient-wake.test.mjs +29 -0
- package/tests/scale-bench.test.mjs +53 -0
- package/tests/settings-plumbing.test.mjs +25 -0
- package/tests/simulate-injection.test.mjs +15 -1
- package/tests/standalone-navigation.test.mjs +44 -0
- package/tests/state.test.mjs +51 -0
- package/tests/temporal-precision.test.mjs +102 -0
- package/tests/temporal.test.mjs +10 -6
- package/tests/token-measurement.test.mjs +98 -0
- package/tests/tool-schema.test.mjs +41 -5
- package/tests/tools.test.mjs +6 -3
- package/tests/turn-token-budget.test.mjs +149 -0
- package/tests/webui-auth.test.mjs +57 -1
- package/tests/webui.test.mjs +40 -15
|
@@ -0,0 +1,641 @@
|
|
|
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-lexicon-recall-'))
|
|
8
|
+
process.env.DSH_HOME = home
|
|
9
|
+
process.env.DSH_MEMU_HOME = home
|
|
10
|
+
process.env.DSH_MEMU_MEMORY_HOME = home
|
|
11
|
+
const state = await import('../lib/state.js')
|
|
12
|
+
const lexicon = await import('../lib/lexicon.js')
|
|
13
|
+
const scope = await import('../lib/lexicon-scope.js')
|
|
14
|
+
const memory = await import('../lib/memory.js')
|
|
15
|
+
const inject = await import('../lib/inject.js')
|
|
16
|
+
const inbound = await import('../lib/inbound.js')
|
|
17
|
+
const paths = await import('../lib/paths.js')
|
|
18
|
+
const { dispatch } = await import('../lib/rpc.js')
|
|
19
|
+
const { registerTools } = await import('../lib/tools.js')
|
|
20
|
+
const { estTokens } = await import('../lib/budget.js')
|
|
21
|
+
const { closeLexiconRt, waitForLexiconRt } = await import('../lib/lexicon-rt.js')
|
|
22
|
+
|
|
23
|
+
test.after(async () => { await closeLexiconRt(); state.flushState(); fs.rmSync(home, { recursive: true, force: true }) })
|
|
24
|
+
let serial = 0
|
|
25
|
+
function fixture(label, domain = 'coding') {
|
|
26
|
+
const id = `lex-recall-${label}-${++serial}`
|
|
27
|
+
const cwd = path.join(home, id)
|
|
28
|
+
state.updateSettings({ memoryBackend: 'agent', crossLibraryRecall: false, relevanceThreshold: 0,
|
|
29
|
+
injectionTotalTokens: 2000, turnTokens: 640, autoInject: 'per-turn', randomCueChance: 0, habitsInjection: false })
|
|
30
|
+
const original = state.ensureSession(id, { cwd, agentPreset: domain })
|
|
31
|
+
state.setSessionBinding(id, { domainOverride: domain, useGlobal: false, useLibrary: true })
|
|
32
|
+
const binding = () => state.getSessionBinding(id)
|
|
33
|
+
const agent = { session: { header: { id, cwd, origin: 'user', agentPreset: domain }, messages: [] } }
|
|
34
|
+
return { id, cwd, libraryId: original.libraryId, binding, agent, exec: { agent } }
|
|
35
|
+
}
|
|
36
|
+
const fileFor = libraryId => path.join(home, 'lexicon', `${libraryId}.json`)
|
|
37
|
+
function add(f, term, meaning, extra = {}) {
|
|
38
|
+
return lexicon.upsertLexiconTerm({ libraryId: f.libraryId || f, term, meaning, kind: 'term', source: 'user', ...extra }).term
|
|
39
|
+
}
|
|
40
|
+
function recall(f, query, options) { return scope.recallLexicon(f.binding(), query, options) }
|
|
41
|
+
function counts(f, id) { return lexicon.loadLexicon(f.libraryId).terms[id].hitCounts }
|
|
42
|
+
function putMemory(f, id, extra = {}) {
|
|
43
|
+
const index = state.loadPrivateIndex(f.libraryId)
|
|
44
|
+
index.entries[id] = { track: 'memory', layer: 'long_term', status: 'active', title: '挫折后沉默',
|
|
45
|
+
content: '上次遇到挫折后沉默了很久。', confidence: 1, strength: 1,
|
|
46
|
+
createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), ...extra }
|
|
47
|
+
state.savePrivateIndex(f.libraryId, index)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
test('meaning, usage and examples recall concepts without the term or alias appearing', () => {
|
|
51
|
+
const f = fixture('concept')
|
|
52
|
+
const expected = add(f, '破防', '遇到挫折后沉默', { usage: '拒绝继续讨论', examples: ['关机之后独自散步'] })
|
|
53
|
+
for (const query of ['遇到挫折后沉默', '拒绝继续讨论', '关机之后独自散步']) {
|
|
54
|
+
assert.ok(!query.includes(expected.term))
|
|
55
|
+
assert.equal(lexicon.matchLexiconHits(f.libraryId, query, {}).length, 0)
|
|
56
|
+
const result = recall(f, query)
|
|
57
|
+
assert.equal(result.lexicon[0].termId, expected.termId)
|
|
58
|
+
assert.equal(result.lexicon[0].matchedBy, 'recall-bm25')
|
|
59
|
+
assert.equal(result.lexicon[0].ref, `[lex:${expected.termId}]`)
|
|
60
|
+
assert.equal(result.lexicon[0].rrfScore, 1 / 61)
|
|
61
|
+
}
|
|
62
|
+
assert.deepEqual(counts(f, expected.termId), { candidate: 0, injection: 0, query: 0 }, 'retrieval must not book an injection')
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
test('RRF uses k=60, independent <=2 slots, and preserves exact/alias/dice labels', () => {
|
|
66
|
+
const f = fixture('fusion')
|
|
67
|
+
const exact = add(f, '糖刀文学', '明亮开场随后转为悲剧', { aliases: ['糖里藏刀'] })
|
|
68
|
+
for (const [query, matchedBy] of [['糖刀文学', 'exact-term'], ['糖里藏刀', 'exact-alias'], ['糖刀文雪', 'dice']]) {
|
|
69
|
+
const hit = recall(f, query).lexicon.find(hit => hit.termId === exact.termId)
|
|
70
|
+
assert.equal(hit.matchedBy, matchedBy)
|
|
71
|
+
assert.equal(hit.rrfScore, Object.values(hit.ranks).reduce((sum, rank) => sum + 1 / (60 + rank), 0))
|
|
72
|
+
}
|
|
73
|
+
for (const term of ['冷茶', '关窗', '熄灯']) add(f, term, '遇到挫折后沉默')
|
|
74
|
+
assert.equal(recall(f, '遇到挫折后沉默').lexicon.length, 2)
|
|
75
|
+
assert.equal(recall(f, '遇到挫折后沉默').hits.length, 3)
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
test('postings score only candidates; a warm scoped corpus is reused', () => {
|
|
79
|
+
const f = fixture('postings')
|
|
80
|
+
const terms = {}
|
|
81
|
+
for (let i = 0; i < 300; i++) terms[`lex-fixture-${i}`] = { term: `label-${i}`, normalizedTerm: `label${i}`,
|
|
82
|
+
meaning: i === 17 ? 'superconductivity resonance' : `catalogue inventory${i}`, context: {}, status: 'active' }
|
|
83
|
+
paths.writeJson(fileFor(f.libraryId), { version: 1, revision: 1, libraryId: f.libraryId, terms })
|
|
84
|
+
const before = lexicon.lexiconRecallDiagnostics()
|
|
85
|
+
assert.equal(recall(f, 'superconductivity').lexicon[0].termId, 'lex-fixture-17')
|
|
86
|
+
const cold = lexicon.lexiconRecallDiagnostics()
|
|
87
|
+
assert.equal(cold.candidates - before.candidates, 1)
|
|
88
|
+
assert.equal(recall(f, 'superconductivity').lexicon[0].termId, 'lex-fixture-17')
|
|
89
|
+
const warm = lexicon.lexiconRecallDiagnostics()
|
|
90
|
+
assert.equal(warm.conceptBuilds, cold.conceptBuilds)
|
|
91
|
+
assert.ok(warm.concept.hits > cold.concept.hits)
|
|
92
|
+
assert.ok(warm.index.bytes <= warm.index.maxBytes)
|
|
93
|
+
assert.ok(warm.concept.bytes <= warm.concept.maxBytes)
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
test('context/knownBy/status/secret gates precede corpus statistics and all automatic projections', () => {
|
|
97
|
+
const f = fixture('privacy')
|
|
98
|
+
state.setSessionBinding(f.id, { memoryContext: { worldId: 'ours', characterId: 'reader' } })
|
|
99
|
+
const visible = add(f, '破防', '遇到挫折后沉默')
|
|
100
|
+
const original = recall(f, '遇到挫折后沉默').lexicon[0]
|
|
101
|
+
add(f, '世界秘密', '遇到挫折后沉默', { context: { worldId: 'other' } })
|
|
102
|
+
add(f, '角色秘密', '遇到挫折后沉默', { knownBy: ['other-character'] })
|
|
103
|
+
add(f, '不可浮出', '遇到挫折后沉默', { visibility: 'secret' })
|
|
104
|
+
const archived = add(f, '归档词条', '遇到挫折后沉默')
|
|
105
|
+
lexicon.archiveLexiconTerm({ libraryId: f.libraryId, termId: archived.termId })
|
|
106
|
+
const after = recall(f, '遇到挫折后沉默')
|
|
107
|
+
assert.deepEqual(after.lexicon.map(hit => hit.termId), [visible.termId])
|
|
108
|
+
assert.equal(after.lexicon[0].score, original.score, 'hidden rows must not affect df or avgdl')
|
|
109
|
+
const turn = inject.injectLexiconTurn({ binding: f.binding(), sessionId: f.id,
|
|
110
|
+
userTexts: ['世界秘密 角色秘密 不可浮出 遇到挫折后沉默'], tokenBudget: 1000 })
|
|
111
|
+
assert.deepEqual(turn.hits.map(hit => hit.termId), [visible.termId])
|
|
112
|
+
const anchor = inject.buildLexiconAnchor(f.binding()).text
|
|
113
|
+
assert.doesNotMatch(anchor, /世界秘密|角色秘密|不可浮出|归档词条/)
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
test('sensitive automatic hits and anchors expose only the term even through semantic matches', () => {
|
|
117
|
+
const f = fixture('sensitive')
|
|
118
|
+
const markers = ['密义不可泄漏', '私用不可泄漏', '私例不可泄漏', '私证不可泄漏']
|
|
119
|
+
const entry = add(f, '红灯', markers[0], { kind: 'trigger', usage: markers[1], examples: [markers[2]],
|
|
120
|
+
evidence: [{ kind: 'message', id: 'e1', quote: markers[3] }], aliases: ['私别不可泄漏'] })
|
|
121
|
+
for (const query of [markers[0], '红灯']) {
|
|
122
|
+
const result = recall(f, query)
|
|
123
|
+
assert.equal(result.lexicon[0].termId, entry.termId)
|
|
124
|
+
for (const key of ['meaning', 'usage', 'examples', 'aliases', 'evidence', 'context']) assert.ok(!(key in result.lexicon[0]), key)
|
|
125
|
+
for (const marker of markers) assert.ok(!JSON.stringify(result).includes(marker), marker)
|
|
126
|
+
const turn = inject.injectLexiconTurn({ binding: f.binding(), sessionId: f.id, userTexts: [query], tokenBudget: 800 })
|
|
127
|
+
assert.ok(turn.text.includes('红灯'))
|
|
128
|
+
for (const marker of markers) assert.ok(!JSON.stringify(turn).includes(marker), marker)
|
|
129
|
+
}
|
|
130
|
+
const anchor = inject.buildLexiconAnchor(f.binding()).text
|
|
131
|
+
assert.match(anchor, /红灯/)
|
|
132
|
+
for (const marker of markers) assert.ok(!anchor.includes(marker), marker)
|
|
133
|
+
assert.ok(recall(f, markers[0], { automatic: false }).lexicon[0].meaning, 'explicit reads keep their existing authority')
|
|
134
|
+
})
|
|
135
|
+
|
|
136
|
+
test('low-level automatic concept/match APIs do not return sensitive definitions either', () => {
|
|
137
|
+
const f = fixture('low-level-sensitive')
|
|
138
|
+
const term = add(f, '红线', 'sensitive definition marker', { sensitivity: 'sensitive', usage: 'usage marker' })
|
|
139
|
+
add(f, '暗线', 'sensitive definition marker', { visibility: 'secret' })
|
|
140
|
+
const concept = lexicon.lexiconConceptHits(f.libraryId, 'definition', {}, { automatic: true })
|
|
141
|
+
const matched = scope.lexiconMatch(f.binding(), '红线 暗线', { automatic: true }).hits
|
|
142
|
+
for (const hits of [concept, matched]) {
|
|
143
|
+
assert.deepEqual(hits.map(hit => hit.termId), [term.termId])
|
|
144
|
+
assert.equal(JSON.stringify(hits).includes('definition marker'), false)
|
|
145
|
+
assert.equal(JSON.stringify(hits).includes('usage marker'), false)
|
|
146
|
+
assert.ok(!('meaning' in hits[0]))
|
|
147
|
+
}
|
|
148
|
+
})
|
|
149
|
+
|
|
150
|
+
test('legacy trigger sensitivity is enforced in automatic projections and direct renderers', () => {
|
|
151
|
+
const f = fixture('legacy-sensitive')
|
|
152
|
+
const marker = 'legacy sensitive definition must stay private'
|
|
153
|
+
const term = add(f, '旧触发词', marker, { kind: 'trigger' })
|
|
154
|
+
const file = fileFor(f.libraryId)
|
|
155
|
+
const raw = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
156
|
+
delete raw.terms[term.termId].sensitivity
|
|
157
|
+
paths.writeJson(file, raw)
|
|
158
|
+
const result = recall(f, 'definition')
|
|
159
|
+
assert.deepEqual(result.lexicon.map(hit => hit.termId), [term.termId])
|
|
160
|
+
assert.equal(JSON.stringify(result).includes(marker), false)
|
|
161
|
+
assert.equal(inject.buildLexiconAnchor(f.binding()).text.includes(marker), false)
|
|
162
|
+
assert.equal(lexicon.lexiconTurnLine({ ...raw.terms[term.termId], termId: term.termId }).includes(marker), false)
|
|
163
|
+
assert.equal(JSON.stringify(lexicon.lexiconRecallHit({ ...raw.terms[term.termId], termId: term.termId })).includes(marker), false)
|
|
164
|
+
assert.equal(recall(f, 'definition', { automatic: false }).lexicon[0].meaning, marker)
|
|
165
|
+
assert.equal(lexicon.loadLexicon(f.libraryId).terms[term.termId].meaning, marker)
|
|
166
|
+
})
|
|
167
|
+
|
|
168
|
+
test('native and inbound automatic messages mask sensitive meanings including anchor and account after admission', async () => {
|
|
169
|
+
for (const bridge of [false, true]) {
|
|
170
|
+
const f = fixture(`complete-sensitive-${bridge}`)
|
|
171
|
+
const marker = '这段敏感释义绝不允许自动发出'
|
|
172
|
+
const term = add(f, '暂停词', `safeword ${marker}`, { sensitivity: 'sensitive', usage: `用法${marker}`,
|
|
173
|
+
examples: [`例句${marker}`], evidence: [{ kind: 'message', id: 'ev-sensitive', quote: marker }] })
|
|
174
|
+
const secret = add(f, '不可浮出的词面', 'safeword', { visibility: 'secret' })
|
|
175
|
+
const automatic = await memory.privateRecall({ exec: f.exec, query: 'safeword', purpose: 'automatic' })
|
|
176
|
+
assert.deepEqual(automatic.lexicon.map(hit => hit.termId), [term.termId])
|
|
177
|
+
assert.equal(JSON.stringify(automatic.lexicon).includes(marker), false)
|
|
178
|
+
const handlers = new Map()
|
|
179
|
+
const ctx = { on(event, handler) { handlers.set(event, handler); return () => {} }, logger: { warn() {} } }
|
|
180
|
+
const dispose = inject.registerInjection(ctx)
|
|
181
|
+
const user = { id: `sensitive-${bridge}`, role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: 'safeword' }] }
|
|
182
|
+
if (bridge) inbound.ingestInboundBatch({ sessionId: f.id, session: f.agent.session, ctx: null,
|
|
183
|
+
batch: { type: inbound.INBOUND_TYPE, version: 1, producer: 'friend-app', batchId: user.id,
|
|
184
|
+
messages: [{ id: user.id, role: 'user', context: {}, content: user.content }] } })
|
|
185
|
+
const out = await inject.injectForStep({ agent: f.agent, decision: { kind: 'enter', messages: bridge ? [] : [user] },
|
|
186
|
+
turn: 1, step: 1, signal: { aborted: false }, log() {}, ctx })
|
|
187
|
+
const plugin = out.messages.filter(message => message.source?.kind === 'plugin:dsh-memu-memory')
|
|
188
|
+
const text = plugin.map(message => message.content.map(block => block.text || '').join('\n')).join('\n')
|
|
189
|
+
assert.match(text, /\[lexicon · 敏感词\]/)
|
|
190
|
+
assert.match(text, /<memory-lexicon>/)
|
|
191
|
+
assert.ok(text.includes(`[lex:${term.termId}]`))
|
|
192
|
+
assert.equal(text.includes(marker), false)
|
|
193
|
+
assert.equal(text.includes('不可浮出的词面'), false)
|
|
194
|
+
assert.equal(JSON.stringify(plugin).includes(secret.termId), false)
|
|
195
|
+
assert.ok(estTokens(text) <= state.getSettings().injectionTotalTokens)
|
|
196
|
+
assert.equal(JSON.stringify(state.getSessionBinding(f.id).pendingInjections).includes(marker), false)
|
|
197
|
+
assert.equal(counts(f, term.termId).injection, 0)
|
|
198
|
+
assert.equal(lexicon.lexiconOnCooldown(f.id, term.termId), false)
|
|
199
|
+
for (const message of out.messages) {
|
|
200
|
+
f.agent.session.messages.push(message)
|
|
201
|
+
await handlers.get('session/event')(f.agent.session, { type: 'user/message', data: message })
|
|
202
|
+
}
|
|
203
|
+
assert.equal(counts(f, term.termId).injection, 1)
|
|
204
|
+
assert.ok(lexicon.lexiconOnCooldown(f.id, term.termId))
|
|
205
|
+
assert.equal(counts(f, secret.termId).candidate, 0)
|
|
206
|
+
assert.equal(counts(f, secret.termId).injection, 0)
|
|
207
|
+
dispose()
|
|
208
|
+
}
|
|
209
|
+
})
|
|
210
|
+
|
|
211
|
+
test('a term matched through different source channels still appears once with private priority', () => {
|
|
212
|
+
const f = fixture('cross-channel-priority')
|
|
213
|
+
state.setSessionBinding(f.id, { useGlobal: true })
|
|
214
|
+
const local = add(f, '同义约定', 'sodium')
|
|
215
|
+
for (let i = 0; i < 14; i++) add(f, `布景${i}`, '同义约定')
|
|
216
|
+
add(lexicon.GLOBAL_LEXICON_ID, '同义约定', 'heterophase', { domain: 'universal' })
|
|
217
|
+
const result = recall(f, '同义约定 heterophase')
|
|
218
|
+
assert.deepEqual(result.hits.map(hit => hit.termId), [local.termId])
|
|
219
|
+
})
|
|
220
|
+
|
|
221
|
+
test('sensitive private surfaces retain normalized source priority after their definition is stripped', () => {
|
|
222
|
+
const f = fixture('sensitive-source-priority')
|
|
223
|
+
state.setSessionBinding(f.id, { useGlobal: true })
|
|
224
|
+
const local = add(f, 'ABC', 'sodium private definition', { sensitivity: 'sensitive' })
|
|
225
|
+
add(lexicon.GLOBAL_LEXICON_ID, 'abc', 'trichromaticguard global definition', { domain: 'universal' })
|
|
226
|
+
const result = recall(f, 'ABC trichromaticguard')
|
|
227
|
+
assert.deepEqual(result.hits.map(hit => hit.termId), [local.termId])
|
|
228
|
+
assert.equal(JSON.stringify(result).includes('definition'), false)
|
|
229
|
+
})
|
|
230
|
+
|
|
231
|
+
test('automatic lexicon rendering redacts API-shaped keys before clipping anchor and turn lines', () => {
|
|
232
|
+
const f = fixture('key-render')
|
|
233
|
+
const key = `sk-${'abcdef123456'.repeat(12)}`
|
|
234
|
+
add(f, '配置词', `api_key=${key}`)
|
|
235
|
+
const anchor = inject.buildLexiconAnchor(f.binding()).text
|
|
236
|
+
const turn = inject.injectLexiconTurn({ binding: f.binding(), sessionId: f.id, userTexts: ['配置词'], tokenBudget: 800 }).text
|
|
237
|
+
for (const text of [anchor, turn]) {
|
|
238
|
+
assert.equal(/sk-[A-Za-z0-9_-]{12,}/.test(text), false)
|
|
239
|
+
assert.match(text, /REDACTED/)
|
|
240
|
+
}
|
|
241
|
+
})
|
|
242
|
+
|
|
243
|
+
test('cross-library/global/domain visibility exactly reuses the memory-side source decision', () => {
|
|
244
|
+
const homeLib = fixture('home')
|
|
245
|
+
const peer = fixture('peer')
|
|
246
|
+
const foreign = fixture('foreign', 'rp')
|
|
247
|
+
const disabled = fixture('disabled')
|
|
248
|
+
const a = add(homeLib, '本库词', 'manganese')
|
|
249
|
+
const b = add(peer, '同域词', 'manganese', { domain: 'coding' })
|
|
250
|
+
add(peer, '异域戳', 'manganese', { domain: 'rp' })
|
|
251
|
+
add(foreign, '异域库词', 'manganese')
|
|
252
|
+
add(disabled, '关库词', 'manganese')
|
|
253
|
+
state.setWorkspacePolicy(disabled.cwd, { useLibrary: false })
|
|
254
|
+
const g = add(lexicon.GLOBAL_LEXICON_ID, '全局词', 'manganese', { domain: 'universal' })
|
|
255
|
+
add(lexicon.GLOBAL_LEXICON_ID, '全局异域词', 'manganese', { domain: 'rp' })
|
|
256
|
+
assert.deepEqual(recall(homeLib, 'manganese').hits.map(hit => hit.termId), [a.termId])
|
|
257
|
+
state.setSessionBinding(homeLib.id, { useGlobal: true })
|
|
258
|
+
state.updateSettings({ crossLibraryRecall: true })
|
|
259
|
+
const expectedPrivate = memory.crossLibrarySources(homeLib.binding(), memory.domainOf(homeLib.binding())).map(source => source.libraryId)
|
|
260
|
+
assert.deepEqual(scope.lexiconSources(homeLib.binding()).filter(source => source.scope === 'private').map(source => source.libraryId), expectedPrivate)
|
|
261
|
+
assert.deepEqual(new Set(recall(homeLib, 'manganese').hits.map(hit => hit.termId)), new Set([a.termId, b.termId, g.termId]))
|
|
262
|
+
state.setSessionBinding(homeLib.id, { useLibrary: false })
|
|
263
|
+
assert.deepEqual(recall(homeLib, 'manganese').hits.map(hit => hit.termId), [g.termId])
|
|
264
|
+
state.setSessionBinding(homeLib.id, { useGlobal: false })
|
|
265
|
+
assert.deepEqual(recall(homeLib, 'manganese').hits, [])
|
|
266
|
+
})
|
|
267
|
+
|
|
268
|
+
test('same surface in private and global sources keeps the private convention', () => {
|
|
269
|
+
const f = fixture('priority')
|
|
270
|
+
state.setSessionBinding(f.id, { useGlobal: true })
|
|
271
|
+
const local = add(f, '同名词', 'zirconium convention')
|
|
272
|
+
add(lexicon.GLOBAL_LEXICON_ID, '同名词', 'zirconium convention')
|
|
273
|
+
const hits = recall(f, 'zirconium').hits
|
|
274
|
+
assert.deepEqual(hits.map(hit => [hit.libraryId, hit.termId]), [[f.libraryId, local.termId]])
|
|
275
|
+
})
|
|
276
|
+
|
|
277
|
+
test('privateRecall and memu_private_recall expose an independent lexicon array/section without losing memory slots', async () => {
|
|
278
|
+
const f = fixture('public')
|
|
279
|
+
const term = add(f, '破防', '遇到挫折后沉默')
|
|
280
|
+
putMemory(f, 'mem-evidence')
|
|
281
|
+
const result = await memory.privateRecall({ exec: f.exec, query: '遇到挫折后沉默', topK: 1 })
|
|
282
|
+
assert.equal(result.files[0].name, 'mem-evidence')
|
|
283
|
+
assert.equal(result.lexicon[0].termId, term.termId)
|
|
284
|
+
assert.equal(result.files.length, 1)
|
|
285
|
+
assert.ok(!result.refs.some(ref => ref.id === term.termId))
|
|
286
|
+
const tools = []
|
|
287
|
+
registerTools({ tools: { register(tool) { tools.push(tool) } }, logger: { warn() {} } })
|
|
288
|
+
const rendered = await tools.find(tool => tool.name === 'memu_private_recall').execute({ query: '遇到挫折后沉默' }, f.exec)
|
|
289
|
+
const text = typeof rendered === 'string' ? rendered : JSON.stringify(rendered)
|
|
290
|
+
assert.match(text, /lexicon/)
|
|
291
|
+
assert.ok(text.includes(`[lex:${term.termId}]`))
|
|
292
|
+
assert.match(text, /matchedBy=recall-bm25/)
|
|
293
|
+
assert.match(text, /mem-evidence/)
|
|
294
|
+
})
|
|
295
|
+
|
|
296
|
+
test('unbound explicit-library recall does not widen to global or secret vocabulary', async () => {
|
|
297
|
+
const f = fixture('unbound')
|
|
298
|
+
const visible = add(f, '可见术语', 'palladium')
|
|
299
|
+
add(f, '隐秘术语', 'palladium', { visibility: 'secret' })
|
|
300
|
+
add(lexicon.GLOBAL_LEXICON_ID, '全局越权词', 'palladium')
|
|
301
|
+
const result = await memory.privateRecall({ libraryId: f.libraryId, query: 'palladium' })
|
|
302
|
+
assert.deepEqual(result.lexicon.map(hit => hit.termId), [visible.termId])
|
|
303
|
+
})
|
|
304
|
+
|
|
305
|
+
test('a lexicon-only query is returned by the existing recall tool even when memories do not match', async () => {
|
|
306
|
+
const f = fixture('lexicon-only')
|
|
307
|
+
const term = add(f, '破防', '遇到挫折后沉默')
|
|
308
|
+
const tools = []
|
|
309
|
+
registerTools({ tools: { register(tool) { tools.push(tool) } }, logger: { warn() {} } })
|
|
310
|
+
const rendered = await tools.find(tool => tool.name === 'memu_private_recall').execute({ query: '遇到挫折后沉默' }, f.exec)
|
|
311
|
+
const text = typeof rendered === 'string' ? rendered : JSON.stringify(rendered)
|
|
312
|
+
assert.ok(text.includes(`[lex:${term.termId}]`))
|
|
313
|
+
assert.doesNotMatch(text, /没有命中/)
|
|
314
|
+
})
|
|
315
|
+
|
|
316
|
+
test('cached concept views switch with context and honor legacy top-level knownBy', () => {
|
|
317
|
+
const f = fixture('context-cache')
|
|
318
|
+
const publicTerm = add(f, '公共词', 'iridium')
|
|
319
|
+
const hidden = add(f, '私知词', 'iridium')
|
|
320
|
+
const file = fileFor(f.libraryId)
|
|
321
|
+
const raw = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
322
|
+
raw.terms[hidden.termId].knownBy = ['owner']
|
|
323
|
+
raw.terms[hidden.termId].context = {}
|
|
324
|
+
paths.writeJson(file, raw)
|
|
325
|
+
state.setSessionBinding(f.id, { memoryContext: { characterId: 'reader' } })
|
|
326
|
+
assert.deepEqual(recall(f, 'iridium').hits.map(hit => hit.termId), [publicTerm.termId])
|
|
327
|
+
state.setSessionBinding(f.id, { memoryContext: { characterId: 'owner' } })
|
|
328
|
+
assert.equal(recall(f, 'iridium').hits.length, 2)
|
|
329
|
+
state.setSessionBinding(f.id, { memoryContext: { characterId: 'reader' } })
|
|
330
|
+
assert.deepEqual(recall(f, 'iridium').hits.map(hit => hit.termId), [publicTerm.termId])
|
|
331
|
+
assert.doesNotMatch(inject.buildLexiconAnchor(f.binding()).text, /私知词/)
|
|
332
|
+
})
|
|
333
|
+
|
|
334
|
+
test('cached explicit views cannot bypass later sensitive or secret changes in automatic reads', () => {
|
|
335
|
+
const f = fixture('cached-privacy-change')
|
|
336
|
+
const meaning = 'cadmium definition marker'
|
|
337
|
+
const term = add(f, '缓存约定', meaning)
|
|
338
|
+
assert.equal(recall(f, 'cadmium').lexicon[0].meaning, meaning)
|
|
339
|
+
add(f, term.term, meaning, { sensitivity: 'sensitive' })
|
|
340
|
+
assert.equal(recall(f, 'cadmium', { automatic: false }).lexicon[0].meaning, meaning)
|
|
341
|
+
const automatic = recall(f, 'cadmium')
|
|
342
|
+
assert.equal(automatic.lexicon[0].termId, term.termId)
|
|
343
|
+
assert.equal(JSON.stringify(automatic).includes(meaning), false)
|
|
344
|
+
add(f, term.term, meaning, { sensitivity: 'sensitive', visibility: 'secret' })
|
|
345
|
+
assert.equal(recall(f, 'cadmium', { automatic: false }).lexicon[0].meaning, meaning)
|
|
346
|
+
assert.deepEqual(recall(f, 'cadmium').hits, [])
|
|
347
|
+
assert.deepEqual(scope.lexiconMatch(f.binding(), term.term, { automatic: true }).hits, [])
|
|
348
|
+
assert.equal(inject.buildLexiconAnchor(f.binding()).text.includes(term.term), false)
|
|
349
|
+
})
|
|
350
|
+
|
|
351
|
+
test('full lexicon block fits every supplied budget; proposals do not consume cooldown/accounting', () => {
|
|
352
|
+
const f = fixture('budget')
|
|
353
|
+
const term = add(f, '破防', '遇到挫折后沉默')
|
|
354
|
+
for (let budget = 0; budget <= 220; budget++) {
|
|
355
|
+
const turn = inject.injectLexiconTurn({ binding: f.binding(), sessionId: f.id, userTexts: ['遇到挫折后沉默'], tokenBudget: budget })
|
|
356
|
+
assert.ok(estTokens(turn.text) <= budget, `${estTokens(turn.text)} > ${budget}`)
|
|
357
|
+
assert.equal(turn.selected.length, turn.text ? 1 : 0)
|
|
358
|
+
}
|
|
359
|
+
assert.deepEqual(counts(f, term.termId), { candidate: 0, injection: 0, query: 0 })
|
|
360
|
+
assert.equal(lexicon.lexiconOnCooldown(f.id, term.termId), false)
|
|
361
|
+
const accepted = inject.injectLexiconTurn({ binding: f.binding(), sessionId: f.id, userTexts: ['遇到挫折后沉默'], tokenBudget: 800 })
|
|
362
|
+
inject.commitLexiconTurn({ libraryId: f.libraryId, sessionId: f.id, hits: accepted.hits, selected: accepted.selected, turn: 12 })
|
|
363
|
+
assert.deepEqual(counts(f, term.termId), { candidate: 1, injection: 1, query: 0 })
|
|
364
|
+
assert.equal(inject.injectLexiconTurn({ binding: f.binding(), sessionId: f.id, userTexts: ['遇到挫折后沉默'], tokenBudget: 800 }).text, '')
|
|
365
|
+
})
|
|
366
|
+
|
|
367
|
+
test('lexicon anchors fit the complete budget for every cap, with normal and sensitive rows', () => {
|
|
368
|
+
const f = fixture('anchor-budget')
|
|
369
|
+
for (let i = 0; i < 8; i++) add(f, `普通约定${i}`, 'meaning '.repeat(18))
|
|
370
|
+
for (let i = 0; i < 2; i++) add(f, `敏感约定${i}`, 'definition stays private', { sensitivity: 'sensitive' })
|
|
371
|
+
for (let cap = 0; cap <= 300; cap++) {
|
|
372
|
+
const text = inject.buildLexiconAnchor(f.binding(), f.id, cap).text
|
|
373
|
+
assert.ok(estTokens(text) <= cap, `${estTokens(text)} > ${cap}`)
|
|
374
|
+
assert.equal(text.includes('definition stays private'), false)
|
|
375
|
+
}
|
|
376
|
+
})
|
|
377
|
+
|
|
378
|
+
test('an unadmitted lexicon proposal releases shared tokens; accepted retries and duplicate events charge once', async () => {
|
|
379
|
+
const f = fixture('admission-retry')
|
|
380
|
+
state.setSessionBinding(f.id, { anchorPushed: true })
|
|
381
|
+
const term = add(f, '冷茶', 'indium')
|
|
382
|
+
const handlers = new Map()
|
|
383
|
+
const ctx = { on(event, handler) { handlers.set(event, handler); return () => {} }, logger: { warn() {} } }
|
|
384
|
+
const dispose = inject.registerInjection(ctx)
|
|
385
|
+
try {
|
|
386
|
+
const user = { id: 'retry-lexicon-user', role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: 'indium' }] }
|
|
387
|
+
const run = () => inject.injectForStep({ agent: f.agent, decision: { kind: 'enter', messages: [user] },
|
|
388
|
+
turn: 1, step: 1, signal: { aborted: false }, ctx })
|
|
389
|
+
const first = await run()
|
|
390
|
+
assert.ok(first.messages.some(message => message.content.some(block => block.text?.includes(`[lex:${term.termId}]`))))
|
|
391
|
+
assert.ok(inject.injectionTokenDiagnostics(f.id, 1).estimated > 0)
|
|
392
|
+
assert.equal(inject.injectionTokenDiagnostics(f.id, 1).admittedEstimated, 0)
|
|
393
|
+
assert.equal(counts(f, term.termId).candidate, 0)
|
|
394
|
+
await handlers.get('session/event')(f.agent.session, { type: 'turn/end', data: { turn: 1, reason: { kind: 'error' } } })
|
|
395
|
+
assert.equal(inject.injectionTokenDiagnostics(f.id, 1).estimated, 0)
|
|
396
|
+
assert.equal(counts(f, term.termId).injection, 0)
|
|
397
|
+
assert.equal(lexicon.lexiconOnCooldown(f.id, term.termId), false)
|
|
398
|
+
const retry = await run()
|
|
399
|
+
const plugin = retry.messages.filter(message => message.source?.kind === 'plugin:dsh-memu-memory')
|
|
400
|
+
assert.ok(plugin.some(message => message.content.some(block => block.text?.includes(`[lex:${term.termId}]`))))
|
|
401
|
+
for (const message of retry.messages) {
|
|
402
|
+
f.agent.session.messages.push(message)
|
|
403
|
+
await handlers.get('session/event')(f.agent.session, { type: 'user/message', data: message })
|
|
404
|
+
}
|
|
405
|
+
const admitted = inject.injectionTokenDiagnostics(f.id, 1)
|
|
406
|
+
assert.equal(admitted.estimated, admitted.admittedEstimated)
|
|
407
|
+
assert.ok(admitted.estimated <= state.getSettings().injectionTotalTokens)
|
|
408
|
+
assert.deepEqual(counts(f, term.termId), { candidate: 1, injection: 1, query: 0 })
|
|
409
|
+
for (const message of plugin) await handlers.get('session/event')(f.agent.session, { type: 'user/message', data: message })
|
|
410
|
+
assert.equal(inject.injectionTokenDiagnostics(f.id, 1).estimated, admitted.estimated)
|
|
411
|
+
assert.deepEqual(counts(f, term.termId), { candidate: 1, injection: 1, query: 0 })
|
|
412
|
+
await handlers.get('session/event')(f.agent.session, { type: 'turn/end', data: { turn: 1, reason: { kind: 'error' } } })
|
|
413
|
+
assert.equal(inject.injectionTokenDiagnostics(f.id, 1).estimated, admitted.estimated)
|
|
414
|
+
assert.equal(counts(f, term.termId).injection, 1)
|
|
415
|
+
assert.ok(lexicon.lexiconOnCooldown(f.id, term.termId))
|
|
416
|
+
} finally { dispose() }
|
|
417
|
+
})
|
|
418
|
+
|
|
419
|
+
test('two slots are shared by admitted batches in the same host turn, even with different terms', () => {
|
|
420
|
+
const f = fixture('turn-slots')
|
|
421
|
+
for (const [term, meaning] of [['破防', 'tungsten'], ['冷茶', 'tungsten'], ['关窗', 'vanadium']]) add(f, term, meaning)
|
|
422
|
+
const first = inject.injectLexiconTurn({ binding: f.binding(), sessionId: f.id, userTexts: ['tungsten'], tokenBudget: 800, turn: 9 })
|
|
423
|
+
assert.equal(first.selected.length, 2)
|
|
424
|
+
inject.commitLexiconTurn({ libraryId: f.libraryId, sessionId: f.id, ...first, turn: 9 })
|
|
425
|
+
const second = inject.injectLexiconTurn({ binding: f.binding(), sessionId: f.id, userTexts: ['vanadium'], tokenBudget: 800, turn: 9 })
|
|
426
|
+
assert.equal(second.selected.length, 0)
|
|
427
|
+
assert.equal(inject.injectLexiconTurn({ binding: f.binding(), sessionId: f.id, userTexts: ['vanadium'], tokenBudget: 800, turn: 10 }).selected.length, 1)
|
|
428
|
+
})
|
|
429
|
+
|
|
430
|
+
test('native and inbound injection share the nominal total and account only on actual host admission', async () => {
|
|
431
|
+
for (const bridge of [false, true]) {
|
|
432
|
+
const f = fixture(`host-${bridge}`)
|
|
433
|
+
state.updateSettings({ injectionTotalTokens: 550, turnTokens: 240 })
|
|
434
|
+
state.setSessionBinding(f.id, { anchorPushed: true })
|
|
435
|
+
const term = add(f, '破防', '遇到挫折后沉默')
|
|
436
|
+
putMemory(f, 'mem-host-evidence')
|
|
437
|
+
const handlers = new Map()
|
|
438
|
+
const ctx = { on(event, handler) { handlers.set(event, handler); return () => {} }, logger: { warn() {} } }
|
|
439
|
+
const dispose = inject.registerInjection(ctx)
|
|
440
|
+
const user = { id: `u-${f.id}`, role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: '遇到挫折后沉默' }] }
|
|
441
|
+
if (bridge) inbound.ingestInboundBatch({ sessionId: f.id, session: f.agent.session, ctx: null,
|
|
442
|
+
batch: { type: inbound.INBOUND_TYPE, version: 1, producer: 'friend-app', batchId: f.id,
|
|
443
|
+
messages: [{ id: user.id, role: 'user', context: {}, content: user.content }] } })
|
|
444
|
+
const decision = await inject.injectForStep({ agent: f.agent, decision: { kind: 'enter', messages: bridge ? [] : [user] },
|
|
445
|
+
turn: 1, step: 1, signal: { aborted: false }, log() {}, ctx })
|
|
446
|
+
const messages = decision.messages.filter(message => message.source?.kind === 'plugin:dsh-memu-memory')
|
|
447
|
+
const text = messages.map(message => message.content.map(block => block.text || '').join('\n')).join('\n')
|
|
448
|
+
assert.match(text, /<memory-lexicon>/)
|
|
449
|
+
assert.ok(text.includes(`[lex:${term.termId}]`))
|
|
450
|
+
assert.ok(estTokens(text) <= 550)
|
|
451
|
+
assert.equal(counts(f, term.termId).injection, 0)
|
|
452
|
+
for (const message of decision.messages) {
|
|
453
|
+
f.agent.session.messages.push(message)
|
|
454
|
+
await handlers.get('session/event')(f.agent.session, { type: 'user/message', data: message })
|
|
455
|
+
}
|
|
456
|
+
assert.equal(counts(f, term.termId).injection, 1)
|
|
457
|
+
assert.ok(inject.injectionTokenDiagnostics(f.id, 1).estimated <= 550)
|
|
458
|
+
dispose()
|
|
459
|
+
}
|
|
460
|
+
})
|
|
461
|
+
|
|
462
|
+
test('domain RPC filters/counts share single/all aggregation and preserve source library routing', async () => {
|
|
463
|
+
const f = fixture('domains')
|
|
464
|
+
add(f, '私有编码', 'cobalt', { domain: ' CODING ' })
|
|
465
|
+
add(f, '旧词未戳', 'cobalt')
|
|
466
|
+
const archived = add(f, '归档剧情', 'cobalt', { domain: 'rp' })
|
|
467
|
+
lexicon.archiveLexiconTerm({ libraryId: f.libraryId, termId: archived.termId })
|
|
468
|
+
const g = add(lexicon.GLOBAL_LEXICON_ID, '全局编码独有', 'cobalt', { domain: 'coding' })
|
|
469
|
+
const single = await dispatch({}, 'lexiconList', { libraryId: f.libraryId, domain: ' CODING ' })
|
|
470
|
+
assert.equal(single.domain, 'coding')
|
|
471
|
+
assert.deepEqual(single.items.map(item => item.term), ['私有编码'])
|
|
472
|
+
assert.deepEqual(single.domains, ['coding', 'general', 'rp'])
|
|
473
|
+
assert.deepEqual(single.domainCounts, { coding: 1, general: 1, rp: 0 })
|
|
474
|
+
assert.equal(single.counts.term, 1)
|
|
475
|
+
const all = await dispatch({}, 'lexiconList', { libraryId: 'all', domain: 'coding', q: 'cobalt' })
|
|
476
|
+
assert.ok(all.items.every(item => item.domain === 'coding'))
|
|
477
|
+
assert.ok(all.items.some(item => item.id === g.termId && item.libraryId === 'global'))
|
|
478
|
+
assert.ok(all.items.some(item => item.libraryId === f.libraryId))
|
|
479
|
+
const archivedView = await dispatch({}, 'lexiconList', { libraryId: f.libraryId, domain: 'rp', status: 'archived' })
|
|
480
|
+
assert.equal(archivedView.total, 1)
|
|
481
|
+
})
|
|
482
|
+
|
|
483
|
+
test('native admission followed by another inbound batch shares the same two lexicon slots', async () => {
|
|
484
|
+
const f = fixture('host-shared-slots')
|
|
485
|
+
state.setSessionBinding(f.id, { anchorPushed: true })
|
|
486
|
+
for (const [term, meaning] of [['冷茶', 'tungsten'], ['关窗', 'tungsten'], ['熄灯', 'vanadium']]) add(f, term, meaning)
|
|
487
|
+
const handlers = new Map()
|
|
488
|
+
const ctx = { on(event, handler) { handlers.set(event, handler); return () => {} }, logger: { warn() {} } }
|
|
489
|
+
const dispose = inject.registerInjection(ctx)
|
|
490
|
+
const user = { id: 'native-slots', role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: 'tungsten' }] }
|
|
491
|
+
const run = (decision, step) => inject.injectForStep({ agent: f.agent, decision, turn: 1, step,
|
|
492
|
+
signal: { aborted: false }, log() {}, ctx })
|
|
493
|
+
const first = await run({ kind: 'enter', messages: [user] }, 1)
|
|
494
|
+
const textOf = decision => decision.messages.filter(message => message.source?.kind === 'plugin:dsh-memu-memory')
|
|
495
|
+
.map(message => message.content.map(block => block.text || '').join('\n')).join('\n')
|
|
496
|
+
assert.match(textOf(first), /<memory-lexicon>/)
|
|
497
|
+
for (const message of first.messages) {
|
|
498
|
+
f.agent.session.messages.push(message)
|
|
499
|
+
await handlers.get('session/event')(f.agent.session, { type: 'user/message', data: message })
|
|
500
|
+
}
|
|
501
|
+
assert.equal(Object.values(lexicon.loadLexicon(f.libraryId).terms).reduce((n, entry) => n + entry.hitCounts.injection, 0), 2)
|
|
502
|
+
inbound.ingestInboundBatch({ sessionId: f.id, session: f.agent.session, ctx: null,
|
|
503
|
+
batch: { type: inbound.INBOUND_TYPE, version: 1, producer: 'friend-app', batchId: 'after-native',
|
|
504
|
+
messages: [{ id: 'after-native-user', role: 'user', context: {}, content: [{ type: 'text', text: 'vanadium' }] }] } })
|
|
505
|
+
const second = await run({ kind: 'enter', messages: [] }, 2)
|
|
506
|
+
assert.doesNotMatch(textOf(second), /<memory-lexicon>/)
|
|
507
|
+
assert.ok(inject.injectionTokenDiagnostics(f.id, 1).estimated <= 2000)
|
|
508
|
+
dispose()
|
|
509
|
+
})
|
|
510
|
+
|
|
511
|
+
test('cache invalidation observes writes, archives, same-length external replacements and corruption', () => {
|
|
512
|
+
const f = fixture('invalidation')
|
|
513
|
+
const term = add(f, '破防', 'niobium')
|
|
514
|
+
assert.equal(recall(f, 'niobium').lexicon[0].termId, term.termId)
|
|
515
|
+
const before = lexicon.lexiconRecallDiagnostics().invalidations
|
|
516
|
+
add(f, '破防', 'hafnium')
|
|
517
|
+
assert.equal(recall(f, 'niobium').hits.length, 0)
|
|
518
|
+
assert.equal(recall(f, 'hafnium').lexicon[0].termId, term.termId)
|
|
519
|
+
const file = fileFor(f.libraryId)
|
|
520
|
+
const originalStat = fs.statSync(file)
|
|
521
|
+
const raw = fs.readFileSync(file, 'utf8')
|
|
522
|
+
fs.writeFileSync(file, raw.replace('hafnium', 'rhenium'), 'utf8')
|
|
523
|
+
fs.utimesSync(file, originalStat.atime, originalStat.mtime)
|
|
524
|
+
assert.equal(recall(f, 'hafnium').hits.length, 0)
|
|
525
|
+
assert.equal(recall(f, 'rhenium').lexicon[0].termId, term.termId)
|
|
526
|
+
lexicon.archiveLexiconTerm({ libraryId: f.libraryId, termId: term.termId })
|
|
527
|
+
assert.equal(recall(f, 'rhenium').hits.length, 0)
|
|
528
|
+
assert.ok(lexicon.lexiconRecallDiagnostics().invalidations > before)
|
|
529
|
+
fs.writeFileSync(file, '{invalid json')
|
|
530
|
+
assert.throws(() => recall(f, 'rhenium'), error => /^LEXICON_/.test(error.code))
|
|
531
|
+
assert.throws(() => recall(f, 'rhenium'), error => /^LEXICON_/.test(error.code))
|
|
532
|
+
assert.ok(lexicon.lexiconRecallDiagnostics().readFailures >= 2)
|
|
533
|
+
})
|
|
534
|
+
|
|
535
|
+
test('relative data homes use absolute cache identity when the working directory changes', () => {
|
|
536
|
+
const cwd = process.cwd()
|
|
537
|
+
const oldHomes = Object.fromEntries(['DSH_HOME', 'DSH_MEMU_HOME', 'DSH_MEMU_MEMORY_HOME'].map(key => [key, process.env[key]]))
|
|
538
|
+
const roots = ['relative-a', 'relative-b'].map(name => path.join(home, name))
|
|
539
|
+
for (const [i, root] of roots.entries()) {
|
|
540
|
+
const directory = path.join(root, 'relative-home', 'lexicon')
|
|
541
|
+
fs.mkdirSync(directory, { recursive: true })
|
|
542
|
+
paths.writeJson(path.join(directory, 'relative-book.json'), { version: 1, revision: 1, terms: {
|
|
543
|
+
[`lex-relative-${i}`]: { term: `相对约定${i}`, normalizedTerm: `相对约定${i}`, status: 'active', context: {}, meaning: 'copperguard' },
|
|
544
|
+
} })
|
|
545
|
+
}
|
|
546
|
+
const read = () => lexicon.lexiconConceptHits('relative-book', 'copperguard', {}, { scopeKey: 'cwd-isolation' })
|
|
547
|
+
try {
|
|
548
|
+
for (const key of Object.keys(oldHomes)) process.env[key] = 'relative-home'
|
|
549
|
+
process.chdir(roots[0])
|
|
550
|
+
assert.deepEqual(read().map(hit => hit.termId), ['lex-relative-0'])
|
|
551
|
+
process.chdir(roots[1])
|
|
552
|
+
assert.deepEqual(read().map(hit => hit.termId), ['lex-relative-1'])
|
|
553
|
+
const before = lexicon.lexiconRecallDiagnostics()
|
|
554
|
+
process.chdir(roots[0])
|
|
555
|
+
assert.deepEqual(read().map(hit => hit.termId), ['lex-relative-0'])
|
|
556
|
+
assert.equal(lexicon.lexiconRecallDiagnostics().builds, before.builds, 'the first absolute file remains independently cached')
|
|
557
|
+
} finally {
|
|
558
|
+
process.chdir(cwd)
|
|
559
|
+
for (const [key, value] of Object.entries(oldHomes)) {
|
|
560
|
+
if (value === undefined) delete process.env[key]
|
|
561
|
+
else process.env[key] = value
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
})
|
|
565
|
+
|
|
566
|
+
test('the former oversized corpus streams fallback and uses compact persistent postings after a worker build', async () => {
|
|
567
|
+
const f = fixture('oversized-corpus')
|
|
568
|
+
const terms = {}
|
|
569
|
+
for (let i = 0; i < 900; i++) {
|
|
570
|
+
const tokens = Array.from({ length: 220 }, (_, j) => `v${i.toString(36)}x${j.toString(36)}`)
|
|
571
|
+
const term = `大库约定${i}`
|
|
572
|
+
terms[`lex-large-${i}`] = { term, normalizedTerm: lexicon.normalizeLexeme(term), status: 'active', context: {},
|
|
573
|
+
meaning: tokens.slice(0, 60).join(' '), usage: tokens.slice(60, 100).join(' '),
|
|
574
|
+
examples: Array.from({ length: 5 }, (_, j) => tokens.slice(100 + 24 * j, 124 + 24 * j).join(' ')) }
|
|
575
|
+
}
|
|
576
|
+
paths.writeJson(fileFor(f.libraryId), { version: 1, revision: 1, terms })
|
|
577
|
+
const before = lexicon.lexiconRecallDiagnostics()
|
|
578
|
+
const rssBefore = process.memoryUsage().rss
|
|
579
|
+
assert.equal(recall(f, 'v0x0').lexicon[0].termId, 'lex-large-0')
|
|
580
|
+
const first = lexicon.lexiconRecallDiagnostics()
|
|
581
|
+
assert.equal(first.concept.maxBytes, 8 * 1024 * 1024)
|
|
582
|
+
assert.equal(first.index.maxBytes, 64 * 1024 * 1024)
|
|
583
|
+
assert.equal(first.rt.builds, before.rt.builds, 'a synchronous query cannot build persistent postings')
|
|
584
|
+
assert.ok(first.largestConceptBytes < first.concept.maxBytes, 'the old complete corpus is no longer retained')
|
|
585
|
+
const expected = recall(f, 'v0x0').lexicon.map(hit => [hit.termId, hit.score])
|
|
586
|
+
await waitForLexiconRt({ timeoutMs: 60000 })
|
|
587
|
+
const previousMode = process.env.DSH_MEMU_RT_INDEX
|
|
588
|
+
process.env.DSH_MEMU_RT_INDEX = 'on'
|
|
589
|
+
try {
|
|
590
|
+
const indexedBefore = lexicon.lexiconRecallDiagnostics()
|
|
591
|
+
assert.deepEqual(recall(f, 'v0x0').lexicon.map(hit => [hit.termId, hit.score]), expected)
|
|
592
|
+
const indexedAfter = lexicon.lexiconRecallDiagnostics()
|
|
593
|
+
assert.equal(indexedAfter.rt.rtQueries, indexedBefore.rt.rtQueries + 1)
|
|
594
|
+
assert.ok(indexedAfter.rt.postingsVisited - indexedBefore.rt.postingsVisited < 900)
|
|
595
|
+
} finally {
|
|
596
|
+
if (previousMode === undefined) delete process.env.DSH_MEMU_RT_INDEX
|
|
597
|
+
else process.env.DSH_MEMU_RT_INDEX = previousMode
|
|
598
|
+
}
|
|
599
|
+
const second = lexicon.lexiconRecallDiagnostics()
|
|
600
|
+
assert.ok(second.concept.bytes <= second.concept.maxBytes)
|
|
601
|
+
console.info(JSON.stringify({ case: 'lexicon-former-oversized-persistent', rows: 900, tokensPerRow: 220,
|
|
602
|
+
largestViewEstimatedBytes: second.largestConceptBytes,
|
|
603
|
+
derivedCacheEstimatedBytes: second.rt.derivedEstimatedBytes, derivedCacheCapBytes: second.rt.derivedCacheCapBytes,
|
|
604
|
+
truthSnapshotEstimatedBytes: second.index.bytes, truthSnapshotCapBytes: second.index.maxBytes,
|
|
605
|
+
processRssBefore: rssBefore, processRssAfter: process.memoryUsage().rss }))
|
|
606
|
+
})
|
|
607
|
+
|
|
608
|
+
test('failed primary lexicon never becomes a successful empty read or blocks memory results', async () => {
|
|
609
|
+
const f = fixture('fail-open')
|
|
610
|
+
putMemory(f, 'mem-survives')
|
|
611
|
+
add(f, '破防', '遇到挫折后沉默')
|
|
612
|
+
fs.writeFileSync(fileFor(f.libraryId), '{invalid json')
|
|
613
|
+
const warnings = []
|
|
614
|
+
paths.setWarnSink(message => warnings.push(message))
|
|
615
|
+
const result = await memory.privateRecall({ exec: f.exec, query: '遇到挫折后沉默' })
|
|
616
|
+
assert.equal(result.files[0].name, 'mem-survives')
|
|
617
|
+
assert.deepEqual(result.lexicon, [])
|
|
618
|
+
assert.ok(result.lexiconErrors.length)
|
|
619
|
+
assert.match(state.getSessionBinding(f.id).lastRecallError, /lexicon/)
|
|
620
|
+
assert.ok(warnings.some(message => /lexicon/.test(message)))
|
|
621
|
+
paths.setWarnSink(null)
|
|
622
|
+
})
|
|
623
|
+
|
|
624
|
+
test('auxiliary corrupt lexicon reports degradation while preserving a healthy primary hit', () => {
|
|
625
|
+
const f = fixture('aux-primary')
|
|
626
|
+
const peer = fixture('aux-broken')
|
|
627
|
+
const term = add(f, '破防', 'ytterbium')
|
|
628
|
+
add(peer, '坏词', 'ytterbium')
|
|
629
|
+
fs.writeFileSync(fileFor(peer.libraryId), '{invalid json')
|
|
630
|
+
state.updateSettings({ crossLibraryRecall: true })
|
|
631
|
+
const result = recall(f, 'ytterbium')
|
|
632
|
+
assert.equal(result.lexicon[0].termId, term.termId)
|
|
633
|
+
assert.ok(result.errors.some(error => error.includes(peer.libraryId)))
|
|
634
|
+
})
|
|
635
|
+
|
|
636
|
+
test('cooldown storage is bounded even when every session remains active', () => {
|
|
637
|
+
for (let i = 0; i < 540; i++) lexicon.lexiconMarkInjected(`bounded-session-${i}`, [`term-${i}`], Date.now(), { turn: 1 })
|
|
638
|
+
assert.ok(lexicon.lexiconCooldownStore.size <= 512)
|
|
639
|
+
lexicon.lexiconMarkInjected('bounded-many-terms', Array.from({ length: 600 }, (_, i) => `term-${i}`))
|
|
640
|
+
assert.ok(lexicon.lexiconCooldownStore.get('bounded-many-terms').size <= 512)
|
|
641
|
+
})
|