dsh-memu-memory 1.2.7 → 1.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +472 -0
  3. package/README.md +10 -15
  4. package/README.zh.md +10 -15
  5. package/docs/memory-semantics.md +23 -3
  6. package/lib/backup.js +155 -26
  7. package/lib/binding-diagnostics.js +1 -2
  8. package/lib/budget.js +31 -9
  9. package/lib/client.js +221 -128
  10. package/lib/commitment.js +138 -0
  11. package/lib/consolidation-ledger.js +5 -2
  12. package/lib/consolidation-receipt.js +2 -0
  13. package/lib/consolidation-worker.js +3 -0
  14. package/lib/curator-policy.js +23 -0
  15. package/lib/cycle.js +8 -4
  16. package/lib/embedding-download.js +168 -28
  17. package/lib/embedding-runtime.js +76 -17
  18. package/lib/engine.js +0 -6
  19. package/lib/freshness.js +24 -0
  20. package/lib/graph.js +139 -11
  21. package/lib/index.js +71 -20
  22. package/lib/inject.js +167 -17
  23. package/lib/lexicon.js +62 -17
  24. package/lib/local-vector-service.js +25 -2
  25. package/lib/media.js +49 -12
  26. package/lib/memory.js +1202 -123
  27. package/lib/memu.js +4 -0
  28. package/lib/paths.js +0 -7
  29. package/lib/preset-scope.js +6 -1
  30. package/lib/private.js +50 -10
  31. package/lib/prompts/private-consolidation.mixed.md +2 -2
  32. package/lib/prompts/private-consolidation.rp.md +6 -1
  33. package/lib/prompts/private-policy.rp.md +4 -0
  34. package/lib/prompts/system-guide.rp.md +3 -0
  35. package/lib/prompts.js +0 -7
  36. package/lib/recall-cache.js +10 -2
  37. package/lib/rpc.js +104 -19
  38. package/lib/snippet.js +41 -0
  39. package/lib/state.js +109 -30
  40. package/lib/stats.js +2 -2
  41. package/lib/temporal.js +348 -0
  42. package/lib/text-retrieval.js +191 -44
  43. package/lib/text-similarity.js +205 -24
  44. package/lib/tokenizer-v2.js +0 -24
  45. package/lib/tools.js +81 -4
  46. package/lib/vector-migration.js +15 -0
  47. package/lib/vector-profile.js +81 -8
  48. package/lib/visibility.js +0 -4
  49. package/lib/webui/standalone.css +17 -22
  50. package/lib/webui/standalone.js +27 -9
  51. package/lib/webui.js +4 -4
  52. package/package.json +3 -2
  53. package/scripts/acceptance-local.mjs +2 -2
  54. package/scripts/bench-recall.mjs +2 -2
  55. package/scripts/check-all.mjs +3 -1
  56. package/scripts/check-i18n.mjs +35 -1
  57. package/scripts/check-seed-compat.mjs +1 -1
  58. package/scripts/migrate-visibility.mjs +3 -3
  59. package/scripts/prune-sessions.mjs +34 -0
  60. package/scripts/prune-vectors.mjs +24 -0
  61. package/tests/appendix-b.test.mjs +5 -4
  62. package/tests/audit-batch3.test.mjs +247 -0
  63. package/tests/audit-regression.test.mjs +2 -2
  64. package/tests/backup.test.mjs +85 -85
  65. package/tests/browser.test.mjs +6 -1
  66. package/tests/client-render.test.mjs +2 -2
  67. package/tests/commitment.test.mjs +144 -0
  68. package/tests/consolidation-fork.test.mjs +3 -3
  69. package/tests/curator-clusters.test.mjs +18 -0
  70. package/tests/curator-pairing.test.mjs +59 -16
  71. package/tests/disclosure.test.mjs +34 -17
  72. package/tests/dynamic-rrf.test.mjs +22 -19
  73. package/tests/dynamic-threshold.test.mjs +52 -0
  74. package/tests/fact-version.test.mjs +146 -0
  75. package/tests/fixtures/tokenizer-cases.mjs +27 -0
  76. package/tests/graph-cascade.test.mjs +29 -0
  77. package/tests/graph.test.mjs +45 -0
  78. package/tests/help-page.test.mjs +1 -1
  79. package/tests/inject-conflict.test.mjs +112 -0
  80. package/tests/inject-guide.test.mjs +5 -3
  81. package/tests/inject.test.mjs +2 -2
  82. package/tests/injection-intent-budget.test.mjs +92 -0
  83. package/tests/lexical-bm25.test.mjs +171 -0
  84. package/tests/lexicon-frequency.test.mjs +17 -1
  85. package/tests/lexicon-inject.test.mjs +21 -0
  86. package/tests/lexicon-perf.test.mjs +37 -9
  87. package/tests/lexicon-scope.test.mjs +2 -2
  88. package/tests/lexicon-ui.test.mjs +1 -1
  89. package/tests/managed-memory.test.mjs +19 -0
  90. package/tests/memory-chain.test.mjs +140 -0
  91. package/tests/memory-fields.test.mjs +134 -0
  92. package/tests/memu-resident.test.mjs +33 -0
  93. package/tests/ops-hardening.test.mjs +209 -0
  94. package/tests/package-shipping.test.mjs +4 -0
  95. package/tests/prompt-semantics.test.mjs +51 -0
  96. package/tests/query-decompose.test.mjs +62 -0
  97. package/tests/recall-cache.test.mjs +4 -2
  98. package/tests/recall-intent.test.mjs +123 -0
  99. package/tests/slot-similarity.test.mjs +153 -0
  100. package/tests/speaker-provenance.test.mjs +120 -0
  101. package/tests/state-gc.test.mjs +34 -0
  102. package/tests/state.test.mjs +2 -2
  103. package/tests/temporal.test.mjs +124 -0
  104. package/tests/tokenizer-v2.test.mjs +1 -1
  105. package/tests/vector-gc.test.mjs +37 -0
  106. package/tests/webui.test.mjs +27 -0
