dsh-memu-memory 1.2.6 → 1.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +1 -1
- package/README.md +10 -15
- package/README.zh.md +10 -15
- package/docs/contributing.md +1 -1
- package/docs/host-adaptation.md +1 -1
- package/docs/memory-semantics.md +26 -4
- package/docs/troubleshooting.md +3 -1
- package/lib/backup.js +1 -1
- package/lib/binding-diagnostics.js +2 -2
- package/lib/budget.js +31 -0
- package/lib/client.js +276 -28
- package/lib/commitment.js +138 -0
- package/lib/consolidation-receipt.js +2 -0
- package/lib/consolidation-worker.js +3 -0
- package/lib/curator-policy.js +98 -0
- package/lib/fork-model.js +312 -0
- package/lib/freshness.js +24 -0
- package/lib/inject.js +117 -10
- package/lib/lexicon.js +1 -1
- package/lib/local-vector-service.js +4 -1
- package/lib/memory.js +600 -43
- package/lib/memu.js +4 -0
- package/lib/private.js +49 -8
- package/lib/prompts/private-consolidation.mixed.md +3 -2
- package/lib/prompts/private-consolidation.rp.md +7 -1
- package/lib/prompts/private-policy.mixed.md +1 -0
- package/lib/prompts/private-policy.rp.md +5 -1
- package/lib/prompts/system-guide.rp.md +3 -0
- package/lib/recall-cache.js +212 -0
- package/lib/rpc.js +44 -6
- package/lib/snippet.js +25 -0
- package/lib/state.js +43 -1
- package/lib/temporal.js +329 -0
- package/lib/text-retrieval.js +292 -28
- package/lib/tokenizer-v2.js +295 -0
- package/lib/tools.js +81 -4
- package/lib/webui/standalone.css +17 -1
- package/package.json +1 -1
- package/scripts/bench-recall.mjs +142 -0
- package/scripts/check-seed-compat.mjs +118 -0
- package/tests/backup.test.mjs +2 -2
- package/tests/commitment.test.mjs +144 -0
- package/tests/consolidation-fork.test.mjs +122 -5
- package/tests/curator-clusters.test.mjs +7 -1
- package/tests/curator-pairing.test.mjs +52 -8
- package/tests/disclosure.test.mjs +34 -17
- package/tests/dynamic-rrf.test.mjs +179 -0
- package/tests/fact-version.test.mjs +128 -0
- package/tests/fork-model.test.mjs +345 -0
- package/tests/help-page.test.mjs +1 -1
- package/tests/inject-conflict.test.mjs +94 -0
- package/tests/inject-guide.test.mjs +5 -3
- package/tests/inject.test.mjs +2 -2
- package/tests/injection-intent-budget.test.mjs +92 -0
- package/tests/lexicon-frequency.test.mjs +1 -1
- package/tests/loader.mjs +3 -0
- package/tests/memory-chain.test.mjs +140 -0
- package/tests/memory-fields.test.mjs +134 -0
- package/tests/memu-resident.test.mjs +33 -0
- package/tests/negation-polarity.test.mjs +135 -0
- package/tests/prompt-semantics.test.mjs +51 -0
- package/tests/query-decompose.test.mjs +62 -0
- package/tests/recall-cache.test.mjs +292 -0
- package/tests/recall-intent.test.mjs +100 -0
- package/tests/speaker-provenance.test.mjs +120 -0
- package/tests/stubs/dsh-llm-pi-ai.js +13 -0
- package/tests/temporal.test.mjs +124 -0
- package/tests/tokenizer-v2.test.mjs +142 -0
|
@@ -0,0 +1,292 @@
|
|
|
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
|
+
import { registerHooks } from 'node:module'
|
|
7
|
+
|
|
8
|
+
// P1-1 召回缓存测试。两部分:
|
|
9
|
+
// 1) 纯单元:lib/recall-cache.js 的 LRU/TTL/代数/wrap 去重/fail-open/键规范化;
|
|
10
|
+
// 2) 接线:managedRecall 的缓存命中、写路径失效、local-fallback 不缓存。
|
|
11
|
+
// managedRecall 不是导出函数,接线行为从导出入口 privateRecall(purpose:
|
|
12
|
+
// 'automatic',不触发 touchAccess 写)覆盖,mock 手法仿 tests/managed-memory.test.mjs:
|
|
13
|
+
// 在导入任何生产模块前用 registerHooks 把 ./memu.js 换成内存桥。
|
|
14
|
+
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-recall-cache-'))
|
|
15
|
+
process.env.DSH_MEMU_HOME = home
|
|
16
|
+
process.env.DSH_MEMU_MEMORY_HOME = home
|
|
17
|
+
|
|
18
|
+
const calls = []
|
|
19
|
+
const warnings = []
|
|
20
|
+
globalThis.__recallCacheTest = {
|
|
21
|
+
async commit(args) { calls.push({ op: 'commit', ...args }); return { ok: true } },
|
|
22
|
+
async retrieve(args) { calls.push({ op: 'retrieve', ...args }); return retrieveHook(args) },
|
|
23
|
+
async forget(args) { calls.push({ op: 'forget', ...args }); return { deleted: 1, segments: 1 } },
|
|
24
|
+
async listFiles() { return { recall_files: [], resources: [], raw: null } },
|
|
25
|
+
}
|
|
26
|
+
let retrieveHook = () => ({ files: [], segments: [], resources: [], raw: null })
|
|
27
|
+
const engineSource = 'const bridge = globalThis.__recallCacheTest; export const commit = bridge.commit, retrieve = bridge.retrieve, forget = bridge.forget, listFiles = bridge.listFiles, closeMemuResident = () => 0, prewarmMemuResident = async () => false;'
|
|
28
|
+
const hooks = registerHooks({
|
|
29
|
+
resolve(specifier, context, nextResolve) {
|
|
30
|
+
if (specifier === './memu.js') {
|
|
31
|
+
return { url: 'data:text/javascript,' + encodeURIComponent(engineSource), shortCircuit: true }
|
|
32
|
+
}
|
|
33
|
+
return nextResolve(specifier, context)
|
|
34
|
+
},
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
const { createRecallCache, recallCache, recallCacheKey, recallCacheStats } = await import('../lib/recall-cache.js')
|
|
38
|
+
const state = await import('../lib/state.js')
|
|
39
|
+
const vp = await import('../lib/vector-profile.js')
|
|
40
|
+
const paths = await import('../lib/paths.js')
|
|
41
|
+
const memory = await import('../lib/memory.js')
|
|
42
|
+
|
|
43
|
+
// ---------------------------------------------------------------- 纯单元部分
|
|
44
|
+
|
|
45
|
+
test('LRU 容量驱逐:max=2 放 3 个,最旧(未刷新)的先被逐', () => {
|
|
46
|
+
const cache = createRecallCache({ max: 2 })
|
|
47
|
+
cache.set('a', { v: 'a' })
|
|
48
|
+
cache.set('b', { v: 'b' })
|
|
49
|
+
assert.deepEqual(cache.get('a'), { v: 'a' }, '命中把 a 刷成最新')
|
|
50
|
+
cache.set('c', { v: 'c' })
|
|
51
|
+
assert.equal(cache.get('b'), null, 'b 是最旧的,被驱逐')
|
|
52
|
+
assert.deepEqual(cache.get('c'), { v: 'c' })
|
|
53
|
+
assert.deepEqual(cache.get('a'), { v: 'a' })
|
|
54
|
+
const stats = cache.stats()
|
|
55
|
+
assert.equal(stats.size, 2)
|
|
56
|
+
assert.equal(stats.evictions, 1)
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
test('TTL 过期:注入假时钟,到点即失效并计逐出', () => {
|
|
60
|
+
let now = 1_000
|
|
61
|
+
const cache = createRecallCache({ ttlMs: 100, now: () => now })
|
|
62
|
+
cache.set('k', { v: 1 })
|
|
63
|
+
now = 1_099
|
|
64
|
+
assert.deepEqual(cache.get('k'), { v: 1 }, '到期前一刻仍有效')
|
|
65
|
+
now = 1_100
|
|
66
|
+
assert.equal(cache.get('k'), null, 'now >= 存入时刻+ttl 即过期')
|
|
67
|
+
assert.equal(cache.stats().evictions, 1, '过期即逐出')
|
|
68
|
+
assert.equal(cache.stats().staleSkipped, 1, '过期同时计为 staleSkipped')
|
|
69
|
+
assert.equal(cache.stats().misses, 1)
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
test('bumpGeneration:旧键立即失联;在途 producer 落回旧代,不污染新代', async () => {
|
|
73
|
+
const cache = createRecallCache()
|
|
74
|
+
cache.set('k', { v: 'old' })
|
|
75
|
+
cache.bumpGeneration()
|
|
76
|
+
assert.equal(cache.get('k'), null, 'bump 后旧键立即失联')
|
|
77
|
+
assert.equal(cache.stats().generations, 1)
|
|
78
|
+
|
|
79
|
+
let release
|
|
80
|
+
const gate = new Promise((resolve) => { release = resolve })
|
|
81
|
+
let runs = 0
|
|
82
|
+
const inflight = cache.wrap('k', async () => { runs += 1; await gate; return { v: 'in-flight' } })
|
|
83
|
+
cache.bumpGeneration()
|
|
84
|
+
release()
|
|
85
|
+
assert.deepEqual(await inflight, { v: 'in-flight' }, '在途请求照常拿到自己的结果')
|
|
86
|
+
assert.equal(cache.get('k'), null, '旧代落地的结果在新代不可见')
|
|
87
|
+
let secondRuns = 0
|
|
88
|
+
const fresh = await cache.wrap('k', async () => { secondRuns += 1; return { v: 'fresh' } })
|
|
89
|
+
assert.deepEqual(fresh, { v: 'fresh' }, '新代重新计算,绝不命中旧值')
|
|
90
|
+
assert.equal(runs + secondRuns, 2, '旧代结果没有回流成新代缓存')
|
|
91
|
+
cache.bumpGeneration()
|
|
92
|
+
assert.equal(cache.stats().size, 0, '下一次 bump 把旧代残留清掉')
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
test('wrap 的 promise 去重:并发两次同 key,producer 只执行一次', async () => {
|
|
96
|
+
const cache = createRecallCache()
|
|
97
|
+
let runs = 0
|
|
98
|
+
let release
|
|
99
|
+
const gate = new Promise((resolve) => { release = resolve })
|
|
100
|
+
const producer = async () => { runs += 1; await gate; return { n: runs } }
|
|
101
|
+
const first = cache.wrap('k', producer)
|
|
102
|
+
const joined = cache.wrap('k', producer)
|
|
103
|
+
assert.equal(first, joined, '同 key 在途合并复用同一个 promise')
|
|
104
|
+
assert.equal(cache.stats().inflight, 1)
|
|
105
|
+
release()
|
|
106
|
+
const [x, y] = await Promise.all([first, joined])
|
|
107
|
+
assert.equal(runs, 1)
|
|
108
|
+
assert.deepEqual(x, y)
|
|
109
|
+
assert.equal(cache.stats().inflight, 0)
|
|
110
|
+
const stats = cache.stats()
|
|
111
|
+
assert.equal(stats.misses, 1)
|
|
112
|
+
assert.equal(stats.hits, 1, '在途合并计为一次命中')
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
test('producer 抛错:不缓存、原样透传,下次重新执行', async () => {
|
|
116
|
+
const cache = createRecallCache()
|
|
117
|
+
let runs = 0
|
|
118
|
+
await assert.rejects(
|
|
119
|
+
cache.wrap('k', async () => { runs += 1; throw new Error('producer boom') }),
|
|
120
|
+
/producer boom/,
|
|
121
|
+
)
|
|
122
|
+
assert.equal(runs, 1)
|
|
123
|
+
assert.equal(cache.stats().errors, 0, 'producer 的业务错误不是缓存自身故障')
|
|
124
|
+
assert.equal(cache.stats().size, 0, '错误结果不入缓存')
|
|
125
|
+
const value = await cache.wrap('k', async () => { runs += 1; return { ok: true } })
|
|
126
|
+
assert.deepEqual(value, { ok: true })
|
|
127
|
+
assert.equal(runs, 2, '上次失败没有留下缓存')
|
|
128
|
+
})
|
|
129
|
+
|
|
130
|
+
test('缓存自身故障 fail-open:错误计数与 onError 留痕,绝不影响取值', () => {
|
|
131
|
+
const seen = []
|
|
132
|
+
const cache = createRecallCache({ onError: (info) => seen.push(info) })
|
|
133
|
+
// 值不可 structuredClone(含函数)→ set 失败开放,计数不抛出。
|
|
134
|
+
cache.set('bad', { fn: () => {} })
|
|
135
|
+
assert.equal(cache.get('bad'), null, '写失败的键按未命中处理')
|
|
136
|
+
assert.equal(cache.stats().size, 0)
|
|
137
|
+
// 假时钟爆炸 → get 失败开放,返回 null。
|
|
138
|
+
let boom = false
|
|
139
|
+
const clocky = createRecallCache({ now: () => { if (boom) throw new Error('clock broke'); return 1 } })
|
|
140
|
+
clocky.set('k', { v: 1 })
|
|
141
|
+
boom = true
|
|
142
|
+
assert.equal(clocky.get('k'), null)
|
|
143
|
+
assert.match(clocky.stats().lastError, /get: clock broke/)
|
|
144
|
+
assert.ok(seen.some((info) => info.op === 'set'), 'onError 把吞没的故障暴露给调用方')
|
|
145
|
+
assert.ok(cache.stats().errors >= 1)
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
test('键规范化:NFKC+trim+lowercase 归一,结构字段参与键', () => {
|
|
149
|
+
const base = { query: 'ABC', topK: 5, libraryId: 'lib', byId: false, route: 'managed-local', generation: 'gen:1:ab', revision: 3 }
|
|
150
|
+
assert.equal(recallCacheKey(base), recallCacheKey({ ...base, query: ' abc ' }), '首尾空格与大小写归一')
|
|
151
|
+
assert.equal(recallCacheKey(base), recallCacheKey({ ...base, query: 'ABC' }), 'NFKC 折叠全角')
|
|
152
|
+
assert.equal(recallCacheKey(base), recallCacheKey({ ...base, topK: '5' }), 'topK 数值归一')
|
|
153
|
+
assert.notEqual(recallCacheKey(base), recallCacheKey({ ...base, query: 'abcd' }), '不同 query 不同键')
|
|
154
|
+
assert.notEqual(recallCacheKey(base), recallCacheKey({ ...base, topK: 6 }), '不同 topK 不同键')
|
|
155
|
+
assert.notEqual(recallCacheKey(base), recallCacheKey({ ...base, libraryId: 'lib2' }), '不同 libraryId 不同键')
|
|
156
|
+
assert.notEqual(recallCacheKey(base), recallCacheKey({ ...base, route: 'remote-api' }), '不同 route 不同键')
|
|
157
|
+
assert.notEqual(recallCacheKey(base), recallCacheKey({ ...base, generation: 'gen:2:cd' }), '向量代数变化换键')
|
|
158
|
+
assert.notEqual(recallCacheKey(base), recallCacheKey({ ...base, revision: 4 }), '写路径 revision 变化换键')
|
|
159
|
+
assert.notEqual(recallCacheKey(base), recallCacheKey({ ...base, automatic: true }), 'automatic 语义不同换键')
|
|
160
|
+
assert.notEqual(recallCacheKey(base), recallCacheKey({ ...base, sessionId: 's2' }), '会话可见性不同换键')
|
|
161
|
+
assert.notEqual(recallCacheKey(base), recallCacheKey({ ...base, domain: 'rp' }), '域过滤不同换键')
|
|
162
|
+
assert.notEqual(recallCacheKey(base), recallCacheKey({ ...base, context: { characterId: 'hero' } }), '绑定上下文不同换键')
|
|
163
|
+
})
|
|
164
|
+
|
|
165
|
+
test('invalidate:按规范化 query 精确失效,其他 query 不受牵连', async () => {
|
|
166
|
+
const cache = createRecallCache()
|
|
167
|
+
const keyOf = (q) => recallCacheKey({ query: q, topK: 4, libraryId: 'lib', route: 'remote-api' })
|
|
168
|
+
await cache.wrap(keyOf('部署 窗口'), async () => ({ v: 1 }))
|
|
169
|
+
await cache.wrap(keyOf('咖啡偏好'), async () => ({ v: 2 }))
|
|
170
|
+
assert.equal(cache.invalidate('deploy-x'), 0)
|
|
171
|
+
assert.equal(cache.invalidate(' 部署 窗口 '), 1, 'trim + lowercase 归一后精确命中')
|
|
172
|
+
assert.equal(cache.get(keyOf('部署 窗口')), null)
|
|
173
|
+
assert.deepEqual(cache.get(keyOf('咖啡偏好')), { v: 2 }, '别的 query 不被牵连')
|
|
174
|
+
})
|
|
175
|
+
|
|
176
|
+
test('模块级单例存在且具备全部公开方法', () => {
|
|
177
|
+
for (const method of ['get', 'set', 'bumpGeneration', 'invalidate', 'clear', 'stats', 'wrap', 'setErrorHandler']) {
|
|
178
|
+
assert.equal(typeof recallCache[method], 'function', method)
|
|
179
|
+
}
|
|
180
|
+
assert.deepEqual(Object.keys(recallCache.stats()).sort(),
|
|
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')
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
// ---------------------------------------------------------------- 接线部分
|
|
186
|
+
|
|
187
|
+
let serial = 0
|
|
188
|
+
function entry(content, extra = {}) {
|
|
189
|
+
return { status: 'active', title: content, content, layer: 'long_term', strength: 1,
|
|
190
|
+
createdAt: '2026-10-01T00:00:00.000Z', updatedAt: '2026-10-01T00:00:00.000Z', ...extra }
|
|
191
|
+
}
|
|
192
|
+
function fixture(entries = {}) {
|
|
193
|
+
serial += 1
|
|
194
|
+
const sessionId = 'cache-' + serial
|
|
195
|
+
const cwd = path.join(home, 'project-' + serial)
|
|
196
|
+
const binding = state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
|
|
197
|
+
state.setSessionBinding(sessionId, { useLibrary: true, useGlobal: true, domainOverride: 'coding' })
|
|
198
|
+
state.savePrivateIndex(binding.libraryId, { entries })
|
|
199
|
+
return { sessionId, libraryId: binding.libraryId, exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'coding' } } } } }
|
|
200
|
+
}
|
|
201
|
+
function activate(libraryIds = []) {
|
|
202
|
+
const profile = vp.profileFromCatalog('bge-small-zh-v1.5-int8')
|
|
203
|
+
const databases = vp.buildDatabaseSet({ profile, generation: 1, libraryIds })
|
|
204
|
+
fs.mkdirSync(path.join(home, 'libraries'), { recursive: true })
|
|
205
|
+
for (const row of [databases.global, ...Object.values(databases.libraries)]) fs.writeFileSync(vp.resolveVectorPath(row.path), '')
|
|
206
|
+
vp.updateVectorStateSync(current => ({ ...current, generation: 1, requested: null, pending: null,
|
|
207
|
+
active: { status: 'active', generation: 1, fingerprint: profile.fingerprint, profile, databases } }))
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const retrieveCalls = () => calls.filter((call) => call.op === 'retrieve').length
|
|
211
|
+
|
|
212
|
+
test.beforeEach(() => {
|
|
213
|
+
state.updateSettings({ memoryBackend: 'api', vectorSource: 'local', relevanceThreshold: 0, privateTopK: 5 })
|
|
214
|
+
state.saveGlobalIndex({ entries: {} })
|
|
215
|
+
calls.length = 0
|
|
216
|
+
warnings.length = 0
|
|
217
|
+
retrieveHook = () => ({ files: [], segments: [], resources: [], raw: null })
|
|
218
|
+
paths.setWarnSink((message) => warnings.push(String(message)))
|
|
219
|
+
})
|
|
220
|
+
test.after(() => {
|
|
221
|
+
hooks.deregister()
|
|
222
|
+
delete globalThis.__recallCacheTest
|
|
223
|
+
paths.setWarnSink(null)
|
|
224
|
+
fs.rmSync(home, { recursive: true, force: true })
|
|
225
|
+
})
|
|
226
|
+
|
|
227
|
+
// purpose 用 'automatic'(每轮注入的真正热路径):显式召回会 touchAccess 写索引,
|
|
228
|
+
// 自己就会推进 revision——那是正确行为,但不适合演示命中。
|
|
229
|
+
test('接线:相同参数的两次召回,第二次命中缓存不再调 retrieveImpl', async () => {
|
|
230
|
+
const f = fixture({ 'mem-needle': entry('needle local match'), 'mem-orbit': entry('orbital mechanics') })
|
|
231
|
+
activate([f.libraryId])
|
|
232
|
+
retrieveHook = () => ({ files: [{ name: 'mem-orbit' }], segments: [], resources: [] })
|
|
233
|
+
const first = await memory.privateRecall({ exec: f.exec, query: 'needle', topK: 8, purpose: 'automatic' })
|
|
234
|
+
assert.equal(first.recallRoute, 'managed-vector-rrf')
|
|
235
|
+
assert.equal(retrieveCalls(), 1)
|
|
236
|
+
const second = await memory.privateRecall({ exec: f.exec, query: 'needle', topK: 8, purpose: 'automatic' })
|
|
237
|
+
assert.equal(second.recallRoute, 'managed-vector-rrf', '缓存值带着原 recallRoute 语义')
|
|
238
|
+
assert.equal(retrieveCalls(), 1, '第二次没有再进语义召回')
|
|
239
|
+
assert.deepEqual(second.files.map((file) => file.name), first.files.map((file) => file.name), '返回相同的 files')
|
|
240
|
+
assert.deepEqual(new Set(second.files.map((file) => file.name)), new Set(['mem-needle', 'mem-orbit']))
|
|
241
|
+
assert.equal(state.getSessionBinding(f.sessionId).lastRecallError, undefined, '命中路径照常清降级信号')
|
|
242
|
+
})
|
|
243
|
+
|
|
244
|
+
test('接线:写入索引后 revision 推进,第三次召回重新调 retrieveImpl 并拿到新记忆', async () => {
|
|
245
|
+
const f = fixture({ 'mem-needle': entry('needle local match'), 'mem-orbit': entry('orbital mechanics') })
|
|
246
|
+
activate([f.libraryId])
|
|
247
|
+
retrieveHook = () => ({ files: [{ name: 'mem-orbit' }], segments: [], resources: [] })
|
|
248
|
+
await memory.privateRecall({ exec: f.exec, query: 'needle', topK: 8, purpose: 'automatic' })
|
|
249
|
+
await memory.privateRecall({ exec: f.exec, query: 'needle', topK: 8, purpose: 'automatic' })
|
|
250
|
+
assert.equal(retrieveCalls(), 1)
|
|
251
|
+
// 写路径失效:真实写收敛点(savePrivateIndex → memoryRevision 自增)改动键。
|
|
252
|
+
const index = state.loadPrivateIndex(f.libraryId)
|
|
253
|
+
index.entries['mem-fresh'] = entry('needle written just now')
|
|
254
|
+
state.savePrivateIndex(f.libraryId, index)
|
|
255
|
+
retrieveHook = () => ({ files: [{ name: 'mem-fresh' }], segments: [], resources: [] })
|
|
256
|
+
const third = await memory.privateRecall({ exec: f.exec, query: 'needle', topK: 8, purpose: 'automatic' })
|
|
257
|
+
assert.equal(retrieveCalls(), 2, '写入后缓存失效,语义召回真实重跑')
|
|
258
|
+
assert.ok(third.files.some((file) => file.name === 'mem-fresh'), '拿到的是写入后的新世界,不是 stale 缓存')
|
|
259
|
+
})
|
|
260
|
+
|
|
261
|
+
test('接线:local-fallback 不缓存——失败的召回不会把降级结果放进缓存', async () => {
|
|
262
|
+
const f = fixture({ 'mem-needle': entry('needle local match') })
|
|
263
|
+
activate([f.libraryId])
|
|
264
|
+
retrieveHook = () => { throw new Error('semantic leg down') }
|
|
265
|
+
const failed = await memory.privateRecall({ exec: f.exec, query: 'needle', topK: 8, purpose: 'automatic' })
|
|
266
|
+
assert.equal(failed.recallRoute, 'local-fallback')
|
|
267
|
+
assert.equal(failed.errors.length, 1, 'fallback 带着 errors 信号')
|
|
268
|
+
assert.equal(retrieveCalls(), 1)
|
|
269
|
+
retrieveHook = () => ({ files: [{ name: 'mem-orbit' }], segments: [], resources: [] })
|
|
270
|
+
const healthy = await memory.privateRecall({ exec: f.exec, query: 'needle', topK: 8, purpose: 'automatic' })
|
|
271
|
+
assert.equal(healthy.recallRoute, 'managed-vector-rrf', '健康结果真实重算(失败那次没有占住键)')
|
|
272
|
+
assert.equal(retrieveCalls(), 2, 'producer 抛错不缓存,第二次仍会执行')
|
|
273
|
+
})
|
|
274
|
+
|
|
275
|
+
test('接线:query 大小写/首尾空格不同命中同一键', async () => {
|
|
276
|
+
const f = fixture({ 'mem-needle': entry('needle local match'), 'mem-orbit': entry('orbital mechanics') })
|
|
277
|
+
activate([f.libraryId])
|
|
278
|
+
retrieveHook = () => ({ files: [{ name: 'mem-orbit' }], segments: [], resources: [] })
|
|
279
|
+
await memory.privateRecall({ exec: f.exec, query: 'Needle', topK: 8, purpose: 'automatic' })
|
|
280
|
+
const again = await memory.privateRecall({ exec: f.exec, query: ' needle ', topK: 8, purpose: 'automatic' })
|
|
281
|
+
assert.equal(retrieveCalls(), 1, '规范化后命中同一缓存键')
|
|
282
|
+
assert.equal(again.recallRoute, 'managed-vector-rrf')
|
|
283
|
+
})
|
|
284
|
+
|
|
285
|
+
test('接线:topK 不同不共享缓存(融合截断上限随 topK 变化)', async () => {
|
|
286
|
+
const f = fixture({ 'mem-needle': entry('needle local match'), 'mem-orbit': entry('orbital mechanics') })
|
|
287
|
+
activate([f.libraryId])
|
|
288
|
+
retrieveHook = () => ({ files: [{ name: 'mem-orbit' }], segments: [], resources: [] })
|
|
289
|
+
await memory.privateRecall({ exec: f.exec, query: 'needle', topK: 8, purpose: 'automatic' })
|
|
290
|
+
await memory.privateRecall({ exec: f.exec, query: 'needle', topK: 3, purpose: 'automatic' })
|
|
291
|
+
assert.equal(retrieveCalls(), 2, 'topK 参与键,两种截断各算各的')
|
|
292
|
+
})
|
|
@@ -0,0 +1,100 @@
|
|
|
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('automatic recall hides never_say and only_if_asked; boundary questions release only_if_asked', async () => {
|
|
71
|
+
const { exec } = session('intent-disclosure')
|
|
72
|
+
const open = await memory.privateRemember({
|
|
73
|
+
exec, title: '账本放在书房', content: '账本放在书房第二个抽屉。',
|
|
74
|
+
})
|
|
75
|
+
const ask = await memory.privateRemember({
|
|
76
|
+
exec, title: '账本记着一笔旧账', content: '账本里记着一笔他不愿提的旧账。', disclosure: 'only_if_asked',
|
|
77
|
+
})
|
|
78
|
+
const never = await memory.privateRemember({
|
|
79
|
+
exec, title: '账本的真正来历', content: '账本其实是他父亲留下的。', disclosure: 'never_say',
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
const automatic = await memory.privateRecall({
|
|
83
|
+
exec, query: '账本', topK: 10, relevanceThreshold: 0, purpose: 'automatic',
|
|
84
|
+
})
|
|
85
|
+
const autoIds = automatic.files.map((file) => file.name)
|
|
86
|
+
assert.ok(autoIds.includes(open.id))
|
|
87
|
+
assert.ok(!autoIds.includes(ask.id), 'only_if_asked waits for a direct question')
|
|
88
|
+
assert.ok(!autoIds.includes(never.id), 'never_say never auto-surfaces')
|
|
89
|
+
|
|
90
|
+
const explicit = await memory.privateRecall({ exec, query: '账本', topK: 10, relevanceThreshold: 0 })
|
|
91
|
+
const explicitIds = explicit.files.map((file) => file.name)
|
|
92
|
+
assert.ok(explicitIds.includes(ask.id) && explicitIds.includes(never.id), 'an explicit recall may still read them')
|
|
93
|
+
|
|
94
|
+
const boundary = await memory.privateRecall({
|
|
95
|
+
exec, query: '账本的秘密是什么', topK: 10, relevanceThreshold: 0, purpose: 'automatic',
|
|
96
|
+
})
|
|
97
|
+
const boundaryIds = boundary.files.map((file) => file.name)
|
|
98
|
+
assert.ok(boundaryIds.includes(ask.id), 'a boundary question is the "asked" case')
|
|
99
|
+
assert.ok(!boundaryIds.includes(never.id), 'never_say stays out even then')
|
|
100
|
+
})
|
|
@@ -0,0 +1,120 @@
|
|
|
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-speaker-'))
|
|
8
|
+
process.env.DSH_MEMU_HOME = home
|
|
9
|
+
|
|
10
|
+
const state = await import('../lib/state.js')
|
|
11
|
+
const memory = await import('../lib/memory.js')
|
|
12
|
+
const inject = await import('../lib/inject.js')
|
|
13
|
+
|
|
14
|
+
test.after(() => {
|
|
15
|
+
try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
let seq = 0
|
|
19
|
+
function session(name) {
|
|
20
|
+
seq += 1
|
|
21
|
+
const cwd = path.join(home, 'ws', `${name}-${seq}`)
|
|
22
|
+
const sessionId = `${name}-${seq}`
|
|
23
|
+
state.ensureSession(sessionId, { cwd, agentPreset: 'rp' })
|
|
24
|
+
return {
|
|
25
|
+
sessionId,
|
|
26
|
+
exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'rp' } } } },
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
test('speaker and source_kind are stored and default honestly', async () => {
|
|
31
|
+
const { exec } = session('speaker-fields')
|
|
32
|
+
const said = await memory.privateRemember({
|
|
33
|
+
exec, title: '用户提到旅行', content: '我想去 Iceland 看极光。', source: 'user_said',
|
|
34
|
+
})
|
|
35
|
+
assert.equal(said.entry.speaker_id, 'user')
|
|
36
|
+
assert.equal(said.entry.source_kind, 'user_said')
|
|
37
|
+
|
|
38
|
+
const promised = await memory.privateRemember({
|
|
39
|
+
exec, title: '助手答应查机票', content: '我明天帮你查去冰岛的机票。',
|
|
40
|
+
sourceKind: 'assistant_said', speakerId: 'assistant',
|
|
41
|
+
quoteSpan: { seq: 42, turn: 7, textHash: 'abc123' },
|
|
42
|
+
storylineId: 'iceland-trip', branchId: 'branch-a', knownBy: ['user', 'assistant'],
|
|
43
|
+
})
|
|
44
|
+
assert.equal(promised.entry.source, 'assistant_said')
|
|
45
|
+
assert.equal(promised.entry.source_kind, 'assistant_said')
|
|
46
|
+
assert.equal(promised.entry.speaker_id, 'assistant')
|
|
47
|
+
assert.deepEqual(promised.entry.quote_span, { seq: 42, turn: 7, textHash: 'abc123' })
|
|
48
|
+
assert.equal(promised.entry.storyline_id, 'iceland-trip')
|
|
49
|
+
assert.equal(promised.entry.branch_id, 'branch-a')
|
|
50
|
+
assert.deepEqual(promised.entry.known_by, ['user', 'assistant'])
|
|
51
|
+
|
|
52
|
+
const imagined = await memory.privateRemember({
|
|
53
|
+
exec, title: '想象里的雪', content: '她想象过冰岛的雪落在窗台上。', source: 'imagined',
|
|
54
|
+
})
|
|
55
|
+
assert.equal(imagined.entry.source_kind, 'imagined')
|
|
56
|
+
assert.equal(imagined.entry.speaker_id, 'unknown', 'an imagined memory cannot claim a speaker')
|
|
57
|
+
|
|
58
|
+
const contextSpeaker = await memory.privateRemember({
|
|
59
|
+
exec, title: '角色说过的话', content: '林说冰岛的冬天太长了。',
|
|
60
|
+
source: 'user_said', context: { speakerId: 'character:lin' },
|
|
61
|
+
})
|
|
62
|
+
assert.equal(contextSpeaker.entry.speaker_id, 'character:lin', 'a bound speaker identity wins over the default')
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
test('a conflicting source/source_kind pair is refused, and so is a bad quote_span', async () => {
|
|
66
|
+
const { exec } = session('speaker-invalid')
|
|
67
|
+
await assert.rejects(
|
|
68
|
+
() => memory.privateRemember({ exec, title: '矛盾来源', content: '测试。', source: 'user_said', sourceKind: 'assistant_said' }),
|
|
69
|
+
/source and source_kind disagree/,
|
|
70
|
+
)
|
|
71
|
+
await assert.rejects(
|
|
72
|
+
() => memory.privateRemember({ exec, title: '坏 span', content: '测试。', sourceKind: 'assistant_said', quoteSpan: { seq: -1 } }),
|
|
73
|
+
/quote_span\.seq/,
|
|
74
|
+
)
|
|
75
|
+
await assert.rejects(
|
|
76
|
+
() => memory.privateRemember({ exec, title: '坏说话人', content: '测试。', sourceKind: 'user_said', speakerId: ' ' }),
|
|
77
|
+
/speaker_id/,
|
|
78
|
+
)
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
test('a query that asks who said it filters recall by speaker', async () => {
|
|
82
|
+
const { exec } = session('speaker-filter')
|
|
83
|
+
const userSide = await memory.privateRemember({
|
|
84
|
+
exec, title: '旅行计划 A', content: '旅行要去冰岛看极光。', source: 'user_said',
|
|
85
|
+
})
|
|
86
|
+
const assistantSide = await memory.privateRemember({
|
|
87
|
+
exec, title: '旅行计划 B', content: '旅行去冰岛看极光,我来订票。', sourceKind: 'assistant_said',
|
|
88
|
+
})
|
|
89
|
+
const unknownSide = await memory.privateRemember({
|
|
90
|
+
exec, title: '旅行计划 C', content: '旅行去冰岛看极光是旧念头。',
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
const mine = await memory.privateRecall({ exec, query: '我说过旅行去冰岛看极光', topK: 10, relevanceThreshold: 0 })
|
|
94
|
+
const mineIds = mine.files.map((file) => file.name)
|
|
95
|
+
assert.ok(mineIds.includes(userSide.id))
|
|
96
|
+
assert.ok(!mineIds.includes(assistantSide.id), 'the assistant statement is not returned for 我说过')
|
|
97
|
+
assert.ok(mineIds.includes(unknownSide.id), 'an entry without a speaker stays recallable')
|
|
98
|
+
|
|
99
|
+
const yours = await memory.privateRecall({ exec, query: '你说过旅行去冰岛看极光', topK: 10, relevanceThreshold: 0 })
|
|
100
|
+
const yourIds = yours.files.map((file) => file.name)
|
|
101
|
+
assert.ok(yourIds.includes(assistantSide.id))
|
|
102
|
+
assert.ok(!yourIds.includes(userSide.id), 'the user statement is not returned for 你说过')
|
|
103
|
+
|
|
104
|
+
assert.equal(memory.detectSpeakerQuery('我说过要早点睡'), 'user')
|
|
105
|
+
assert.equal(memory.detectSpeakerQuery('你说过会帮我查机票'), 'assistant')
|
|
106
|
+
assert.equal(memory.detectSpeakerQuery('他说过要早点睡'), 'third')
|
|
107
|
+
assert.equal(memory.detectSpeakerQuery('冰岛在哪里'), null)
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
test('the injected title card names a non-default speaker', async () => {
|
|
111
|
+
const { exec, sessionId } = session('speaker-inject')
|
|
112
|
+
await memory.privateRemember({
|
|
113
|
+
exec, title: '助手答应订票', content: '助手答应明天订机票。', sourceKind: 'assistant_said',
|
|
114
|
+
})
|
|
115
|
+
const binding = state.getSessionBinding(sessionId)
|
|
116
|
+
const recall = await inject.buildRecall(binding, '订票', 1, { ...state.getSettings(), relevanceThreshold: 0, privateTopK: 5 }, exec, sessionId)
|
|
117
|
+
assert.deepEqual(recall.errors, [])
|
|
118
|
+
assert.match(recall.text, /source=assistant_said/)
|
|
119
|
+
assert.match(recall.text, /speaker=assistant/)
|
|
120
|
+
})
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// dsh-llm-pi-ai 的测试桩:整理 fork 自定义模型 route(lib/fork-model.js)在测试进程里
|
|
2
|
+
// 拉不到宿主包,loader(tests/loader.mjs)把该 peer 依赖映射到这里。只保证「PiAiAdapter
|
|
3
|
+
// 是可构造的类、构造 options 会被记录」——构造/探测/注册的真实逻辑由 fork-model.test.mjs
|
|
4
|
+
// 用注入的 loader stub(mock llm + 注入 PiAiAdapter)逐分支覆盖,这里只让 private.js 的
|
|
5
|
+
// 生产接线(默认 loader)在测试里走通成功路径。
|
|
6
|
+
export class PiAiAdapter {
|
|
7
|
+
constructor(options) {
|
|
8
|
+
globalThis.__dshMemuLastPiAiAdapterOptions = options
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export const name = 'llm-pi-ai'
|
|
13
|
+
export const inject = ['llm']
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
parseTemporalExpression,
|
|
6
|
+
extractTemporalExpressions,
|
|
7
|
+
resolveQueryDates,
|
|
8
|
+
parseAbsoluteDate,
|
|
9
|
+
hasTemporalHint,
|
|
10
|
+
} from '../lib/temporal.js'
|
|
11
|
+
|
|
12
|
+
// 2026-11-06 12:00 Asia/Shanghai (Friday).
|
|
13
|
+
const NOW = new Date('2026-11-06T04:00:00Z')
|
|
14
|
+
|
|
15
|
+
const parse = (text, options = {}) => parseTemporalExpression(text, { now: NOW, ...options })
|
|
16
|
+
const dateOf = (text, options = {}) => parse(text, options)?.absoluteDate ?? null
|
|
17
|
+
|
|
18
|
+
test('relative day words resolve against the scene time', () => {
|
|
19
|
+
assert.equal(dateOf('今天'), '2026-11-06')
|
|
20
|
+
assert.equal(dateOf('明天'), '2026-11-07')
|
|
21
|
+
assert.equal(dateOf('后天'), '2026-11-08')
|
|
22
|
+
assert.equal(dateOf('大后天'), '2026-11-09')
|
|
23
|
+
assert.equal(dateOf('昨天'), '2026-11-05')
|
|
24
|
+
assert.equal(dateOf('前天'), '2026-11-04')
|
|
25
|
+
assert.equal(dateOf('大前天'), '2026-11-03')
|
|
26
|
+
// A longer term wins over the shorter one inside it.
|
|
27
|
+
const daHoutian = parse('大后天')
|
|
28
|
+
assert.equal(daHoutian.sourceText, '大后天')
|
|
29
|
+
assert.equal(daHoutian.precision, 'day')
|
|
30
|
+
assert.equal(daHoutian.dateSource, 'relative')
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
test('relative days cross month, year and leap-day boundaries', () => {
|
|
34
|
+
assert.equal(dateOf('明天', { now: new Date('2026-01-31T04:00:00Z') }), '2026-02-01')
|
|
35
|
+
assert.equal(dateOf('明天', { now: new Date('2026-12-31T04:00:00Z') }), '2027-01-01')
|
|
36
|
+
// 2028 is a leap year: Feb 28 + 1 = Feb 29, Feb 29 + 1 = Mar 1.
|
|
37
|
+
assert.equal(dateOf('明天', { now: new Date('2028-02-28T04:00:00Z') }), '2028-02-29')
|
|
38
|
+
assert.equal(dateOf('明天', { now: new Date('2028-02-29T04:00:00Z') }), '2028-03-01')
|
|
39
|
+
assert.equal(dateOf('昨天', { now: new Date('2028-03-01T04:00:00Z') }), '2028-02-29')
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
test('week phrases use Monday-based weeks and never guess a bare weekday', () => {
|
|
43
|
+
// 2026-11-06 is a Friday; this week's Monday is 2026-11-02.
|
|
44
|
+
assert.equal(dateOf('这周三'), '2026-11-04')
|
|
45
|
+
assert.equal(dateOf('本周日'), '2026-11-08')
|
|
46
|
+
assert.equal(dateOf('下周一'), '2026-11-09')
|
|
47
|
+
assert.equal(dateOf('下周三'), '2026-11-11')
|
|
48
|
+
assert.equal(dateOf('下个星期天'), '2026-11-15')
|
|
49
|
+
assert.equal(dateOf('上周六'), '2026-10-31')
|
|
50
|
+
assert.equal(dateOf('上上礼拜一'), '2026-10-19')
|
|
51
|
+
// Bare "周三" is ambiguous between this week and next; the module must not pick one.
|
|
52
|
+
assert.equal(dateOf('周三见'), null)
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
test('month, month-end and year boundaries resolve to a concrete day', () => {
|
|
56
|
+
assert.equal(dateOf('下个月15号'), '2026-12-15')
|
|
57
|
+
assert.equal(dateOf('本月6号'), '2026-11-06')
|
|
58
|
+
const monthEnd = parse('月底')
|
|
59
|
+
assert.equal(monthEnd.absoluteDate, '2026-11-30')
|
|
60
|
+
assert.equal(monthEnd.precision, 'month')
|
|
61
|
+
assert.equal(dateOf('下月底'), '2026-12-31')
|
|
62
|
+
const yearStart = parse('年初')
|
|
63
|
+
assert.equal(yearStart.absoluteDate, '2026-01-01')
|
|
64
|
+
assert.equal(yearStart.precision, 'year')
|
|
65
|
+
assert.equal(dateOf('年底'), '2026-12-31')
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
test('impossible dates are refused instead of guessed', () => {
|
|
69
|
+
assert.equal(dateOf('2026-02-30'), null)
|
|
70
|
+
assert.equal(dateOf('2026-13-01'), null)
|
|
71
|
+
// "下个月30号" said in January points at February 30th, which does not exist.
|
|
72
|
+
assert.equal(dateOf('下个月30号', { now: new Date('2026-01-15T04:00:00Z') }), null)
|
|
73
|
+
assert.equal(parseAbsoluteDate('2026-02-29'), null)
|
|
74
|
+
assert.equal(parseAbsoluteDate('2028-02-29'), '2028-02-29')
|
|
75
|
+
assert.equal(dateOf('下周'), null, 'a week without a weekday is not a day')
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
test('explicit dates win over relative words and keep their precision', () => {
|
|
79
|
+
assert.equal(dateOf('2026-11-09 见面'), '2026-11-09')
|
|
80
|
+
assert.equal(dateOf('约定在2026年12月1日'), '2026-12-01')
|
|
81
|
+
assert.equal(dateOf('昨天说好下周三'), '2026-11-05', 'the first trustworthy expression is used for the entry date')
|
|
82
|
+
const explicit = parse('2026-11-09')
|
|
83
|
+
assert.equal(explicit.dateSource, 'explicit')
|
|
84
|
+
assert.equal(explicit.precision, 'day')
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
test('offset days and English relative words', () => {
|
|
88
|
+
assert.equal(dateOf('3天后'), '2026-11-09')
|
|
89
|
+
assert.equal(dateOf('10天前'), '2026-10-27')
|
|
90
|
+
assert.equal(dateOf('tomorrow'), '2026-11-07')
|
|
91
|
+
assert.equal(dateOf('the day after tomorrow'), '2026-11-08')
|
|
92
|
+
assert.equal(dateOf('yesterday'), '2026-11-05')
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
test('the time zone changes what "today" means', () => {
|
|
96
|
+
// 16:30Z is already Nov 6 in Shanghai but still Nov 5 in New York.
|
|
97
|
+
const instant = new Date('2026-11-05T16:30:00Z')
|
|
98
|
+
assert.equal(dateOf('明天', { now: instant, timeZone: 'Asia/Shanghai' }), '2026-11-07')
|
|
99
|
+
assert.equal(dateOf('明天', { now: instant, timeZone: 'America/New_York' }), '2026-11-06')
|
|
100
|
+
// An unknown zone falls back instead of throwing: a bad setting must not fail a write.
|
|
101
|
+
assert.equal(dateOf('明天', { now: instant, timeZone: 'Not/AZone' }), '2026-11-07')
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
test('all expressions can be extracted for query expansion', () => {
|
|
105
|
+
const all = extractTemporalExpressions('昨天她说下周三见面,月底再确认', { now: NOW })
|
|
106
|
+
assert.deepEqual(all.map((item) => item.sourceText), ['昨天', '下周三', '月底'])
|
|
107
|
+
assert.deepEqual(resolveQueryDates('昨天她说下周三见面,月底再确认', { now: NOW }), ['2026-11-05', '2026-11-11', '2026-11-30'])
|
|
108
|
+
assert.deepEqual(resolveQueryDates('没有日期的句子', { now: NOW }), [])
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
test('hasTemporalHint distinguishes a relative hint from ordinary text', () => {
|
|
112
|
+
assert.equal(hasTemporalHint('下周再说'), true)
|
|
113
|
+
assert.equal(hasTemporalHint('月底前给答复'), true)
|
|
114
|
+
assert.equal(hasTemporalHint('tomorrow morning'), true)
|
|
115
|
+
assert.equal(hasTemporalHint('窗外的雨停了'), false)
|
|
116
|
+
assert.equal(hasTemporalHint(undefined), false)
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
test('empty and non-string input never throw', () => {
|
|
120
|
+
for (const value of [null, undefined, '', ' ', 123, {}]) {
|
|
121
|
+
assert.equal(parseTemporalExpression(value, { now: NOW }), null)
|
|
122
|
+
assert.deepEqual(extractTemporalExpressions(value, { now: NOW }), [])
|
|
123
|
+
}
|
|
124
|
+
})
|