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
@@ -0,0 +1,281 @@
1
+ // Issue #4 / #5(dsh-memu-memory#4、#5)的 sweep 全链路模拟:
2
+ // #5 冷掉的 inbound.pending 残骸不再永久阻断空闲整理,热队列仍然让路;
3
+ // #4-1 snapshot-failed 熔断不再返回 settled:true(游标不推平、错误不清零)、
4
+ // 冻结期内活动日志去重、冷却到期自动放行真实重试;
5
+ // #4-2 多窗整理 remaining>0 时粗游标不推平,尾段 <200 事件由下一扫收口;
6
+ // #4-3 归档会话在候选阶段事前跳过,手动整理返回明确的 session-archived。
7
+ // 全部走 runSleepPass → requestPrivateConsolidation → fork → 回执 → 账本 的真实链路。
8
+ import test from 'node:test'
9
+ import assert from 'node:assert/strict'
10
+ import fs from 'node:fs'
11
+ import os from 'node:os'
12
+ import path from 'node:path'
13
+
14
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-sweep-issues-'))
15
+ process.env.DSH_MEMU_HOME = home
16
+
17
+ const state = await import('../lib/state.js')
18
+ const cycle = await import('../lib/cycle.js')
19
+ const privateLib = await import('../lib/private.js')
20
+ const ledger = await import('../lib/consolidation-ledger.js')
21
+ const activityLog = await import('../lib/activity-log.js')
22
+
23
+ test.after(() => {
24
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
25
+ })
26
+
27
+ function touchAgo(sessionId, minutesAgo) {
28
+ state.setSessionBinding(sessionId, { lastTurnAt: new Date(Date.now() - minutesAgo * 60_000).toISOString() })
29
+ }
30
+
31
+ // 与 cycle.test.mjs 的 fakeCtx 同款,外加三个旋钮:
32
+ // receipts: 'full'(回执覆盖整段转录,默认)/ 'window'(回执只覆盖本窗种子,
33
+ // 用来模拟多窗的第一窗)/ 'error'(turn 以 error 收尾,走 failJob 退避)。
34
+ // archived: 宿主 workspaceRegistry 的 archivedSessionIds。
35
+ // events: 会话转录(默认一段最小真人对话)。
36
+ function fakeCtx({ live = [], receipts = 'full', archived = [], events = null, inbound = {} } = {}) {
37
+ const liveSet = new Set(live)
38
+ const created = []
39
+ const disposed = []
40
+ const forkFollowups = []
41
+ const sessionHandlers = []
42
+ const transcript = events || [
43
+ { seq: 0, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '帮我看一下这个插件为什么空闲整理从来没跑过,日志里只有 skip 一行' }] } },
44
+ { seq: 1, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '排查结果:inbound 队列里留着召回异常的残骸,把会话挡住了。' }] } } },
45
+ { seq: 2, type: 'turn/end', data: { turn: 0, reason: { kind: 'completed' } } },
46
+ ]
47
+ const ctx = {
48
+ created, disposed, forkFollowups,
49
+ on: (name, handler) => {
50
+ if (name !== 'session/event') return () => {}
51
+ sessionHandlers.push(handler)
52
+ return () => {
53
+ const index = sessionHandlers.indexOf(handler)
54
+ if (index >= 0) sessionHandlers.splice(index, 1)
55
+ }
56
+ },
57
+ get: (name) => {
58
+ if (name === 'agents') {
59
+ return {
60
+ get: (id) => (liveSet.has(id)
61
+ ? { options: { provider: 'test-provider', model: 'test-model' } }
62
+ : undefined),
63
+ create: async (spec) => {
64
+ created.push(spec)
65
+ const childSession = { id: spec.sessionId }
66
+ return {
67
+ agent: {
68
+ session: childSession,
69
+ followup: (message) => {
70
+ forkFollowups.push({ child: spec.sessionId, message })
71
+ if (receipts === 'error') {
72
+ for (const handler of sessionHandlers) {
73
+ handler(childSession, { type: 'assistant/message', seq: 99, data: { message: { content: [{ type: 'text', text: 'worker turn blew up' }] } } })
74
+ handler(childSession, { type: 'turn/end', seq: 100, data: { turn: 1, reason: { kind: 'error', error: { message: 'the fork turn ended error: simulated' } } } })
75
+ }
76
+ return
77
+ }
78
+ // 回执的 checkedRange:full = 整段转录;window = 本窗(多窗第一窗)。
79
+ // 窗口边界用与 private.js 相同的 selectConsolidationWindow 计算——
80
+ // seed.lastSeq 只是最后一个「对话」事件的 seq(todo/write 不进 seed),
81
+ // 不是窗口边界。
82
+ const childBinding = state.getSessionBinding(spec.sessionId)
83
+ const throughSeq = receipts === 'window'
84
+ ? privateLib.selectConsolidationWindow(transcript, privateLib.CONSOLIDATION_WINDOW_EVENTS).throughSeq
85
+ : transcript[transcript.length - 1].seq
86
+ const proof = {
87
+ version: 1,
88
+ jobId: childBinding.jobId,
89
+ snapshotHash: childBinding.snapshotHash,
90
+ status: 'completed',
91
+ outcome: 'no_value',
92
+ checkedRange: { fromSeq: spec.seed?.fromSeq ?? 0, throughSeq },
93
+ createdIds: [], updatedIds: [], heldIds: [],
94
+ }
95
+ const tick = '```'
96
+ for (const handler of sessionHandlers) {
97
+ handler(childSession, { type: 'assistant/message', seq: 99, data: { message: { content: [{ type: 'text', text: tick + 'memu-consolidation-receipt\n' + JSON.stringify(proof) + '\n' + tick }] } } })
98
+ handler(childSession, { type: 'turn/end', seq: 100, data: { turn: 1, reason: { kind: 'completed' } } })
99
+ }
100
+ },
101
+ whenIdle: async () => {},
102
+ },
103
+ dispose: async () => { disposed.push(spec.sessionId) },
104
+ }
105
+ },
106
+ }
107
+ }
108
+ if (name === 'sessionQuery') {
109
+ return {
110
+ readSession: async () => ({ events: transcript, session: { cwd: path.join(home, 'p'), agentPreset: 'rp' } }),
111
+ }
112
+ }
113
+ if (name === 'workspaceRegistry') return { archivedSessionIds: archived }
114
+ return undefined
115
+ },
116
+ }
117
+ return ctx
118
+ }
119
+
120
+ function ensureIdle(id, { minutesAgo = 60, inbound = null, lastInboundMinutesAgo = null } = {}) {
121
+ state.ensureSession(id, { cwd: path.join(home, 'p-' + id), agentPreset: 'rp' })
122
+ touchAgo(id, minutesAgo)
123
+ if (inbound) {
124
+ const ago = (m) => new Date(Date.now() - m * 60_000).toISOString()
125
+ state.setSessionBinding(id, {
126
+ inbound,
127
+ ...(lastInboundMinutesAgo !== null ? {
128
+ lastInboundAt: ago(lastInboundMinutesAgo),
129
+ lastInboundOutcome: { reason: 'error', at: ago(lastInboundMinutesAgo), count: inbound.pending.length, injectedCount: 0 },
130
+ } : {}),
131
+ })
132
+ }
133
+ }
134
+
135
+ // 失败后的两条退避时钟都清掉(binding.sleepRetryAt + 账本 entry.retryAt),
136
+ // 让下一扫立刻有资格再次进入,模拟「退避到期后」的时序。
137
+ function clearBackoffs(sessionId) {
138
+ state.setSessionBinding(sessionId, { sleepRetryAt: null, sleepAttempts: 0 })
139
+ patchLedger(sessionId, (entry) => { entry.retryAt = null })
140
+ }
141
+
142
+ // 直接编辑 consolidation.json(mutateLedger 未导出;测试只改自家临时目录里的文件)。
143
+ function patchLedger(sessionId, patch) {
144
+ const file = ledger.ledgerPath()
145
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'))
146
+ patch(raw.sessions[sessionId])
147
+ fs.writeFileSync(file, JSON.stringify(raw, null, 2), 'utf8')
148
+ }
149
+
150
+ // —— Issue #5:inbound.pending 热窗 ——
151
+
152
+ test('issue #5: a hot inbound queue still defers the sweep', async () => {
153
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 10 })
154
+ ensureIdle('issue5-hot', { minutesAgo: 30, inbound: { pending: [{ key: 'k1' }], retryAt: new Date(Date.now() + 20_000).toISOString() }, lastInboundMinutesAgo: 1 })
155
+ const out = await cycle.runSleepPass(fakeCtx({ live: ['issue5-hot'] }))
156
+ assert.equal(out.ran, 0)
157
+ assert.equal(out.considered, 0, 'a hot queue is skipped at the candidate stage, without entering private.js')
158
+ assert.equal(state.getLastSleepAt('issue5-hot'), null)
159
+ })
160
+
161
+ test('issue #5: cold queue residue no longer blocks idle consolidation forever', async () => {
162
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 10 })
163
+ ensureIdle('issue5-cold', { minutesAgo: 30, inbound: { pending: [{ key: 'k1' }, { key: 'k2' }, { key: 'k3' }], retryAt: new Date(Date.now() - 3 * 60 * 60_000).toISOString() }, lastInboundMinutesAgo: 3 * 60 })
164
+ const ctx = fakeCtx({ live: ['issue5-cold'] })
165
+ const out = await cycle.runSleepPass(ctx, { limit: 10 })
166
+ assert.equal(out.ran, 1, 'the residue is not drained until the user speaks again, so the sweep must proceed')
167
+ assert.equal(ctx.created.length, 1, 'the fork ran')
168
+ assert.ok(state.getLastSleepAt('issue5-cold'), 'the cursor advanced and the tail is not stranded')
169
+ })
170
+
171
+ // —— Issue #4 缺陷 3:归档会话事前跳过 ——
172
+
173
+ test('issue #4/defect 3: archived sessions are skipped at the candidate stage', async () => {
174
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 10 })
175
+ ensureIdle('issue4-arch', { minutesAgo: 30 })
176
+ ensureIdle('issue4-live', { minutesAgo: 30 })
177
+ const ctx = fakeCtx({ live: ['issue4-arch', 'issue4-live'], archived: ['issue4-arch'] })
178
+ const out = await cycle.runSleepPass(ctx, { limit: 10 })
179
+ assert.equal(out.ran, 1, 'only the unarchived session is consolidated')
180
+ assert.deepEqual(ctx.created.map((spec) => spec.meta.parentSession), ['issue4-live'], 'the archived session never becomes a fork and takes no budget slot')
181
+ })
182
+
183
+ test('issue #4/defect 3: a manual consolidation of an archived session is refused with a clear reason', async () => {
184
+ ensureIdle('issue4-arch-manual', { minutesAgo: 30 })
185
+ const ctx = fakeCtx({ live: ['issue4-arch-manual'], archived: ['issue4-arch-manual'] })
186
+ const result = await privateLib.requestPrivateConsolidation(ctx, 'issue4-arch-manual', { force: true })
187
+ assert.equal(result.ok, false)
188
+ assert.equal(result.reasonCode, 'session-archived')
189
+ assert.equal(ctx.created.length, 0, 'no doomed fork is created for an archived session')
190
+ })
191
+
192
+ // —— Issue #4 缺陷 1:snapshot-failed 熔断 ——
193
+
194
+ test('issue #4/defect 1: a frozen snapshot is not settled, keeps the error visible, and never advances the cursor', async () => {
195
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 5 })
196
+ ensureIdle('issue4-freeze', { minutesAgo: 60 })
197
+ const errorCtx = () => fakeCtx({ live: ['issue4-freeze'], receipts: 'error' })
198
+ // 两次真实失败 → 同一快照连击到上限(CONSOLIDATION_SNAPSHOT_FAILURE_LIMIT = 2)。
199
+ // 每次失败后的退避到期前不能重试,先把退避清掉模拟「退避过期」的时序。
200
+ await cycle.runSleepPass(errorCtx(), { limit: 10 })
201
+ clearBackoffs('issue4-freeze')
202
+ await cycle.runSleepPass(errorCtx(), { limit: 10 })
203
+ const frozenBinding = state.getSessionBinding('issue4-freeze')
204
+ assert.ok(frozenBinding.lastSleepError, 'the last real failure stays visible')
205
+
206
+ // 第三扫:命中熔断闸门。修复后 settled:false → deferred 路径:
207
+ // 游标不推平、lastSleepError 不清零。
208
+ clearBackoffs('issue4-freeze')
209
+ await cycle.runSleepPass(errorCtx(), { limit: 10 })
210
+ assert.equal(state.getLastSleepAt('issue4-freeze'), null, 'a frozen failure must not flatten the sleep cursor (was settled:true before the fix)')
211
+ assert.ok(state.getSessionBinding('issue4-freeze').lastSleepError, 'the failure is not erased by the frozen gate')
212
+
213
+ // 活动日志去重:同一份冻结记录只落一条 snapshot-failed-too-many。
214
+ const frozenEvents = () => activityLog.listEvents({ kind: 'consolidate', limit: 50 })
215
+ .filter((entry) => entry.detail?.reasonCode === 'snapshot-failed-too-many')
216
+ assert.equal(frozenEvents().length, 1, 'the freeze logs once')
217
+
218
+ clearBackoffs('issue4-freeze')
219
+ await cycle.runSleepPass(errorCtx(), { limit: 10 })
220
+ assert.equal(state.getLastSleepAt('issue4-freeze'), null, 'still frozen on the next sweep')
221
+ assert.equal(frozenEvents().length, 1, 'repeated sweeps inside the freeze do not spam activity.jsonl')
222
+ })
223
+
224
+ test('issue #4/defect 1: the freeze expires after its cooldown and a real retry is allowed', async () => {
225
+ // 沿用上一条冻结的 issue4-freeze:把冻结记录的 at 改到冷却期之外
226
+ //(failures 保持 2),下一扫应当清零连击并真的 fork 一次。
227
+ const frozen = ledger.loadLedger().sessions['issue4-freeze']
228
+ assert.ok(frozen, 'the ledger entry exists')
229
+ const failedKeys = Object.entries(frozen.operations || {})
230
+ .filter(([, op]) => op?.outcome === 'failed' && Number(op?.failures) >= 2)
231
+ assert.ok(failedKeys.length >= 1, 'the failed operation streak is recorded')
232
+ patchLedger('issue4-freeze', (entry) => {
233
+ for (const [key] of failedKeys) {
234
+ entry.operations[key].at = new Date(Date.now() - 7 * 60 * 60_000).toISOString()
235
+ }
236
+ entry.retryAt = null
237
+ })
238
+ state.setSessionBinding('issue4-freeze', { sleepRetryAt: null, sleepAttempts: 0 })
239
+
240
+ const ctx = fakeCtx({ live: ['issue4-freeze'], receipts: 'error' })
241
+ await cycle.runSleepPass(ctx, { limit: 10 })
242
+ assert.equal(ctx.created.length, 1, 'the cooldown expiry lets one real fork through (was frozen forever before the fix)')
243
+ })
244
+
245
+ // —— Issue #4 缺陷 2:多窗尾段 ——
246
+
247
+ test('issue #4/defect 2: a mid-window completion leaves the cursor behind and the tail is picked up by the next sweep', async () => {
248
+ state.updateSettings({ sleepConsolidation: true, sleepAfterIdleMinutes: 10 })
249
+ ensureIdle('issue4-tail', { minutesAgo: 30 })
250
+ // 650 事件:头一段真人对话 + 644 条 todo/write 填充。第一窗切出约 500 条,
251
+ // 余数 < 200(CONSOLIDATION_BACKLOG_EVENTS),修复前会永久悬空。
252
+ const filler = Array.from({ length: privateLib.CONSOLIDATION_WINDOW_EVENTS + 144 }, (_, i) => ({
253
+ seq: 3 + i,
254
+ type: 'todo/write',
255
+ data: { todo: '填充事件 ' + i },
256
+ }))
257
+ const longEvents = [
258
+ { seq: 0, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '我们把整个记忆系统的整理链路从头到尾对一遍账。' }] } },
259
+ { seq: 1, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: '好的,先从 sweep 的候选筛选开始。' }] } } },
260
+ { seq: 2, type: 'turn/end', data: { turn: 0, reason: { kind: 'completed' } } },
261
+ ...filler,
262
+ ]
263
+ const ctx = fakeCtx({ live: ['issue4-tail'], receipts: 'window', events: longEvents })
264
+
265
+ // 第一扫:fork 第一窗,回执只覆盖本窗(seed.lastSeq ≈ 502)→ remaining > 0。
266
+ const first = await cycle.runSleepPass(ctx, { limit: 10 })
267
+ assert.equal(first.ran, 1)
268
+ assert.ok(ctx.created.length, 1, 'the first window forked')
269
+ const checkedAfterFirst = ledger.sessionState('issue4-tail')?.checked
270
+ assert.ok(checkedAfterFirst?.throughSeq > 0, 'window 1 advanced the ledger cursor')
271
+ assert.ok(checkedAfterFirst.throughSeq < longEvents[longEvents.length - 1].seq, 'the receipt covered only window 1')
272
+ assert.equal(state.getLastSleepAt('issue4-tail'), null, 'the coarse cursor must NOT advance while remaining > 0 (before the fix it was flattened here and the tail stranded)')
273
+
274
+ // 第二扫:剩余尾段走 no-human-turn 终态跳过(skipRange),整段收口。
275
+ const second = await cycle.runSleepPass(fakeCtx({ live: ['issue4-tail'], receipts: 'window', events: longEvents }), { limit: 10 })
276
+ assert.equal(second.ran, 0, 'the tail sweep is a terminal policy skip, not a worker run')
277
+ const settled = ledger.sessionState('issue4-tail')?.checked
278
+ assert.equal(settled.throughSeq, longEvents[longEvents.length - 1].seq, 'the tail is fully checked — before the fix it stayed pending forever')
279
+ assert.equal(ledger.sessionState('issue4-tail')?.pending, null, 'no pending range left behind')
280
+ assert.ok(state.getLastSleepAt('issue4-tail'), 'the cursor advances once the whole transcript is settled')
281
+ })
@@ -24,14 +24,14 @@ test.after(() => {
24
24
  })
