dsh-memu-memory 1.3.7 → 1.3.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 (63) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +70 -0
  3. package/README.md +7 -7
  4. package/README.zh.md +7 -7
  5. package/docs/client-conventions.md +1 -0
  6. package/docs/contributing.md +2 -2
  7. package/docs/host-adaptation.md +1 -1
  8. package/docs/memory-semantics.md +7 -6
  9. package/docs/troubleshooting.md +74 -7
  10. package/lib/auto-link/decide.js +0 -4
  11. package/lib/binding-diagnostics.js +2 -2
  12. package/lib/client.js +150 -81
  13. package/lib/consolidation-ledger.js +6 -2
  14. package/lib/curator.js +42 -10
  15. package/lib/cycle.js +28 -3
  16. package/lib/inbound.js +24 -9
  17. package/lib/inject.js +379 -215
  18. package/lib/local-vector-service.js +1 -10
  19. package/lib/memory.js +704 -181
  20. package/lib/paths.js +24 -0
  21. package/lib/private.js +294 -134
  22. package/lib/rpc.js +53 -6
  23. package/lib/snippet.js +49 -28
  24. package/lib/state.js +185 -26
  25. package/lib/tools.js +137 -28
  26. package/lib/webui.js +25 -1
  27. package/lib/worker-pool.js +260 -26
  28. package/package.json +1 -1
  29. package/scripts/check-i18n.mjs +19 -0
  30. package/scripts/recall-bench.mjs +4 -4
  31. package/scripts/simulate-injection.mjs +3 -0
  32. package/tests/activity-wiring.test.mjs +52 -0
  33. package/tests/client-render.test.mjs +207 -0
  34. package/tests/consolidation-feed.test.mjs +26 -0
  35. package/tests/consolidation-fork.test.mjs +587 -26
  36. package/tests/cross-library-recall.test.mjs +156 -0
  37. package/tests/cue.test.mjs +15 -2
  38. package/tests/curator-contract.test.mjs +191 -0
  39. package/tests/curator-probe.test.mjs +5 -5
  40. package/tests/curator.test.mjs +3 -1
  41. package/tests/hybrid-recall.test.mjs +488 -0
  42. package/tests/inbound.test.mjs +49 -4
  43. package/tests/inject-conflict.test.mjs +70 -9
  44. package/tests/inject-guide.test.mjs +13 -1
  45. package/tests/inject.test.mjs +10 -0
  46. package/tests/injection-budget.test.mjs +101 -0
  47. package/tests/injection-chain.test.mjs +37 -0
  48. package/tests/injection-rollback.test.mjs +172 -9
  49. package/tests/issue2-chain.test.mjs +169 -0
  50. package/tests/lexicon-inject.test.mjs +33 -5
  51. package/tests/managed-memory.test.mjs +625 -1
  52. package/tests/media.test.mjs +1 -1
  53. package/tests/new-session-gate.test.mjs +280 -25
  54. package/tests/open-loop-date.test.mjs +11 -1
  55. package/tests/recall-intent.test.mjs +52 -3
  56. package/tests/regression-sweep.test.mjs +281 -0
  57. package/tests/simulate-injection.test.mjs +4 -4
  58. package/tests/snippet.test.mjs +33 -1
  59. package/tests/state.test.mjs +8 -3
  60. package/tests/tool-schema.test.mjs +52 -0
  61. package/tests/tools.test.mjs +394 -0
  62. package/tests/webui.test.mjs +16 -2
  63. package/tests/worker-lifecycle.test.mjs +419 -36