@@ -0,0 +1,33 @@
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-resident-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const memu = await import('../lib/memu.js')
11
+
12
+ test.after(() => {
13
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
14
+ })
15
+
16
+ test('the resident singleton is declared before its first executable use', () => {
17
+ const source = fs.readFileSync(new URL('../lib/memu.js', import.meta.url), 'utf8')
18
+ const declaration = /^let residentRecord = null$/m.exec(source)
19
+ assert.ok(declaration, 'lib/memu.js must declare `let residentRecord = null`')
20
+ // Comments may mention the name before the declaration; the first executable use
21
+ // (stopResident) must sit after it, or ESM strict mode throws ReferenceError.
22
+ const firstCodeUse = source.indexOf('residentRecord === record')
23
+ assert.ok(firstCodeUse > declaration.index, 'the first executable use must come after the declaration')
24
+ })
25
+
26
+ test('closing and prewarming the resident engine does not throw ReferenceError', async () => {
27
+ assert.equal(typeof memu.closeMemuResident, 'function')
28
+ assert.equal(memu.closeMemuResident(), 0, 'closing a non-existent resident is a no-op')
29
+ assert.equal(memu.closeMemuResident(), 0, 'close is idempotent')
30
+ // Default route is lexical, so prewarm returns false without spawning. The point is
31
+ // that the function body runs and the module-level singleton is reachable.
32
+ assert.equal(await memu.prewarmMemuResident(), false)
33
+ })
@@ -0,0 +1,209 @@
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-ops-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const state = await import('../lib/state.js')
11
+ const memory = await import('../lib/memory.js')
12
+ const activity = await import('../lib/activity-log.js')
13
+ const media = await import('../lib/media.js')
14
+ const { zipSync, unzipSync } = await import('fflate')
15
+ const { dispatch } = await import('../lib/rpc.js')
16
+
17
+ test.after(() => {
18
+ state.flushState()
19
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
20
+ })
21
+
22
+ function session(name) {
23
+ const cwd = path.join(home, 'ws', name)
24
+ state.ensureSession(name, { cwd, agentPreset: 'coding' })
25
+ return {
26
+ libraryId: state.getSessionBinding(name).libraryId,
27
+ exec: { agent: { session: { header: { id: name, cwd, agentPreset: 'coding' } } } },
28
+ }
29
+ }
30
+
31
+ test('permanently deleting a host clears duplicateOf on its copies', async () => {
32
+ const { libraryId, exec } = session('ops-delete')
33
+ const now = new Date().toISOString()
34
+ state.savePrivateIndex(libraryId, {
35
+ entries: {
36
+ 'mem-host': { title: 'host', content: 'host body', status: 'archived', layer: 'long_term', createdAt: now, updatedAt: now },
37
+ 'mem-copy': { title: 'copy', content: 'copy body', status: 'active', layer: 'long_term', createdAt: now, updatedAt: now, duplicateOf: 'mem-host' },
38
+ },
39
+ })
40
+ await memory.privateDelete({ exec, id: 'mem-host' })
41
+ const entries = state.loadPrivateIndex(libraryId).entries
42
+ assert.equal(entries['mem-host'], undefined)
43
+ assert.equal(entries['mem-copy'].duplicateOf, undefined, 'a dangling duplicateOf must not keep the soft penalty')
44
+ assert.equal(entries['mem-copy'].content, 'copy body')
45
+ })
46
+
47
+ test('clearing the activity log requires explicit confirmation', async () => {
48
+ activity.clearEvents()
49
+ activity.record({ kind: 'write', message: 'must survive an unconfirmed clear' })
50
+ await assert.rejects(
51
+ () => dispatch({}, 'clearActivityLog', {}),
52
+ /explicit confirmation/,
53
+ )
54
+ assert.equal(activity.listEvents().length, 1, 'the unconfirmed call must not clear anything')
55
+ await dispatch({}, 'clearActivityLog', { confirmed: true })
56
+ assert.equal(activity.listEvents().length, 0)
57
+ })
58
+
59
+ test('delete preview is read-only and a permanent delete can be restored locally', async () => {
60
+ const { libraryId } = session('ops-delete-restore')
61
+ const now = new Date().toISOString()
62
+ state.savePrivateIndex(libraryId, {
63
+ entries: {
64
+ 'mem-restorable': {
65
+ title: 'restorable', content: 'this body should come back', status: 'archived',
66
+ layer: 'long_term', createdAt: now, updatedAt: now,
67
+ },
68
+ },
69
+ })
70
+ const preview = await dispatch({}, 'deleteMemory', { libraryId, id: 'mem-restorable', preview: true })
71
+ assert.equal(preview.deletable, true)
72
+ assert.equal(preview.plan.deleteFromIndex, true)
73
+ assert.ok(state.loadPrivateIndex(libraryId).entries['mem-restorable'], 'preview must not write')
74
+
75
+ await assert.rejects(
76
+ () => dispatch({}, 'deleteMemory', { libraryId, id: 'mem-restorable' }),
77
+ /explicit confirmation/,
78
+ 'an archived memory still needs consent before it is erased',
79
+ )
80
+ await dispatch({}, 'deleteMemory', { libraryId, id: 'mem-restorable', confirmed: true })
81
+ assert.equal(state.loadPrivateIndex(libraryId).entries['mem-restorable'], undefined)
82
+ const restored = await dispatch({}, 'deleteMemory', { libraryId, id: 'mem-restorable', restore: true })
83
+ assert.equal(restored.entry.content, 'this body should come back')
84
+ assert.equal(restored.entry.status, 'active')
85
+ assert.equal(state.loadPrivateIndex(libraryId).entries['mem-restorable'].content, 'this body should come back')
86
+ await assert.rejects(() => dispatch({}, 'deleteMemory', { libraryId, id: 'mem-nope', restore: true }), /no deleted memory/)
87
+ })
88
+
89
+ test('a memory bundle carries a memories checksum and rejects tampering', () => {
90
+ const { libraryId } = session('ops-bundle')
91
+ const bundle = media.exportMediaBundle(libraryId, {
92
+ bundleId: 'bnd-test',
93
+ memories: [{ title: 'bundle member', content: 'bundle member body' }],
94
+ graph: null,
95
+ lexicon: null,
96
+ })
97
+ const files = unzipSync(bundle)
98
+ const manifest = JSON.parse(Buffer.from(files['manifest.json']).toString('utf8'))
99
+ assert.equal(manifest.bundleId, 'bnd-test')
100
+ assert.match(manifest.memoriesSha256, /^[0-9a-f]{64}$/)
101
+ const imported = media.importMediaBundle(libraryId, bundle)
102
+ assert.equal(imported.bundleId, 'bnd-test')
103
+
104
+ files['memories.json'] = Buffer.from(JSON.stringify({ bundleId: 'bnd-test', memories: [{ title: 'tampered', content: 'tampered' }] }))
105
+ const tampered = Buffer.from(zipSync(files, { level: 0 }))
106
+ assert.throws(() => media.importMediaBundle(libraryId, tampered), /memories\.json checksum mismatch/)
107
+ })
108
+
109
+ test('an import batch can be reverted without touching earlier memories', async () => {
110
+ const { libraryId } = session('ops-revert')
111
+ const now = new Date().toISOString()
112
+ state.savePrivateIndex(libraryId, {
113
+ entries: { 'mem-before': { title: 'before', content: 'before body', status: 'active', layer: 'long_term', createdAt: now, updatedAt: now } },
114
+ })
115
+ const imported = await dispatch({}, 'importMemories', {
116
+ libraryId,
117
+ bundleId: 'bnd-revert',
118
+ memories: [{ title: 'bundle fact', content: 'this fact came from a bundle' }],
119
+ })
120
+ assert.equal(imported.importBatchId, 'bnd-revert')
121
+ let entries = state.loadPrivateIndex(libraryId).entries
122
+ assert.ok(Object.values(entries).some((entry) => entry.importedBundle === 'bnd-revert'))
123
+ const reverted = await dispatch({}, 'importMemories', { libraryId, revertBatchId: 'bnd-revert' })
124
+ assert.equal(reverted.removed, 1)
125
+ entries = state.loadPrivateIndex(libraryId).entries
126
+ assert.equal(entries['mem-before'].content, 'before body')
127
+ assert.ok(!Object.values(entries).some((entry) => entry.importedBundle === 'bnd-revert'))
128
+ })
129
+
130
+
131
+ function bundleWithManifest(files, manifest) {
132
+ return Buffer.from(zipSync({ ...files, 'manifest.json': Buffer.from(JSON.stringify(manifest)) }, { level: 0 }))
133
+ }
134
+
135
+ test('a v2 bundle rejects a removed, malformed or forged checksum', () => {
136
+ const { libraryId } = session('ops-bundle-integrity')
137
+ const files = unzipSync(media.exportMediaBundle(libraryId, {
138
+ bundleId: 'bnd-integrity', memories: [{ title: 'kept', content: 'kept body' }], graph: null, lexicon: null,
139
+ }))
140
+ const manifest = JSON.parse(Buffer.from(files['manifest.json']).toString('utf8'))
141
+ assert.equal(manifest.format, 'dsh-memu-memory-media@2')
142
+ assert.equal(media.importMediaBundle(libraryId, bundleWithManifest(files, manifest)).memories.length, 1)
143
+
144
+ const removed = { ...manifest }
145
+ delete removed.memoriesSha256
146
+ assert.throws(() => media.importMediaBundle(libraryId, bundleWithManifest(files, removed)), /checksum missing/)
147
+ assert.throws(() => media.importMediaBundle(libraryId, bundleWithManifest(files, { ...manifest, memoriesSha256: 'nope' })), /checksum is malformed/)
148
+ assert.throws(() => media.importMediaBundle(libraryId, bundleWithManifest(files, { ...manifest, memoriesSha256: '0'.repeat(64) })), /checksum mismatch/)
149
+ })
150
+
151
+ test('legacy v1 archives without a checksum stay importable', () => {
152
+ const { libraryId } = session('ops-bundle-legacy')
153
+ const archive = Buffer.from(zipSync({
154
+ 'memories.json': Buffer.from(JSON.stringify({ memories: [{ title: 'legacy', content: 'legacy body' }] })),
155
+ 'manifest.json': Buffer.from(JSON.stringify({ format: 'dsh-memu-media@1', blobs: {} })),
156
+ }, { level: 0 }))
157
+ assert.equal(media.importMediaBundle(libraryId, archive).memories.length, 1)
158
+ })
159
+
160
+ test('streaming imports enforce the same checksum rule', async () => {
161
+ const { Readable } = await import('node:stream')
162
+ const { libraryId } = session('ops-bundle-stream')
163
+ const files = unzipSync(media.exportMediaBundle(libraryId, {
164
+ bundleId: 'bnd-stream', memories: [{ title: 'streamed', content: 'streamed body' }], graph: null, lexicon: null,
165
+ }))
166
+ const manifest = JSON.parse(Buffer.from(files['manifest.json']).toString('utf8'))
167
+ delete manifest.memoriesSha256
168
+ await assert.rejects(
169
+ media.importMediaStream(libraryId, Readable.from([bundleWithManifest(files, manifest)])),
170
+ /checksum missing/,
171
+ )
172
+ })
173
+
174
+ test('a corrupt manifest is reported as an invalid archive, not a raw SyntaxError', () => {
175
+ const { libraryId } = session('ops-bundle-corrupt')
176
+ const archive = Buffer.from(zipSync({
177
+ 'memories.json': Buffer.from('{ not json'),
178
+ 'manifest.json': Buffer.from('{ not json'),
179
+ }, { level: 0 }))
180
+ assert.throws(() => media.importMediaBundle(libraryId, archive), /invalid memory archive/)
181
+ })
182
+
183
+ test('an expired delete stash cannot be restored, is swept and never enters a backup', async () => {
184
+ const { indexDir, writeJson } = await import('../lib/paths.js')
185
+ const { libraryId, exec } = session('ops-delete-ttl')
186
+ const now = new Date().toISOString()
187
+ state.savePrivateIndex(libraryId, {
188
+ entries: { 'mem-expired': { title: 'gone', content: 'PERMANENTLY-DELETED-BODY', status: 'archived', layer: 'long_term', createdAt: now, updatedAt: now } },
189
+ })
190
+ await memory.privateDelete({ exec, id: 'mem-expired' })
191
+ const stashPath = path.join(indexDir(), `${libraryId}.deleted.json`)
192
+ const stash = JSON.parse(fs.readFileSync(stashPath, 'utf8'))
193
+ assert.ok(stash.items['mem-expired'], 'a fresh delete is still restorable')
194
+ stash.items['mem-expired'].deletedAt = new Date(Date.now() - 8 * 24 * 60 * 60 * 1000).toISOString()
195
+ writeJson(stashPath, stash)
196
+ await assert.rejects(() => memory.restoreDeleted({ libraryId, id: 'mem-expired' }), /no deleted memory/)
197
+
198
+ const swept = memory.pruneDeletedStores()
199
+ assert.ok(swept.removed >= 1, 'the startup sweep must drop expired stash entries')
200
+ assert.ok(!JSON.parse(fs.readFileSync(stashPath, 'utf8')).items['mem-expired'])
201
+
202
+ const dest = await state.backupDatabases()
203
+ const manifest = JSON.parse(fs.readFileSync(path.join(dest, 'manifest.json'), 'utf8'))
204
+ assert.deepEqual(
205
+ Object.keys(manifest.files).filter(rel => rel.endsWith('.deleted.json')),
206
+ [],
207
+ 'permanently deleted bodies must not leak into a backup',
208
+ )
209
+ })
@@ -43,6 +43,10 @@ function runCheckAll(root) {
43
43
  test('package.json ships tests/ so the packaged suite is not silently empty', () => {
44
44
  assert.ok(Array.isArray(pkg.files), 'package.json needs a files whitelist')
45
45
  assert.ok(pkg.files.includes('tests'), 'files must include "tests" or npm test finds 0 test files')
46
+ // G-1 in the packaged acceptance suite reads CHANGELOG.md. If it does not ship,
47
+ // the installed package reports a 49/50 acceptance run while the repo is 50/50.
48
+ assert.ok(pkg.files.includes('CHANGELOG.md'), 'files must include "CHANGELOG.md" for packaged acceptance G-1')
49
+ assert.equal(new Set(pkg.files).size, pkg.files.length, 'files must not contain duplicate entries')
46
50
  // The suite is only runnable if its harness (loader + stubs) travels with it.
47
51
  for (const rel of ['loader-register.mjs', 'loader.mjs', 'stubs/dsh-llm.js']) {
48
52
  assert.ok(fs.existsSync(path.join(REPO, 'tests', rel)), 'tests/' + rel + ' must ship with the package')
@@ -0,0 +1,51 @@
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-prompt-128-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const prompts = await import('../lib/prompts.js')
11
+ const { buildWorkerBrief } = await import('../lib/consolidation-worker.js')
12
+
13
+ test.after(() => {
14
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
15
+ })
16
+
17
+ const policyVars = { shortTermTtlHours: 72, mustRememberCap: 12, unpinBudget: 2, anchorTokens: 800 }
18
+ const guideVars = { mustRememberCap: 12, unpinBudget: 2, shortTermTtlHours: 72, anchorTokens: 800, turnTokens: 800 }
19
+
20
+ test('the RP guide asks for scene-time dates, two versions and speaker separation', () => {
21
+ const text = prompts.loadPromptForDomain('system-guide', guideVars, 'rp').text
22
+ assert.match(text, /相对日期先按这一轮的时间换算/)
23
+ assert.match(text, /记忆里有两版说法时/)
24
+ assert.match(text, /分清是谁说的/)
25
+ })
26
+
27
+ test('the RP policy teaches the S1–S4 write fields', () => {
28
+ const text = prompts.loadPromptForDomain('private-policy', policyVars, 'rp').text
29
+ assert.match(text, /absolute_date/)
30
+ assert.match(text, /date_precision=unknown/)
31
+ assert.match(text, /conflicts_with/)
32
+ assert.match(text, /supersedes/)
33
+ assert.match(text, /commitment/)
34
+ assert.match(text, /assistant_said/)
35
+ })
36
+
37
+ test('the consolidation page and worker brief carry the same field contract', () => {
38
+ const text = prompts.loadPromptForDomain('private-consolidation', {
39
+ libraryName: '测试库', domain: 'rp', mustRememberCap: 12,
40
+ }, 'rp').text
41
+ for (const needle of ['speaker_id', 'source_kind', 'absolute_date', 'conflicts_with', 'commitment']) {
42
+ assert.ok(text.includes(needle), `consolidation prompt is missing ${needle}`)
43
+ }
44
+ const brief = buildWorkerBrief({
45
+ snapshot: { fromSeq: 1, throughSeq: 2, eventCount: 2, hash: 'prompt-128' },
46
+ probe: { tools: ['memu_private_remember', 'memu_private_update'] },
47
+ })
48
+ for (const needle of ['speaker_id', 'source_kind', 'absolute_date', 'conflicts_with', 'supersedes', 'commitment', 'assistant_said', '每窗最多新增 10 条']) {
49
+ assert.ok(brief.includes(needle), `worker brief is missing ${needle}`)
50
+ }
51
+ })
@@ -0,0 +1,62 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import { detectQueryIntent, decomposeQuery, extractQueryEntities } from '../lib/text-retrieval.js'
5
+ import { intentTopK, recallIntentBudget, RECALL_INTENT_TOPK } from '../lib/budget.js'
6
+
7
+ const NOW = new Date('2026-11-06T04:00:00Z')
8
+
9
+ test('intent detection covers the six recall strategies', () => {
10
+ assert.equal(detectQueryIntent('我们上次说的地板颜色到底哪个对'), 'conflict')
11
+ assert.equal(detectQueryIntent('你答应过我什么时候查机票'), 'commitment')
12
+ assert.equal(detectQueryIntent('那件事你别告诉别人'), 'boundary')
13
+ assert.equal(detectQueryIntent('下周三是几号'), 'date')
14
+ assert.equal(detectQueryIntent('今天有什么安排'), 'date')
15
+ assert.equal(detectQueryIntent('"林眠"住在哪里'), 'entity')
16
+ assert.equal(detectQueryIntent('窗外的雨停了'), 'general')
17
+ assert.equal(detectQueryIntent(''), 'general')
18
+ })
19
+
20
+ test('queries are decomposed into dates, entities and an expanded search string', () => {
21
+ const decomposed = decomposeQuery('下周三跟"林眠"约了几点', null, {
22
+ now: NOW, knownEntities: ['林眠', 'Yuike'],
23
+ })
24
+ assert.equal(decomposed.intent, 'date', 'a time word outranks the quoted entity')
25
+ assert.deepEqual(decomposed.dates, ['2026-11-11'])
26
+ assert.deepEqual(decomposed.entities, ['林眠'])
27
+ assert.match(decomposed.expanded, /2026-11-11/)
28
+ assert.match(decomposed.expanded, /林眠/)
29
+
30
+ const named = decomposeQuery('Yuike 上次提到的地点', null, { now: NOW, knownEntities: ['Yuike', '林眠'] })
31
+ assert.equal(named.intent, 'date', '上次 makes this a time question')
32
+ assert.deepEqual(named.entities, ['Yuike'])
33
+
34
+ const entity = decomposeQuery('"林眠"住在哪里', null, { now: NOW })
35
+ assert.equal(entity.intent, 'entity')
36
+ assert.deepEqual(entity.entities, ['林眠'])
37
+
38
+ assert.deepEqual(decomposeQuery('').dates, [])
39
+ assert.deepEqual(decomposeQuery('', null, { now: NOW }).entities, [])
40
+ })
41
+
42
+ test('entity extraction only trusts explicit markers or a known-entity table', () => {
43
+ assert.deepEqual(extractQueryEntities('“Yuike”和「林眠」都在'), ['Yuike', '林眠'])
44
+ assert.deepEqual(extractQueryEntities('@yuike 说了什么'), ['yuike'])
45
+ assert.deepEqual(extractQueryEntities('Yuike 说了什么', { knownEntities: ['Yuike'] }), ['Yuike'])
46
+ assert.deepEqual(extractQueryEntities('一个普通句子'), [])
47
+ assert.deepEqual(extractQueryEntities('“x”'), [], 'one character is not an entity handle')
48
+ })
49
+
50
+ test('intent budgets raise the candidate count without overriding a larger explicit topK', () => {
51
+ assert.deepEqual(RECALL_INTENT_TOPK, { general: 5, date: 8, entity: 8, conflict: 6, commitment: 5, boundary: 5 })
52
+ assert.equal(intentTopK('general', 3), 3)
53
+ assert.equal(intentTopK('general', 0), 5)
54
+ assert.equal(intentTopK('date', 3), 8)
55
+ assert.equal(intentTopK('entity', 5), 8)
56
+ assert.equal(intentTopK('conflict', 5), 6)
57
+ assert.equal(intentTopK('date', 10), 10, 'a deliberate larger request is kept')
58
+ assert.equal(intentTopK('date', 50), 20, 'but never unbounded')
59
+ assert.equal(intentTopK('unknown', 4), 4)
60
+ assert.deepEqual(recallIntentBudget('conflict', { privateTopK: 4 }), { intent: 'conflict', topK: 6 })
61
+ assert.deepEqual(recallIntentBudget('nope', { privateTopK: 2 }), { intent: 'general', topK: 2 })
62
+ })
@@ -34,7 +34,7 @@ const hooks = registerHooks({
34
34
  },
35
35
  })
36
36
 
37
- const { createRecallCache, recallCache, recallCacheKey } = await import('../lib/recall-cache.js')
37
+ const { createRecallCache, recallCache, recallCacheKey, recallCacheStats } = await import('../lib/recall-cache.js')
38
38
  const state = await import('../lib/state.js')
39
39
  const vp = await import('../lib/vector-profile.js')
40
40
  const paths = await import('../lib/paths.js')
@@ -65,6 +65,7 @@ test('TTL 过期:注入假时钟,到点即失效并计逐出', () => {
65
65
  now = 1_100
66
66
  assert.equal(cache.get('k'), null, 'now >= 存入时刻+ttl 即过期')
67
67
  assert.equal(cache.stats().evictions, 1, '过期即逐出')
68
+ assert.equal(cache.stats().staleSkipped, 1, '过期同时计为 staleSkipped')
68
69
  assert.equal(cache.stats().misses, 1)
69
70
  })
70
71
 
@@ -177,7 +178,8 @@ test('模块级单例存在且具备全部公开方法', () => {
177
178
  assert.equal(typeof recallCache[method], 'function', method)
178
179
  }
179
180
  assert.deepEqual(Object.keys(recallCache.stats()).sort(),
180
- ['errors', 'evictions', 'generations', 'hits', 'inflight', 'lastError', 'misses', 'size'])
181
+ ['errors', 'evictions', 'generations', 'hits', 'inflight', 'lastError', 'misses', 'size', 'staleSkipped'])
182
+ assert.deepEqual(recallCacheStats(), recallCache.stats(), 'the stats reader is a snapshot of the singleton')
181
183
  })
182
184
 
183
185
  // ---------------------------------------------------------------- 接线部分
@@ -0,0 +1,123 @@
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-recall-intent-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const state = await import('../lib/state.js')
11
+ const memory = await import('../lib/memory.js')
12
+
13
+ test.after(() => {
14
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
15
+ })
16
+
17
+ let seq = 0
18
+ function session(name) {
19
+ seq += 1
20
+ const cwd = path.join(home, 'ws', `${name}-${seq}`)
21
+ const sessionId = `${name}-${seq}`
22
+ state.ensureSession(sessionId, { cwd, agentPreset: 'rp' })
23
+ return {
24
+ sessionId,
25
+ exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'rp' } } } },
26
+ }
27
+ }
28
+
29
+ test('a date question raises the candidate count; a general question keeps the requested topK', async () => {
30
+ const { exec } = session('intent-topk')
31
+ const topics = ['灯光', '投影仪', '白板', '咖啡机', '门禁', '椅子', '窗帘', '空调', '插座', '网络', '打印纸', '绿植']
32
+ for (const [index, topic] of topics.entries()) {
33
+ await memory.privateRemember({
34
+ exec,
35
+ title: `会议记录 ${index + 1}`,
36
+ content: `会议室第 ${index + 1} 项:${topic}的情况需要跟进。`,
37
+ absoluteDate: `2026-11-${String(index + 1).padStart(2, '0')}`,
38
+ })
39
+ }
40
+ const general = await memory.privateRecall({ exec, query: '会议', topK: 3, relevanceThreshold: 0 })
41
+ assert.equal(general.files.length, 3, 'general respects the requested three')
42
+
43
+ const dated = await memory.privateRecall({ exec, query: '会议什么时候开', topK: 3, relevanceThreshold: 0 })
44
+ assert.ok(dated.files.length > general.files.length, 'a date question asks for a bigger timeline')
45
+ assert.ok(dated.files.length <= 8)
46
+ })
47
+
48
+ test('one-hop expansion follows an explicit link to a memory the query never matched', async () => {
49
+ const { exec, sessionId } = session('intent-multihop')
50
+ const a = await memory.privateRemember({
51
+ exec, title: '林眠去了码头', content: '林眠傍晚一个人去了码头。',
52
+ })
53
+ const b = await memory.privateRemember({
54
+ exec, title: '她带了一把旧伞', content: '那天她带着一把旧伞。',
55
+ })
56
+ const binding = state.getSessionBinding(sessionId)
57
+ state.updatePrivateIndex(binding.libraryId, (index) => {
58
+ index.entries[a.id].links = [{ to: b.id, kind: 'event', note: 'same evening', confidence: 0.9 }]
59
+ index.entries[b.id].links = [{ to: a.id, kind: 'event', note: 'same evening', confidence: 0.9 }]
60
+ })
61
+
62
+ const recalled = await memory.privateRecall({ exec, query: '林眠到码头', topK: 2, relevanceThreshold: 0 })
63
+ const ids = recalled.files.map((file) => file.name)
64
+ assert.ok(ids.includes(a.id), 'the direct hit is recalled')
65
+ assert.ok(ids.includes(b.id), 'the linked clue rides along one hop')
66
+ assert.deepEqual(recalled.expanded, [{ from: a.id, to: b.id, kind: 'event' }])
67
+ assert.ok(recalled.files.find((file) => file.name === b.id).relatedTo === a.id)
68
+ })
69
+
70
+ test('graph expansion only fills empty topK seats, never adds injected entries', async () => {
71
+ const { exec, sessionId } = session('intent-multihop-budget')
72
+ const a = await memory.privateRemember({
73
+ exec, title: '码头灯塔记录', content: '林眠傍晚去了码头看灯塔。',
74
+ })
75
+ const b = await memory.privateRemember({
76
+ exec, title: '灯塔亮起时间', content: '码头边的灯塔亮了三次。',
77
+ })
78
+ const linked = await memory.privateRemember({
79
+ exec, title: '她带了一把旧伞', content: '那天她带着一把旧伞。',
80
+ })
81
+ const binding = state.getSessionBinding(sessionId)
82
+ state.updatePrivateIndex(binding.libraryId, (index) => {
83
+ index.entries[a.id].links = [{ to: linked.id, kind: 'event', note: 'same evening', confidence: 0.9 }]
84
+ })
85
+ const recalled = await memory.privateRecall({ exec, query: '码头 灯塔', topK: 2, relevanceThreshold: 0 })
86
+ const ids = recalled.files.map((file) => file.name)
87
+ assert.equal(recalled.files.length, 2, 'topK seats stay full; expansion cannot add a third')
88
+ assert.ok(ids.includes(a.id) && ids.includes(b.id))
89
+ assert.ok(!ids.includes(linked.id), 'the linked memory must wait until a seat is free')
90
+ assert.equal(recalled.expanded, undefined)
91
+ })
92
+
93
+ test('automatic recall hides never_say and only_if_asked; boundary questions release only_if_asked', async () => {
94
+ const { exec } = session('intent-disclosure')
95
+ const open = await memory.privateRemember({
96
+ exec, title: '账本放在书房', content: '账本放在书房第二个抽屉。',
97
+ })
98
+ const ask = await memory.privateRemember({
99
+ exec, title: '账本记着一笔旧账', content: '账本里记着一笔他不愿提的旧账。', disclosure: 'only_if_asked',
100
+ })
101
+ const never = await memory.privateRemember({
102
+ exec, title: '账本的真正来历', content: '账本其实是他父亲留下的。', disclosure: 'never_say',
103
+ })
104
+
105
+ const automatic = await memory.privateRecall({
106
+ exec, query: '账本', topK: 10, relevanceThreshold: 0, purpose: 'automatic',
107
+ })
108
+ const autoIds = automatic.files.map((file) => file.name)
109
+ assert.ok(autoIds.includes(open.id))
110
+ assert.ok(!autoIds.includes(ask.id), 'only_if_asked waits for a direct question')
111
+ assert.ok(!autoIds.includes(never.id), 'never_say never auto-surfaces')
112
+
113
+ const explicit = await memory.privateRecall({ exec, query: '账本', topK: 10, relevanceThreshold: 0 })
114
+ const explicitIds = explicit.files.map((file) => file.name)
115
+ assert.ok(explicitIds.includes(ask.id) && explicitIds.includes(never.id), 'an explicit recall may still read them')
116
+
117
+ const boundary = await memory.privateRecall({
118
+ exec, query: '账本的秘密是什么', topK: 10, relevanceThreshold: 0, purpose: 'automatic',
119
+ })
120
+ const boundaryIds = boundary.files.map((file) => file.name)
121
+ assert.ok(boundaryIds.includes(ask.id), 'a boundary question is the "asked" case')
122
+ assert.ok(!boundaryIds.includes(never.id), 'never_say stays out even then')
123
+ })