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,153 @@
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-slots-'))
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 similarity = await import('../lib/text-similarity.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: 'coding' })
24
+ return {
25
+ sessionId,
26
+ libraryId: state.getSessionBinding(sessionId).libraryId,
27
+ exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'coding' } } } },
28
+ }
29
+ }
30
+
31
+ const LOAN_A = '图书馆借阅规则:每人每次最多借五本书,借期十四天,可以续借一次,逾期按天收取滞纳金,闭馆日不办理。'
32
+ const LOAN_B = '图书馆借阅规则:每人每次最多借七本书,借期十四天,可以续借一次,逾期按天收取滞纳金,闭馆日不办理。'
33
+
34
+ test('numbers, dates, times, weekdays and quoted names are slot conflicts', () => {
35
+ const cases = [
36
+ [LOAN_A, LOAN_B],
37
+ ['复诊安排在2026-11-08上午十点。', '复诊安排在2026-11-15上午十点。'],
38
+ ['每周一上午九点开会。', '每周二上午九点开会。'],
39
+ ['他说“林眠”明天会来,而且会带伞。', '他说“Yuike”明天会来,而且会带伞。'],
40
+ ]
41
+ for (const [a, b] of cases) {
42
+ const detail = similarity.similarityDetail(a, b)
43
+ assert.equal(detail.slotConflict, true, a.slice(0, 18))
44
+ assert.ok(detail.dice >= similarity.TOPIC_DICE, 'fixture must be similar enough to inspect slots')
45
+ assert.ok(similarity.similarTexts(a, b) < similarity.TOPIC_DICE, 'slot conflict must fall below the topic band')
46
+ }
47
+ assert.deepEqual(similarity.slotSignature('借五本书,等十五天').numbers.sort(), ['15', '5'])
48
+ })
49
+
50
+ test('same slots and added numbers are not capped', () => {
51
+ assert.equal(similarity.similarityDetail(LOAN_A, LOAN_A).slotConflict, false)
52
+ const same = '图书馆借阅规则:每人每次最多借五本书,借期十四天。'
53
+ const added = '图书馆借阅规则:每人每次最多借五本书,借期十四天,押金二十元,每人限办一张卡。'
54
+ const detail = similarity.similarityDetail(same, added)
55
+ assert.equal(detail.slotConflict, false, 'an added number is an enrichment, not a contradiction')
56
+ assert.equal(similarity.similarTexts(same, added), Math.max(detail.dice, detail.containment))
57
+ // Totally unrelated text never pays for slot extraction and is not a conflict.
58
+ assert.equal(similarity.similarityDetail('窗外的雨停了。', '图书馆周三闭馆。').slotConflict, false)
59
+ })
60
+
61
+ test('different-title facts that only change a number both stay active', async () => {
62
+ const { exec, libraryId } = session('slot-write')
63
+ const first = await memory.privateRemember({ exec, title: '借阅上限', content: LOAN_A })
64
+ const raw = similarity.similarityDetail(LOAN_A, LOAN_B)
65
+ assert.ok(raw.dice >= similarity.DUP_REJECT_DICE, 'fixture must sit in the old reject band, got ' + raw.dice)
66
+ assert.equal(raw.slotConflict, true)
67
+ const second = await memory.privateRemember({ exec, title: '借阅额度', content: LOAN_B })
68
+ assert.equal(second.deduped, undefined)
69
+ assert.equal(second.entry.status, 'active')
70
+ assert.equal(second.entry.duplicateOf, undefined)
71
+ const index = state.loadPrivateIndex(libraryId)
72
+ assert.equal(Object.keys(index.entries).length, 2)
73
+ assert.equal(index.entries[first.id].status, 'active')
74
+ assert.equal(index.entries[second.id].content, LOAN_B)
75
+ })
76
+
77
+ test('same title + changed number is held as a conflict, not swallowed as duplicate', async () => {
78
+ const { exec, libraryId } = session('slot-same-title')
79
+ const first = await memory.privateRemember({ exec, title: '借阅上限', content: LOAN_A })
80
+ const second = await memory.privateRemember({ exec, title: '借阅上限', content: LOAN_B })
81
+ assert.equal(second.conflict, first.id, 'same-title slot correction must be a conflict')
82
+ const index = state.loadPrivateIndex(libraryId)
83
+ assert.equal(index.entries[second.id].status, 'pending_review')
84
+ assert.match(index.entries[second.id].reviewReason, /slot|说法|同题/)
85
+ assert.equal(index.entries[second.id].content, LOAN_B, 'the corrected text is preserved')
86
+ })
87
+
88
+ test('an update that only changes a number is not refused as a duplicate', async () => {
89
+ const { exec, libraryId } = session('slot-update')
90
+ const index = state.loadPrivateIndex(libraryId)
91
+ const now = new Date().toISOString()
92
+ index.entries['mem-host'] = {
93
+ title: '借阅上限', content: LOAN_A,
94
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
95
+ }
96
+ index.entries['mem-target'] = {
97
+ title: '借阅额度备注', content: '这条先占位,稍后改成正式规则。',
98
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
99
+ }
100
+ state.savePrivateIndex(libraryId, index)
101
+ const updated = await memory.privateUpdate({ exec, id: 'mem-target', content: LOAN_B })
102
+ assert.equal(updated.entry.content, LOAN_B)
103
+ assert.equal(updated.entry.status, 'active')
104
+ assert.equal(updated.entry.duplicateOf, undefined, 'a slot change is a different fact, not a duplicate')
105
+ })
106
+
107
+ test('recall keeps same-template different-number facts in separate seats', async () => {
108
+ const { exec, libraryId } = session('slot-recall')
109
+ const index = state.loadPrivateIndex(libraryId)
110
+ const now = new Date().toISOString()
111
+ index.entries['mem-five'] = {
112
+ title: '借阅上限五本', content: LOAN_A,
113
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
114
+ }
115
+ index.entries['mem-seven'] = {
116
+ title: '借阅上限七本', content: LOAN_B,
117
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
118
+ }
119
+ state.savePrivateIndex(libraryId, index)
120
+ const raw = similarity.similarityDetail(LOAN_A, LOAN_B)
121
+ assert.ok(raw.dice >= similarity.DUP_DICE, 'fixture must be in the old folding band')
122
+ const recalled = await memory.privateRecall({ exec, query: '图书馆借阅规则', topK: 10, relevanceThreshold: 0 })
123
+ const ids = recalled.files.map((file) => file.name)
124
+ assert.ok(ids.includes('mem-five') && ids.includes('mem-seven'), 'distinct facts must keep two seats')
125
+ assert.deepEqual(recalled.dedup?.collapsed || [], [], 'the pair must not be folded')
126
+ })
127
+
128
+ test('A-10: similarity thresholds have a single source; compat exports keep their values', () => {
129
+ assert.deepEqual(similarity.SIMILARITY_THRESHOLDS, {
130
+ duplicateDice: 0.82,
131
+ rejectDice: 0.90,
132
+ topicDice: 0.55,
133
+ lengthPruneRatio: 0.5,
134
+ containmentFloor: 0.92,
135
+ probeMinChars: 6,
136
+ probeMaxChars: 240,
137
+ })
138
+ assert.equal(similarity.DUP_DICE, similarity.SIMILARITY_THRESHOLDS.duplicateDice)
139
+ assert.equal(similarity.DUP_REJECT_DICE, similarity.SIMILARITY_THRESHOLDS.rejectDice)
140
+ assert.equal(similarity.TOPIC_DICE, similarity.SIMILARITY_THRESHOLDS.topicDice)
141
+ assert.equal(similarity.LENGTH_PRUNE_RATIO, similarity.SIMILARITY_THRESHOLDS.lengthPruneRatio)
142
+ assert.equal(similarity.CONTAINMENT_FLOOR, similarity.SIMILARITY_THRESHOLDS.containmentFloor)
143
+ assert.equal(similarity.CORE_COVER_FLOOR, similarity.SIMILARITY_THRESHOLDS.rejectDice)
144
+ for (const value of [similarity.DUP_DICE, similarity.DUP_REJECT_DICE, similarity.TOPIC_DICE, similarity.CONTAINMENT_FLOOR]) {
145
+ assert.equal(typeof value, 'number', 'compat exports stay plain numbers')
146
+ }
147
+ })
148
+
149
+ test('D-21: jaccard is exported from the shared ruler with the old formula', () => {
150
+ assert.equal(similarity.jaccard(new Set(), new Set(['a'])), 0)
151
+ assert.equal(similarity.jaccard(new Set(['a', 'b']), new Set(['b', 'c'])), 1 / 3)
152
+ assert.equal(similarity.jaccard(new Set(['a', 'b']), new Set(['a', 'b'])), 1)
153
+ })
@@ -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,34 @@
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-gc-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const state = await import('../lib/state.js')
11
+
12
+ test.after(() => {
13
+ state.flushState()
14
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
15
+ })
16
+
17
+ test('session-binding GC is dry-run first and skips bindings without a clock', async () => {
18
+ state.ensureSession('gc-old', { cwd: path.join(home, 'old') })
19
+ state.setSessionBinding('gc-old', { lastTurnAt: '2020-01-01T00:00:00.000Z' })
20
+ state.ensureSession('gc-new', { cwd: path.join(home, 'new') })
21
+ state.setSessionBinding('gc-new', { lastTurnAt: new Date().toISOString() })
22
+ state.ensureSession('gc-noclock', { cwd: path.join(home, 'noclock') })
23
+
24
+ const dry = state.pruneSessionBindings({ olderThanDays: 30 })
25
+ assert.equal(dry.dryRun, true)
26
+ assert.deepEqual(dry.candidates.map((item) => item.sessionId), ['gc-old'])
27
+ assert.ok(state.getSessionBinding('gc-old'), 'dry-run must not remove')
28
+
29
+ const applied = state.pruneSessionBindings({ olderThanDays: 30, dryRun: false })
30
+ assert.deepEqual(applied.removed, ['gc-old'])
31
+ assert.equal(state.getSessionBinding('gc-old'), null)
32
+ assert.ok(state.getSessionBinding('gc-new'), 'a recent binding survives')
33
+ assert.ok(state.getSessionBinding('gc-noclock'), 'a binding without lastTurnAt is never guessed away')
34
+ })
@@ -56,8 +56,8 @@ test('the unpin marker is gone from session bindings', () => {
56
56
  assert.equal(typeof state.consumeTrauma, 'undefined')
57
57
  })