@@ -39,7 +39,7 @@ test('three image events store one verified blob and hint at a habit, not an aut
39
39
 
40
40
  test('image-only turns retrieve a saved image and expose the image count in status', async () => {
41
41
  const saved = await memory.privateRemember({ exec, title: '生日照片', content: '上次生日的一张照片。', attachments: [{ sha256: sha }], layer: 'long_term' })
42
- const message = { role: 'user', ...event(4).data }
42
+ const message = { id: 'image-only-native-user', role: 'user', ...event(4).data }
43
43
  const decision = await inject.injectForStep({ agent: exec.agent, decision: { kind: 'enter', messages: [message] }, turn: 2, step: 1 })
44
44
  assert.ok(decision.messages.length > 1)
45
45
  assert.ok(decision.messages[0].content[0].text.includes(saved.id))
@@ -12,8 +12,29 @@ function makeElement(type, props, ...children) {
12
12
  }
13
13
 
14
14
  let hooks = []
15
+ let refs = []
15
16
  let cursor = 0
16
17
  let effects = []
18
+ const committedEffects = new Map()
19
+ const sameDeps = (a, b) => a && b && a.length === b.length && a.every((value, index) => Object.is(value, b[index]))
20
+
21
+ function commitEffects() {
22
+ const scheduled = effects
23
+ effects = []
24
+ for (const { fn, deps, index } of scheduled) {
25
+ const previous = committedEffects.get(index)
26
+ if (sameDeps(previous?.deps, deps)) continue
27
+ previous?.cleanup?.()
28
+ committedEffects.set(index, { deps, cleanup: fn() })
29
+ }
30
+ }
31
+
32
+ function unmount() {
33
+ for (const effect of committedEffects.values()) effect.cleanup?.()
34
+ committedEffects.clear()
35
+ }
36
+
37
+ test.afterEach(unmount)
17
38
 
18
39
  const React = {
19
40
  createElement: makeElement,
@@ -23,11 +44,22 @@ const React = {
23
44
  if (hooks[index] === undefined) hooks[index] = typeof initial === 'function' ? initial() : initial
24
45
  return [hooks[index], (next) => { hooks[index] = typeof next === 'function' ? next(hooks[index]) : next }]
25
46
  },
26
- useCallback: (fn) => fn,
27
- useMemo: (fn) => fn(),
47
+ useCallback(fn, deps) { return React.useMemo(() => fn, deps) },
48
+ useMemo(fn, deps) {
49
+ const index = cursor++
50
+ if (!sameDeps(hooks[index]?.deps, deps)) hooks[index] = { deps, value: fn() }
51
+ return hooks[index].value
52
+ },
28
53
  useEffect(fn, deps) { effects.push({ fn, deps, index: cursor++ }) },
29
54
  useLayoutEffect() {},
30
- useRef: (value) => ({ current: value }),
55
+ // Refs must survive re-renders like real React: the gate's decided/deferred/
56
+ // failures refs span renders, and a fresh-object-per-render stub would make
57
+ // every cross-render scenario (稍后 → 切走 → 回来) a false pass.
58
+ useRef(value) {
59
+ const index = cursor++
60
+ if (refs[index] === undefined) refs[index] = { current: value }
61
+ return refs[index]
62
+ },
31
63
  useSyncExternalStore: (_subscribe, getSnapshot) => getSnapshot(),
32
64
  }
33
65
 
@@ -73,13 +105,31 @@ const OPEN_FOLDER = {
73
105
  settings: { newSessionPromptDismissed: false, newSessionDefault: 'both' },
74
106
  }
75
107
 
76
- function buildCtx(promptState) {
77
- const snapshot = { byId: { 'sess-1': { cwd: '/ws/demo', blank: true, origin: 'user' } }, ids: ['sess-1'] }
108
+ function buildCtx(promptState, opts = {}) {
109
+ // The live session/summary state the gate reads through the host stores.
110
+ // Mutable so a test can walk the exact issue #2 path: 新建会话 → 稍后 → 切走 →
111
+ // 再新建会话 (the host reuses the same blank session id; see ui-workspace
112
+ // navigation.ts "New Session returns to that blank").
113
+ const runtime = {
114
+ current: opts.current || 'sess-1',
115
+ sessions: opts.sessions || { 'sess-1': { cwd: '/ws/demo', blank: true, origin: 'user' } },
116
+ failEndpoints: new Set(opts.failEndpoints || []),
117
+ stateCalls: 0,
118
+ }
119
+ lastRuntime = runtime
120
+ const snapshot = () => ({
121
+ byId: Object.fromEntries(Object.entries(runtime.sessions).map(([id, value]) => [id, { ...value }])),
122
+ ids: Object.keys(runtime.sessions),
123
+ })
78
124
  const connection = {
79
125
  rpc: {
80
126
  call: async (_path, endpoint, payload) => {
81
- if (endpoint === 'getSessionPromptState') return { ok: true, value: promptState }
82
- if (endpoint === 'initSession' || endpoint === 'setSessionScope' || endpoint === 'setDomain') {
127
+ if (endpoint === 'getSessionPromptState') runtime.stateCalls++
128
+ if (runtime.failEndpoints.has(endpoint)) throw new Error('rpc failed: ' + endpoint)
129
+ if (endpoint === 'getSessionPromptState') {
130
+ return { ok: true, value: typeof promptState === 'function' ? await promptState(payload) : promptState }
131
+ }
132
+ if (endpoint === 'initSession' || endpoint === 'setSessionScope' || endpoint === 'setDomain' || endpoint === 'logClientEvent') {
83
133
  calls.push({ endpoint, payload })
84
134
  return { ok: true, value: {} }
85
135
  }
@@ -91,9 +141,9 @@ function buildCtx(promptState) {
91
141
  // sub-scope that can still reach the session and the RPC connection.
92
142
  const gateScope = {
93
143
  get: (name) => (name === 'uiSession'
94
- ? { adapter: { current: { subscribe: () => () => {}, getSnapshot: () => ({ key: 'sess-1' }) } } }
144
+ ? { adapter: { current: { subscribe: () => () => {}, getSnapshot: () => ({ key: runtime.current }) } } }
95
145
  : undefined),
96
- sessions: { list: { subscribe: () => () => {}, getSnapshot: () => snapshot } },
146
+ sessions: { list: { subscribe: () => () => {}, getSnapshot: snapshot } },
97
147
  connection,
98
148
  effect: (fn) => { try { fn() } catch {} },
99
149
  }
@@ -112,14 +162,18 @@ function buildCtx(promptState) {
112
162
  }
113
163
 
114
164
  const calls = []
165
+ let lastRuntime = null
115
166
 
116
- function renderGate(promptState) {
167
+ function renderGate(promptState, opts) {
168
+ unmount()
117
169
  hooks = []
170
+ refs = []
118
171
  calls.length = 0
172
+ lastRuntime = null
119
173
  cursor = 0
120
174
  effects = []
121
175
  roots.length = 0
122
- globalThis.__dshMemuExports.apply(buildCtx(promptState))
176
+ globalThis.__dshMemuExports.apply(buildCtx(promptState, opts))
123
177
  assert.equal(roots.length, 1, 'the new-session gate was not mounted at all')
124
178
  return roots[0].element
125
179
  }
@@ -127,15 +181,10 @@ function renderGate(promptState) {
127
181
  // First pass renders nothing (no prompt yet), the mount effect fetches the state,
128
182
  // the second pass renders the dialog with whatever the effect decided.
129
183
  async function settle(element) {
130
- effects = []
131
- cursor = 0
132
- const first = element.type(element.props)
133
- for (const effect of effects) effect.fn()
134
- await new Promise((resolve) => setTimeout(resolve, 0))
135
- await new Promise((resolve) => setTimeout(resolve, 0))
136
- effects = []
137
- cursor = 0
138
- return { first, tree: element.type(element.props) }
184
+ const first = paint(element)
185
+ await tick()
186
+ await tick()
187
+ return { first, tree: paint(element) }
139
188
  }
140
189
 
141
190
  function treeText(node, depth = 0) {
@@ -235,13 +284,12 @@ const CARD_ANSWERS = [
235
284
  { key: 'memBothTitle', layers: { useLibrary: true, useGlobal: true }, createLibrary: true },
236
285
  ]
237
286
 
238
- // Re-run the component with the current hook state but WITHOUT replaying the
239
- // mount effect: the effect re-fetches the state and would reset the card the
240
- // test just clicked.
241
287
  function paint(element) {
242
288
  cursor = 0
243
289
  effects = []
244
- return element.type(element.props)
290
+ const tree = element.type(element.props)
291
+ commitEffects()
292
+ return tree
245
293
  }
246
294
 
247
295
  function findNode(tree, predicate) {
@@ -250,7 +298,7 @@ function findNode(tree, predicate) {
250
298
  return hit
251
299
  }
252
300
 
253
- const tick = () => new Promise((resolve) => setTimeout(resolve, 0))
301
+ const tick = () => new Promise((resolve) => setImmediate(resolve))
254
302
 
255
303
  async function answerCard(cardKey) {
256
304
  const element = renderGate(OPEN_FOLDER)
@@ -359,3 +407,210 @@ test('the prompt defaults the domain to RP and can switch it to Coding', async (
359
407
  assert.deepEqual(calls.map((call) => call.endpoint), ['initSession', 'setSessionScope', 'setDomain'])
360
408
  assert.equal(calls[2].payload.domain, 'coding', 'the selected Coding domain was not written')
361
409
  })
410
+
411
+ // ---- issue #2: 新会话弹窗在「点稍后 → 再新建会话」后不再出现 ------------------
412
+ // The host's New Session reuses the same blank session (ui-workspace
413
+ // navigation.ts), so a 稍后 that answered forever meant the blank conversation
414
+ // could never be asked again — and its first message silently bound RP.
415
+
416
+ async function live(element) {
417
+ return (await settle(element)).tree
418
+ }
419
+
420
+ test('稍后 keeps the blank session askable: stay quiet, then ask again on reopen', async () => {
421
+ const element = renderGate(OPEN_FOLDER, {
422
+ sessions: {
423
+ 'sess-0': { cwd: '/ws/demo', blank: false, origin: 'user' }, // 已有的普通会话
424
+ 'sess-1': { cwd: '/ws/demo', blank: true, origin: 'user' }, // 新建的空白会话
425
+ },
426
+ })
427
+ const { tree } = await settle(element)
428
+ assert.ok(tree, 'the prompt did not appear for a fresh blank session')
429
+
430
+ const laterButton = findNode(tree, (node) => node.props?.key === 'later' && typeof node.props?.onClick === 'function')
431
+ assert.ok(laterButton, 'the prompt has no Later button')
432
+ await laterButton.props.onClick()
433
+
434
+ // 还停在这个会话上(列表刷新等导致的重渲染):不重复打扰。
435
+ const stayed = await live(element)
436
+ assert.equal(stayed, null, '稍后 must suppress re-asking while the user stays on the session')
437
+
438
+ // 切回另一个已有会话(有内容,本来就终局不问)。
439
+ lastRuntime.current = 'sess-0'
440
+ await live(element)
441
+
442
+ // 再点「新建会话」——宿主复用同一个空白会话 sess-1:必须重新弹窗(issue #2)。
443
+ lastRuntime.current = 'sess-1'
444
+ const again = await live(element)
445
+ assert.ok(again, 'the prompt never came back after 稍后 + New Session reuse')
446
+ })
447
+
448
+ test('a failed check logs and retries after backoff without a list refresh', async (t) => {
449
+ t.mock.timers.enable({ apis: ['setTimeout', 'Date'] })
450
+ const element = renderGate(OPEN_FOLDER, { failEndpoints: ['getSessionPromptState'] })
451
+ assert.equal((await settle(element)).tree, null)
452
+ assert.equal(lastRuntime.stateCalls, 1)
453
+ assert.ok(calls.some((call) => call.endpoint === 'logClientEvent' && call.payload.kind === 'error'))
454
+ lastRuntime.failEndpoints.clear()
455
+ t.mock.timers.tick(999)
456
+ assert.equal(await live(element), null)
457
+ assert.equal(lastRuntime.stateCalls, 1)
458
+ t.mock.timers.tick(1)
459
+ assert.ok(await live(element))
460
+ assert.equal(lastRuntime.stateCalls, 2)
461
+ })
462
+
463
+ test('three failures remain retryable and reopening bypasses the old backoff', async (t) => {
464
+ t.mock.timers.enable({ apis: ['setTimeout', 'Date'] })
465
+ const element = renderGate(OPEN_FOLDER, { failEndpoints: ['getSessionPromptState'] })
466
+ await settle(element)
467
+ for (const delay of [1000, 2000]) { t.mock.timers.tick(delay); await live(element) }
468
+ assert.equal(lastRuntime.stateCalls, 3)
469
+ lastRuntime.sessions['sess-0'] = { cwd: '/ws/demo', blank: false, origin: 'user' }
470
+ lastRuntime.current = 'sess-0'
471
+ await live(element)
472
+ lastRuntime.failEndpoints.clear()
473
+ lastRuntime.current = 'sess-1'
474
+ assert.ok(await live(element), 'reopening a recovered session must ask without a remount')
475
+ assert.equal(lastRuntime.stateCalls, 4)
476
+ assert.equal(calls.filter((call) => call.endpoint === 'logClientEvent').length, 3)
477
+ })
478
+
479
+ test('repeated failures back off up to thirty seconds instead of giving up', async (t) => {
480
+ t.mock.timers.enable({ apis: ['setTimeout', 'Date'] })
481
+ const element = renderGate(OPEN_FOLDER, { failEndpoints: ['getSessionPromptState'] })
482
+ await settle(element)
483
+ for (const delay of [1000, 2000, 4000, 8000, 16000, 30000, 30000]) {
484
+ const before = lastRuntime.stateCalls
485
+ lastRuntime.sessions['sess-1'] = { ...lastRuntime.sessions['sess-1'], title: String(before) }
486
+ await live(element)
487
+ t.mock.timers.tick(delay - 1)
488
+ await live(element)
489
+ assert.equal(lastRuntime.stateCalls, before, 'a list refresh bypassed backoff')
490
+ t.mock.timers.tick(1)
491
+ await live(element)
492
+ assert.equal(lastRuntime.stateCalls, before + 1)
493
+ }
494
+ lastRuntime.failEndpoints.clear()
495
+ t.mock.timers.tick(30000)
496
+ assert.ok(await live(element), 'the still-mounted gate did not recover')
497
+ })
498
+
499
+ test('a failed silent init also retains its backoff across successful state reads', async (t) => {
500
+ t.mock.timers.enable({ apis: ['setTimeout', 'Date'] })
501
+ const element = renderGate({ ...OPEN_FOLDER, shouldPrompt: false }, { failEndpoints: ['initSession'] })
502
+ await settle(element)
503
+ for (const delay of [1000, 2000]) { t.mock.timers.tick(delay); await live(element) }
504
+ assert.equal(lastRuntime.stateCalls, 3)
505
+ t.mock.timers.tick(3999)
506
+ await live(element)
507
+ assert.equal(lastRuntime.stateCalls, 3)
508
+ lastRuntime.failEndpoints.clear()
509
+ t.mock.timers.tick(1)
510
+ assert.equal(await live(element), null)
511
+ assert.equal(lastRuntime.stateCalls, 4)
512
+ assert.equal(calls.filter((call) => call.endpoint === 'setSessionScope').length, 1)
513
+ })
514
+
515
+ test('switching away or unmounting cancels retry timers even when logging fails', async (t) => {
516
+ t.mock.timers.enable({ apis: ['setTimeout', 'Date'] })
517
+ const element = renderGate(OPEN_FOLDER, { failEndpoints: ['getSessionPromptState', 'logClientEvent'] })
518
+ await settle(element)
519
+ lastRuntime.current = null
520
+ await live(element)
521
+ t.mock.timers.tick(60000)
522
+ await tick()
523
+ assert.equal(lastRuntime.stateCalls, 1)
524
+ lastRuntime.current = 'sess-1'
525
+ await live(element)
526
+ assert.equal(lastRuntime.stateCalls, 2)
527
+ unmount()
528
+ t.mock.timers.tick(60000)
529
+ await tick()
530
+ assert.equal(lastRuntime.stateCalls, 2)
531
+ })
532
+
533
+ test('an implicit binding still asks on a blank session; a chosen one does not', async () => {
534
+ const implicit = {
535
+ ...OPEN_FOLDER,
536
+ binding: { scopeKey: '/ws/demo', domainOverride: 'rp', domainSource: 'auto', useLibrary: true, useGlobal: true, libraryId: 'lib-1' },
537
+ }
538
+ const { tree } = await settle(renderGate(implicit))
539
+ assert.ok(tree, 'an implicit (injection-path) binding silenced the prompt on a still-blank session')
540
+
541
+ const chosen = { ...implicit, binding: { ...implicit.binding, domainSource: 'chosen' } }
542
+ const { tree: chosenTree } = await settle(renderGate(chosen))
543
+ assert.equal(chosenTree, null, 'an explicitly chosen binding was asked again')
544
+ })
545
+
546
+ test('a first message before cwd arrives does not lose the pending domain question', async () => {
547
+ const implicit = { ...OPEN_FOLDER, binding: { scopeKey: '/ws/demo', domainOverride: 'coding', domainSource: 'auto' } }
548
+ const element = renderGate(implicit, { sessions: { 'sess-1': { blank: true, origin: 'user' } } })
549
+ assert.equal(await live(element), null)
550
+ assert.equal(lastRuntime.stateCalls, 0)
551
+ lastRuntime.sessions['sess-1'] = { cwd: '/ws/demo', blank: false, origin: 'user' }
552
+ const tree = await live(element)
553
+ assert.ok(tree, 'blank=false must not discard a new session that has not answered')
554
+ assert.equal(lastRuntime.stateCalls, 1)
555
+ findNode(tree, (node) => node.type === 'select').props.onChange({ target: { value: 'coding' } })
556
+ await findNode(paint(element), (node) => node.props?.key === 'ok').props.onClick()
557
+ assert.equal(calls.find((call) => call.endpoint === 'setDomain')?.payload.domain, 'coding')
558
+ })
559
+
560
+ for (const summary of [{ blank: false, origin: 'user' }, { blank: true, origin: 'subagent' }]) {
561
+ test('historical sessions and subagents do not become newly pending: ' + JSON.stringify(summary), async () => {
562
+ const element = renderGate({ ...OPEN_FOLDER, binding: { domainSource: 'auto' } }, {
563
+ sessions: { 'sess-1': { cwd: '/ws/demo', ...summary } },
564
+ })
565
+ assert.equal(await live(element), null)
566
+ assert.equal(lastRuntime.stateCalls, 0)
567
+ })
568
+ }
569
+
570
+ test('leaving the session view also releases a Later choice', async () => {
571
+ const element = renderGate(OPEN_FOLDER)
572
+ const tree = await live(element)
573
+ await findNode(tree, (node) => node.props?.key === 'later').props.onClick()
574
+ await live(element)
575
+ lastRuntime.current = null
576
+ assert.equal(await live(element), null)
577
+ lastRuntime.current = 'sess-1'
578
+ assert.ok(await live(element))
579
+ })
580
+
581
+ for (const outcome of ['resolve', 'reject']) {
582
+ test('a late RPC ' + outcome + ' from a departed session cannot change the current prompt', async () => {
583
+ let complete
584
+ const element = renderGate(() => new Promise((resolve, reject) => {
585
+ complete = () => outcome === 'resolve' ? resolve(OPEN_FOLDER) : reject(new Error('late failure'))
586
+ }))
587
+ await live(element)
588
+ lastRuntime.sessions['sess-0'] = { cwd: '/ws/demo', blank: false, origin: 'user' }
589
+ lastRuntime.current = 'sess-0'
590
+ await live(element)
591
+ complete()
592
+ assert.equal(await live(element), null)
593
+ assert.equal(calls.length, 0, 'a cancelled check must not log or commit a decision')
594
+ })
595
+ }
596
+
597
+ test('summary refresh and the first message preserve an open prompt selection', async () => {
598
+ const element = renderGate(OPEN_FOLDER)
599
+ const tree = await live(element)
600
+ findNode(tree, (node) => node.type === 'select').props.onChange({ target: { value: 'coding' } })
601
+ lastRuntime.sessions['sess-1'] = { cwd: '/ws/demo', blank: false, origin: 'user', title: 'first message' }
602
+ const refreshed = await live(element)
603
+ assert.equal(findNode(refreshed, (node) => node.type === 'select').props.value, 'coding')
604
+ assert.equal(lastRuntime.stateCalls, 1)
605
+ })
606
+
607
+ test('a remembered answer binds silently even when the binding is implicit', async () => {
608
+ const remembered = {
609
+ ...OPEN_FOLDER,
610
+ binding: { scopeKey: '/ws/demo', domainOverride: 'rp', domainSource: 'auto', useLibrary: true, useGlobal: true, libraryId: 'lib-1' },
611
+ settings: { newSessionPromptDismissed: true, newSessionDefault: 'both' },
612
+ }
613
+ const { tree } = await settle(renderGate(remembered))
614
+ assert.equal(tree, null, 'the remembered answer still opened the prompt')
615
+ assert.deepEqual(calls.map((call) => call.endpoint), ['initSession', 'setSessionScope'])
616
+ })
@@ -5,12 +5,19 @@ import os from 'node:os'
5
5
  import path from 'node:path'
6
6
 
7
7
  const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-loop-date-'))
8
+ process.env.DSH_HOME = home
8
9
  process.env.DSH_MEMU_HOME = home
10
+ process.env.DSH_MEMU_MEMORY_HOME = home
9
11
 
10
12
  const state = await import('../lib/state.js')
11
13
  const memory = await import('../lib/memory.js')
12
14
  const inject = await import('../lib/inject.js')
13
15
  const { estTokens } = await import('../lib/budget.js')
16
+ const handlers = new Map()
17
+ inject.registerInjection({ on: (name, handler) => { handlers.set(name, handler); return () => {} }, logger: { warn() {} } })
18
+ async function admit(sessionId, out) {
19
+ for (const message of out.messages || []) if (message.role === 'user') await handlers.get('session/event')({ header: { id: sessionId } }, { type: 'user/message', data: message })
20
+ }
14
21
 
15
22
  test.after(() => {
16
23
  try { state.flushState() } catch {}
@@ -349,6 +356,7 @@ test('a budget-dropped anniversary does not silence the nudge (injectForStep)',
349
356
  assert.ok(text.includes('mem-said'))
350
357
  assert.equal(state.getSessionBinding(sessionId).openLoopRemindedAt?.['mem-said'], undefined,
351
358
  'the regular leg does not write the recurring clock')
359
+ await admit(sessionId, out)
352
360
  } finally {
353
361
  state.updateSettings({ injectionTotalTokens: 2000 })
354
362
  }
@@ -394,8 +402,10 @@ test('injectForStep records the overdue reminder only after the block is really
394
402
  .join('\n\n')
395
403
  assert.match(text, /\[open loop\]/)
396
404
  assert.ok(text.includes('mem-recurring'))
405
+ assert.equal(state.wasOpenLoopRemindedToday(sessionId, 'mem-recurring', new Date()), false, 'a proposal does not consume the reminder clock')
406
+ await admit(sessionId, out)
397
407
  assert.equal(state.wasOpenLoopRemindedToday(sessionId, 'mem-recurring', new Date()), true,
398
- 'the clock starts once the reminder reached the prompt')
408
+ 'the clock starts once the reminder entered host history')
399
409
 
400
410
  const again = await inject.injectForStep({ ...step, turn: 2, step: 1, signal: { aborted: false } })
401
411
  const againText = (again.messages || [])
@@ -5,7 +5,9 @@ import os from 'node:os'
5
5
  import path from 'node:path'
6
6
 
7
7
  const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-recall-intent-'))
8
+ process.env.DSH_HOME = home
8
9
  process.env.DSH_MEMU_HOME = home
10
+ process.env.DSH_MEMU_MEMORY_HOME = home
9
11
 
10
12
  const state = await import('../lib/state.js')
11
13
  const memory = await import('../lib/memory.js')
@@ -26,7 +28,44 @@ function session(name) {
26
28
  }
27
29
  }
28
30
 
29
- test('a date question raises the candidate count; a general question keeps the requested topK', async () => {
31
+ test('style removal preserves dotted identifiers, URLs, decimals and line separators in topic evidence', async () => {
32
+ const { exec, sessionId } = session('ranking-topic-text')
33
+ const previous = state.getSettings().crossLibraryRecall
34
+ state.updateSettings({ crossLibraryRecall: false })
35
+ try {
36
+ for (const topic of ['node.js', 'release-1.2', 'https://example.test/a', 'version 1.25', 'runtime\npackage']) {
37
+ state.savePrivateIndex(state.getSessionBinding(sessionId).libraryId, { entries: {
38
+ 'mem-topic-text': { title: topic, content: topic, status: 'active', layer: 'long_term', strength: 1 },
39
+ } })
40
+ const plain = await memory.privateRecall({ exec, query: topic, relevanceThreshold: 0 })
41
+ const styled = await memory.privateRecall({ exec, query: topic + '。请简洁回答。', relevanceThreshold: 0 })
42
+ assert.equal(styled.files[0]?.name, 'mem-topic-text')
43
+ assert.ok(plain.files[0].lexicalEvidence > 0)
44
+ assert.equal(styled.files[0].lexicalEvidence, plain.files[0].lexicalEvidence, topic)
45
+ }
46
+ } finally { state.updateSettings({ crossLibraryRecall: previous }) }
47
+ })
48
+
49
+ test('lexical dominance evidence excludes the date boost consistently with and without style text', async () => {
50
+ const { exec, sessionId } = session('ranking-date-evidence')
51
+ const previous = state.getSettings().crossLibraryRecall
52
+ state.updateSettings({ crossLibraryRecall: false })
53
+ try {
54
+ state.savePrivateIndex(state.getSessionBinding(sessionId).libraryId, { entries: {
55
+ 'mem-date-evidence': { title: 'production release', content: 'release schedule', absolute_date: '2026-11-18', status: 'active', layer: 'long_term', strength: 1 },
56
+ } })
57
+ const plain = await memory.privateRecall({ exec, query: 'release 2026-11-18', relevanceThreshold: 0 })
58
+ const styled = await memory.privateRecall({ exec, query: 'release 2026-11-18。请简洁回答。', relevanceThreshold: 0 })
59
+ const a = plain.files.find(file => file.name === 'mem-date-evidence')
60
+ const b = styled.files.find(file => file.name === 'mem-date-evidence')
61
+ assert.ok(a && b)
62
+ assert.ok(Math.abs(a.lexical - a.lexicalEvidence * 1.35) < 1e-10)
63
+ assert.ok(Math.abs(b.lexical - b.lexicalEvidence * 1.35) < 1e-10)
64
+ assert.equal(b.lexicalEvidence, a.lexicalEvidence)
65
+ } finally { state.updateSettings({ crossLibraryRecall: previous }) }
66
+ })
67
+
68
+ test('date intent expands candidates but explicit topK remains a hard row limit', async () => {
30
69
  const { exec } = session('intent-topk')
31
70
  const topics = ['灯光', '投影仪', '白板', '咖啡机', '门禁', '椅子', '窗帘', '空调', '插座', '网络', '打印纸', '绿植']
32
71
  for (const [index, topic] of topics.entries()) {
@@ -41,8 +80,18 @@ test('a date question raises the candidate count; a general question keeps the r
41
80
  assert.equal(general.files.length, 3, 'general respects the requested three')
42
81
 
43
82
  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)
83
+ assert.ok(dated.files.length <= 3, 'explicit date search does not silently enlarge topK')
84
+ assert.equal(dated.trace.request.requestedTopK, 3)
85
+ assert.equal(dated.trace.request.candidateTopK, 8)
86
+ const automatic = await memory.privateRecall({ exec, query: '会议什么时候开', topK: 3, relevanceThreshold: 0, purpose: 'automatic' })
87
+ assert.ok(automatic.groups.length <= 3, 'automatic intent expands candidates, not the configured group limit')
88
+ assert.ok(automatic.files.length <= 3)
89
+ assert.equal(automatic.trace.request.candidateTopK, 8)
90
+ assert.equal(automatic.trace.request.maxGroups, 3)
91
+ for (const query of ['会议什么时候开', '会议人物是谁', '会议有矛盾冲突', '会议']) {
92
+ const one = await memory.privateRecall({ exec, query, topK: 1, relevanceThreshold: 0 })
93
+ assert.ok(one.files.length <= 1, query)
94
+ }
46
95
  })
47
96
 
48
97
  test('one-hop expansion follows an explicit link to a memory the query never matched', async () => {