25
25
 
26
26
  test('the simulator measures what the injection pipeline put in each request', () => {
27
- const out = path.join(home, 'run-6')
28
- const summary = JSON.parse(run(['--turns', '6', '--json', '--out', out, '--home', path.join(home, 'home-6')]))
27
+ const out = path.join(home, 'run-18')
28
+ const summary = JSON.parse(run(['--turns', '18', '--json', '--out', out, '--home', path.join(home, 'home-18')]))
29
29
 
30
- assert.equal(summary.turns, 6)
30
+ assert.equal(summary.turns, 18)
31
31
  assert.equal(summary.warnCount, 0, 'a warn means the pipeline itself complained: that is a failure, not noise')
32
32
  assert.equal(summary.sendFailures, 0)
33
33
  // 规则 guide 只在首回合投放一次,靠的就是"转录里带着之前发过的插件消息"。
34
- // 若驱动把历史丢掉,这里会变成 6 而不是 1。
34
+ // 若驱动把历史丢掉,这里会变成 18 而不是 1。
35
35
  assert.equal(summary.deltaTotals.guide, 1, 'the rules guide is placed once, not per turn')
36
36
  assert.equal(summary.deltaTotals.anchor, 1, 'the anchor lands on the first turn only')
37
37
  assert.ok(summary.deltaTotals.context >= 1, 'per-turn recall title cards are counted')
@@ -1,7 +1,7 @@
1
1
  import test from 'node:test'
2
2
  import assert from 'node:assert/strict'
3
3
 
4
- const { queryTerms, firstHit, centeredSnippet } = await import('../lib/snippet.js')
4
+ const { queryTerms, firstHit, centeredSnippet, centeredSnippetWindow } = await import('../lib/snippet.js')
5
5
 
6
6
  test('query terms drop noise and keep the long phrase as a fallback', () => {
7
7
  const terms = queryTerms('where a is the deploy key?')
@@ -45,3 +45,35 @@ test('firstHit is case-insensitive and picks the earliest term', () => {
45
45
  assert.equal(firstHit('the vault was rotated', terms), 4)
46
46
  assert.equal(firstHit('nothing here', terms), -1)
47
47
  })
48
+
49
+ test('160 is whole but 161 has explicit truncation and a strict 160-codepoint payload', () => {
50
+ const whole = centeredSnippetWindow('甲'.repeat(160), 'missing')
51
+ assert.equal(whole.body, '甲'.repeat(160))
52
+ assert.deepEqual([whole.start, whole.end, whole.returnedChars, whole.totalChars, whole.truncated], [0, 160, 160, 160, false])
53
+ const clipped = centeredSnippetWindow('甲'.repeat(161), 'missing')
54
+ assert.equal(clipped.body, '甲'.repeat(160) + '…')
55
+ assert.deepEqual([clipped.start, clipped.end, clipped.returnedChars, clipped.totalChars, clipped.truncated], [0, 160, 160, 161, true])
56
+ })
57
+
58
+ test('snippet windows count emoji as codepoints and never cut surrogate pairs', () => {
59
+ const body = '😀'.repeat(200) + '部署条件' + '🚀'.repeat(200)
60
+ const snippet = centeredSnippetWindow(body, '部署条件')
61
+ assert.equal(snippet.start, 160)
62
+ assert.equal(snippet.end, 320)
63
+ assert.equal(snippet.returnedChars, 160)
64
+ assert.equal(snippet.totalChars, 404)
65
+ assert.equal(snippet.truncated, true)
66
+ assert.equal(snippet.body, '…' + Array.from(body).slice(160, 320).join('') + '…')
67
+ assert.equal(snippet.body.isWellFormed(), true)
68
+ const head = centeredSnippet('😀'.repeat(169), 'missing')
69
+ assert.equal(head, '😀'.repeat(160) + '…')
70
+ assert.equal(Array.from(head).length, 161)
71
+ })
72
+
73
+ test('short Unicode text and empty windows report exact payload counts without ellipses', () => {
74
+ const body = '😀尾部🚀'
75
+ assert.equal(centeredSnippet(body, ''), body)
76
+ const snippet = centeredSnippetWindow(body, '')
77
+ assert.deepEqual([snippet.returnedChars, snippet.totalChars, snippet.truncated], [4, 4, false])
78
+ assert.deepEqual(centeredSnippetWindow('', ''), { body: '', start: 0, end: 0, returnedChars: 0, totalChars: 0, truncated: false })
79
+ })
@@ -27,14 +27,19 @@ test('different cwd gets a different library', () => {
27
27
  assert.notEqual(a.libraryId, b.libraryId)
28
28
  })
29
29
 
30
- test('a new memory binding defaults its domain selection to RP, and an explicit choice sticks', () => {
30
+ test('an unasked binding follows detectDomain for its domain, and an explicit choice sticks', () => {
31
31
  const cwd = path.join(home, 'project-domain-default')
32
32
  const binding = state.ensureSession('state-domain-default', { cwd, agentPreset: 'coding' })
33
33
  assert.equal(binding.domain, 'coding', 'the detected domain stays as metadata')
34
- assert.equal(binding.domainOverride, 'rp', 'the selector starts on RP')
35
- state.setSessionBinding('state-domain-default', { domainOverride: 'general' })
34
+ // issue #2: the old hard `rp` fallback silently put every unasked conversation
35
+ // on the RP track; the fallback now follows the same detectDomain rule as the
36
+ // `domain` metadata, and `domainSource` marks that nobody chose it yet.
37
+ assert.equal(binding.domainOverride, 'coding', 'the unasked fallback follows detectDomain, not a hard rp')
38
+ assert.equal(binding.domainSource, 'auto', 'the fallback is implicit until someone answers')
39
+ state.setSessionBinding('state-domain-default', { domainOverride: 'general', domainSource: 'chosen' })
36
40
  const rebound = state.ensureSession('state-domain-default', { cwd, agentPreset: 'coding' })
37
41
  assert.equal(rebound.domainOverride, 'general', 'general is a real explicit choice')
42
+ assert.equal(rebound.domainSource, 'chosen', 'an explicit answer is remembered as chosen')
38
43
  })
39
44
 
40
45
  test('deleting a session binding keeps the library', () => {
@@ -1,5 +1,16 @@
1
1
  import test from 'node:test'
2
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-tool-schema-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+ test.after(async () => {
10
+ const state = await import('../lib/state.js')
11
+ state.flushState()
12
+ fs.rmSync(home, { recursive: true, force: true })
13
+ })
3
14
 
4
15
  import { defineTool } from './stubs/dsh-tools.js'
5
16
 
@@ -72,3 +83,44 @@ test('the shipped tool surface compiles under the host rules', async () => {
72
83
  assert.ok(registered.includes('memu_private_remember_batch'), 'the batch write tool compiles under the host rules')
73
84
  dispose()
74
85
  })
86
+
87
+ test('recall schemas retain required query, supported enums and integer paging; all 14 outputs stay string', async () => {
88
+ const { registerTools } = await import('../lib/tools.js')
89
+ const tools = []
90
+ const dispose = registerTools({ tools: { register: (tool) => { tools.push(tool); return () => {} } }, logger: { warn() {} } })
91
+ try {
92
+ assert.equal(tools.length, 14)
93
+ for (const tool of tools) {
94
+ assert.deepEqual(tool.output.schema, { type: 'string' })
95
+ assert.deepEqual(tool.output.render({}, 'receipt'), [{ type: 'text', text: 'receipt' }])
96
+ }
97
+ for (const name of ['memu_private_recall', 'memu_global_recall']) {
98
+ const tool = tools.find((item) => item.name === name)
99
+ const p = tool.parameters
100
+ assert.equal(p.query.type, 'string')
101
+ assert.equal(p.query.required, true)
102
+ assert.equal(p.view.type, 'string')
103
+ assert.deepEqual(p.view.enum, ['auto', 'snippet', 'full'])
104
+ assert.equal(p.view.default, 'auto')
105
+ assert.equal(p.offset.type, 'integer')
106
+ assert.equal(p.limitChars.type, 'integer')
107
+ assert.equal(p.revision.type, 'string')
108
+ assert.equal(p.topK.type, 'integer')
109
+ assert.match(p.topK.description, /1\.\.20/)
110
+ assert.match(p.offset.description, /code points/)
111
+ assert.match(p.revision.description, /MEMORY_CHANGED/)
112
+ assert.equal(Object.hasOwn(p, 'libraryId'), name === 'memu_private_recall')
113
+ if (p.libraryId) assert.equal(p.libraryId.type, 'string')
114
+ for (const property of Object.values(p)) {
115
+ assert.equal(Object.hasOwn(property, 'minimum'), false)
116
+ assert.equal(Object.hasOwn(property, 'maximum'), false)
117
+ }
118
+ }
119
+ } finally { dispose() }
120
+ })
121
+
122
+ test('host DSL rejects numeric bounds: recall ranges must stay in execute validation', () => {
123
+ for (const bound of ['minimum', 'maximum']) {
124
+ assert.throws(() => defineTool(good({ offset: { type: 'integer', [bound]: 0 } })), /not supported by the value schema DSL/)
125
+ }
126
+ })