58
58
 
59
- test('backup creates a timestamped directory', () => {
60
- const dest = state.backupDatabases()
59
+ test('backup creates a timestamped directory', async () => {
60
+ const dest = await state.backupDatabases()
61
61
  assert.ok(fs.existsSync(dest))
62
62
  assert.ok(fs.existsSync(path.join(dest, 'index')))
63
63
  })
@@ -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
+ })
@@ -5,9 +5,9 @@ import {
5
5
  tokenize,
6
6
  tokenizeStats,
7
7
  tokenizeV2,
8
- TEST_CASES,
9
8
  tokenStreamV2,
10
9
  } from '../lib/tokenizer-v2.js'
10
+ import { TEST_CASES } from './fixtures/tokenizer-cases.mjs'
11
11
 
12
12
  // —— 召回升级 P0-1:Tokenizer V2(CJK 三层 n-gram + 实体保护)——
13
13
  // 开关在 lib/curator-policy.js(TOKENIZER_V2);这里测 V2 本身的行为契约。
@@ -0,0 +1,37 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import { vectorGcCandidates } from '../lib/vector-profile.js'
5
+
6
+ const DAY = 86_400_000
7
+ const NOW = 1_800_000_000_000
8
+
9
+ test('vector GC keeps active/pending paths and the last N generations', () => {
10
+ const old = NOW - 40 * DAY
11
+ const files = [
12
+ { file: 'global.aaaa.g1.sqlite3', generation: 1, bytes: 10, mtimeMs: old },
13
+ { file: 'global.aaaa.g2.sqlite3', generation: 2, bytes: 10, mtimeMs: old },
14
+ { file: 'global.aaaa.g3.sqlite3', generation: 3, bytes: 10, mtimeMs: old },
15
+ { file: 'vector-ledger.aaaa.g1.json', generation: 1, bytes: 10, mtimeMs: old },
16
+ { file: 'legacy.sqlite3', generation: null, bytes: 10, mtimeMs: old },
17
+ ]
18
+ const candidates = vectorGcCandidates({
19
+ files, activeGeneration: 3, keepGenerations: 2, olderThanDays: 7, now: NOW,
20
+ })
21
+ assert.deepEqual(candidates.map((item) => item.file).sort(), [
22
+ 'global.aaaa.g1.sqlite3',
23
+ 'vector-ledger.aaaa.g1.json',
24
+ ])
25
+
26
+ const kept = vectorGcCandidates({
27
+ files, activeGeneration: 3, keepGenerations: 2, olderThanDays: 7, now: NOW,
28
+ keepPaths: ['global.aaaa.g1.sqlite3'],
29
+ })
30
+ assert.deepEqual(kept.map((item) => item.file), ['vector-ledger.aaaa.g1.json'])
31
+
32
+ const recent = vectorGcCandidates({
33
+ files: [{ file: 'global.aaaa.g1.sqlite3', generation: 1, bytes: 10, mtimeMs: NOW - DAY }],
34
+ activeGeneration: 3, keepGenerations: 2, olderThanDays: 7, now: NOW,
35
+ })
36
+ assert.deepEqual(recent, [], 'a recent old generation is left for the retention window')
37
+ })
@@ -135,6 +135,33 @@ test('wall heartbeat retries failed paints, pauses hidden and shares the metadat
135
135
  assert.match(source, /data\.type === "memory-write"/)
136
136
  })
137
137
 
138
+ test('fullscreen wall avoids the WebView2 compositor traps that dropped cards', () => {
139
+ const client = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
140
+ // The overlay is a full-viewport iframe over the host app. A backdrop-filter on
141
+ // that wrapper (and a transparent iframe background) made WebView2 re-blur the
142
+ // whole host on every repaint; at fullscreen it started dropping wall tiles.
143
+ const overlay = client.slice(client.indexOf('function toggleWebUiOverlay'), client.indexOf('function glyph'))
144
+ assert.ok(!/backdrop-filter\s*:/.test(overlay), 'the overlay wrapper must not blur the host behind the iframe')
145
+ assert.match(overlay, /background:var\(--dsw-alias-bg-base, #f4f5f9\)/, 'the iframe stays opaque while its page paints')
146
+ // Late replies must not repaint the wall/browser after a newer library was picked.
147
+ assert.match(client, /const requestId = \+\+browseRequest\.current/)
148
+ assert.match(client, /const requestId = \+\+browseLibraryRequest\.current/)
149
+ assert.match(client, /const requestId = \+\+statsRequest\.current/)
150
+ assert.match(client, /const requestId = \+\+reviewsRequest\.current/)
151
+ assert.match(client, /if \(!current\(\)\) return/, 'stale browseWall replies are dropped')
152
+
153
+ const css = fs.readFileSync(new URL('../lib/webui/standalone.css', import.meta.url), 'utf8')
154
+ const start = css.indexOf('html[data-standalone] .dshm-wall-item {')
155
+ const wall = css.slice(start, css.indexOf('html[data-standalone] .dshm-wall-item:hover'))
156
+ assert.ok(!/backdrop-filter\s*:/.test(wall), 'wall cards must not stack dozens of blur layers on screen')
157
+ assert.match(wall, /content-visibility: auto/, 'off-screen wall rows stay out of the paint path')
158
+
159
+ const standalone = fs.readFileSync(new URL('../lib/webui/standalone.js', import.meta.url), 'utf8')
160
+ assert.match(standalone, /var spot = document\.querySelector\('\.ambient-spot'\)/)
161
+ assert.match(standalone, /\(spot \|\| document\.documentElement\)\.style/, 'pointer moves only invalidate the spotlight element')
162
+ assert.match(standalone, /if \(!framed && !reduceMotion/, 'the iframe overlay does not repaint a full-screen spotlight')
163
+ })
164
+
138
165
  test('single-library browseWall still carries global rows and F1/F2 metadata', async () => {
139
166
  const library = state.createLibrary({ name: 'wall-global-merge', cwd: path.join(home, 'wall-global-merge') })
140
167
  state.updatePrivateIndex(library.id, (index) => {