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
@@ -6,6 +6,7 @@ import path from 'node:path'
6
6
 
7
7
  const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-cross-library-'))
8
8
  process.env.DSH_MEMU_HOME = home
9
+ process.env.DSH_MEMU_MEMORY_HOME = home
9
10
 
10
11
  const state = await import('../lib/state.js')
11
12
  const { privateRecall, privateList } = await import('../lib/memory.js')
@@ -111,3 +112,158 @@ test('the bound library is always included, while other libraries depend on a do
111
112
  assert.ok(result.files.some((file) => file.name === 'mem-current'))
112
113
  assert.ok(!result.files.some((file) => file.name === 'mem-other'))
113
114
  })
115
+
116
+ test('foreign conflict partners and their titles remain inside the domain scope', async () => {
117
+ const libs = world()
118
+ state.updateSettings({ memoryBackend: 'agent', crossLibraryRecall: true })
119
+ seed(libs.other.id, 'mem-coding-left', { title: 'AlphaCert 部署证书', content: 'AlphaCert 部署证书轮换', domain: 'coding', conflicts_with: 'mem-rp-right' })
120
+ seed(libs.other.id, 'mem-rp-right', { title: '不应泄露的异域版本标题', content: '舞台剧中的秘密', domain: 'rp', conflicts_with: 'mem-coding-left' })
121
+ for (const purpose of ['automatic', 'explicit']) {
122
+ const result = await privateRecall({ exec: execFor('cross-current'), query: 'AlphaCert', topK: 1, relevanceThreshold: 0.8, purpose })
123
+ assert.deepEqual(result.files.map(file => file.name), ['mem-coding-left'])
124
+ assert.equal(result.files[0].libraryId, libs.other.id)
125
+ assert.equal(result.files[0].conflictComplete, false)
126
+ const pointer = result.files[0].related.find(item => item.kind === 'conflict')
127
+ assert.equal(pointer?.available, false)
128
+ assert.notEqual(pointer?.title, '不应泄露的异域版本标题')
129
+ }
130
+ })
131
+
132
+ test('conflict partners in the primary library retain the unfiltered domain contract', async () => {
133
+ const libs = world()
134
+ state.updateSettings({ memoryBackend: 'agent', crossLibraryRecall: true })
135
+ seed(libs.current.id, 'mem-primary-left', { title: 'LocalCert 部署证书', content: 'LocalCert 部署证书轮换', domain: 'rp', conflicts_with: 'mem-primary-right' })
136
+ seed(libs.current.id, 'mem-primary-right', { title: '本库另一版本', content: '本库相冲突的不同记忆', domain: 'rp', conflicts_with: 'mem-primary-left' })
137
+ const result = await privateRecall({ exec: execFor('cross-current'), query: 'LocalCert', topK: 1, relevanceThreshold: 0.8, purpose: 'automatic' })
138
+ assert.deepEqual(new Set(result.files.map(file => file.name)), new Set(['mem-primary-left', 'mem-primary-right']))
139
+ assert.ok(result.files.every(file => file.libraryId === libs.current.id && file.conflictComplete))
140
+ })
141
+
142
+ // ---------------------------------------------------------------- R4 反例
143
+
144
+ test('R4: the same id in two libraries stays two facts with owning-library conflict pairing', async () => {
145
+ const libs = world()
146
+ state.updateSettings({ memoryBackend: 'agent', crossLibraryRecall: true })
147
+ seed(libs.current.id, 'mem-twin', { title: '本库同名条目', content: 'alpha 集群的扩容记录与负责人安排', conflicts_with: 'mem-twin-partner' })
148
+ seed(libs.current.id, 'mem-twin-partner', { title: '本库配对版本', content: 'alpha 集群扩容的另一版记录' })
149
+ seed(libs.other.id, 'mem-twin', { title: '外库同名条目', content: 'beta 服务的回滚步骤与值班表' })
150
+ const result = await privateRecall({ exec: execFor('cross-current'), query: '同名条目', topK: 2, relevanceThreshold: 0 })
151
+ const twins = result.files.filter(file => file.name === 'mem-twin')
152
+ assert.equal(twins.length, 2, '同 id 不同库是两条事实,不能被裸 id 折叠或 MMR 文本缓存误杀')
153
+ assert.deepEqual(new Set(twins.map(file => file.libraryId)), new Set([libs.current.id, libs.other.id]))
154
+ const local = twins.find(file => file.libraryId === libs.current.id)
155
+ const foreign = twins.find(file => file.libraryId === libs.other.id)
156
+ assert.ok(local.content.includes('alpha'), '本库正文不被外库覆盖')
157
+ assert.ok(foreign.content.includes('beta'), '外库正文不被本库覆盖')
158
+ assert.equal(local.conflictPair, 'mem-twin-partner', '冲突配对落在 owning library')
159
+ assert.equal(foreign.conflictPair, undefined, '外库同 id 不继承本库的冲突关系')
160
+ })
161
+
162
+ test('R4: exact-id recall keeps both libraries documents, primary first', async () => {
163
+ const libs = world()
164
+ state.updateSettings({ memoryBackend: 'agent', crossLibraryRecall: true })
165
+ seed(libs.current.id, 'mem-twin', { title: '本库同名条目', content: 'alpha 集群的扩容记录与负责人安排' })
166
+ seed(libs.other.id, 'mem-twin', { title: '外库同名条目', content: 'beta 服务的回滚步骤与值班表' })
167
+ const result = await privateRecall({ exec: execFor('cross-current'), query: 'mem-twin', topK: 5, relevanceThreshold: 0 })
168
+ assert.deepEqual(result.files.map(file => file.libraryId), [libs.current.id, libs.other.id])
169
+ assert.ok(result.files.every(file => file.name === 'mem-twin'))
170
+ })
171
+
172
+ test('R4: a strong local lexical hit outranks a weak foreign first place and the weak hit is cut', async () => {
173
+ const libs = world()
174
+ state.updateSettings({ memoryBackend: 'agent', crossLibraryRecall: true })
175
+ seed(libs.current.id, 'mem-strong-local', { title: '量子计算部署约定', content: '量子计算部署约定,量子计算部署流程,量子计算部署检查清单' })
176
+ seed(libs.other.id, 'mem-weak-foreign', { title: '部署工具清单', content: '部署工具清单' })
177
+ const open = await privateRecall({ exec: execFor('cross-current'), query: '量子计算部署', topK: 10, relevanceThreshold: 0 })
178
+ assert.equal(open.fusion?.crossLibraryLexical, 'unified-bm25', '跨库词法腿使用统一授权语料')
179
+ const strong = open.files.find(file => file.name === 'mem-strong-local')
180
+ const weak = open.files.find(file => file.name === 'mem-weak-foreign')
181
+ assert.ok(strong && weak, '阈值 0 时两条都在候选里')
182
+ assert.ok(strong.retrievalScore > weak.retrievalScore, '统一 BM25 分数可比:强本库命中高于弱外库首名')
183
+ assert.equal(open.files[0].name, 'mem-strong-local')
184
+ const cut = await privateRecall({ exec: execFor('cross-current'), query: '量子计算部署', topK: 10, relevanceThreshold: 0.8 })
185
+ assert.deepEqual(cut.files.map(file => file.name), ['mem-strong-local'], '弱外库命中被相关度阈值拒绝,不因库内第一名身份保留')
186
+ })
187
+
188
+ test('R4: never_say and out-of-context foreign entries never enter automatic cross-library recall', async () => {
189
+ const libs = world()
190
+ state.updateSettings({ memoryBackend: 'agent', crossLibraryRecall: true })
191
+ seed(libs.other.id, 'mem-never', { title: '隐蔽条目测试的不可说版本', content: '隐蔽条目测试 never', disclosure: 'never_say' })
192
+ seed(libs.other.id, 'mem-context', { title: '隐蔽条目测试的频道版本', content: '隐蔽条目测试 context', context: { channelId: 'secret-channel' } })
193
+ const automatic = await privateRecall({ exec: execFor('cross-current'), query: '隐蔽条目测试', topK: 10, relevanceThreshold: 0, purpose: 'automatic' })
194
+ assert.ok(!automatic.files.some(file => ['mem-never', 'mem-context'].includes(file.name)), '自动召回不泄露 never_say 与异上下文条目')
195
+ const explicit = await privateRecall({ exec: execFor('cross-current'), query: '隐蔽条目测试', topK: 10, relevanceThreshold: 0 })
196
+ assert.ok(explicit.files.some(file => file.name === 'mem-never'), '显式召回仍可读 never_say')
197
+ assert.ok(!explicit.files.some(file => file.name === 'mem-context'), '异上下文条目对显式召回也不可见')
198
+ })
199
+
200
+ test('R4: empty cross-library query stays a bounded recency page with finite scores', async () => {
201
+ world()
202
+ state.updateSettings({ memoryBackend: 'agent', crossLibraryRecall: true })
203
+ const result = await privateRecall({ exec: execFor('cross-current'), query: '', topK: 5, relevanceThreshold: 0 })
204
+ assert.equal(result.fusion?.crossLibraryLexical, 'recency')
205
+ assert.ok(result.files.length > 0)
206
+ assert.ok(result.files.every(file => Number.isFinite(file.score) && file.libraryId), '空查询不产生 NaN 分数,来源库不丢')
207
+ })
208
+
209
+ test('R4: semantic hits without raw scores keep an explicit rank-only limitation', async () => {
210
+ const libs = world()
211
+ state.updateSettings({ memoryBackend: 'api', vectorSource: 'api', crossLibraryRecall: true })
212
+ seed(libs.current.id, 'mem-hybrid-local', { title: '混合召回本地条', content: 'hybrid local body' })
213
+ seed(libs.other.id, 'mem-hybrid-foreign', { title: '混合召回外库条', content: 'hybrid foreign body' })
214
+ const retrieveImpl = async ({ db }) => ({
215
+ files: [{ name: String(db).includes(libs.current.id) ? 'mem-hybrid-local' : 'mem-hybrid-foreign' }],
216
+ segments: [], resources: [],
217
+ })
218
+ const result = await privateRecall({ exec: execFor('cross-current'), query: 'zzzqqq wwwvvv', topK: 10, relevanceThreshold: 0, retrieveImpl })
219
+ assert.equal(result.fusion?.crossLibrarySemantic, 'rank-only', '缺原始分数时不伪造跨库可比性')
220
+ assert.deepEqual(new Set(result.files.map(file => file.name)), new Set(['mem-hybrid-local', 'mem-hybrid-foreign']))
221
+ assert.ok(result.files.every(file => file.libraryId))
222
+ })
223
+
224
+ test('R4: a score missing on one library demotes the whole semantic leg to rank-only', async () => {
225
+ const libs = world()
226
+ state.updateSettings({ memoryBackend: 'api', vectorSource: 'api', crossLibraryRecall: true })
227
+ seed(libs.current.id, 'mem-hybrid-local', { title: '混合召回本地条', content: 'hybrid local body' })
228
+ seed(libs.other.id, 'mem-hybrid-foreign', { title: '混合召回外库条', content: 'hybrid foreign body' })
229
+ const retrieveImpl = async ({ db }) => ({
230
+ files: String(db).includes(libs.current.id)
231
+ ? [{ name: 'mem-hybrid-local', score: 0.9 }]
232
+ : [{ name: 'mem-hybrid-foreign' }],
233
+ segments: [], resources: [],
234
+ })
235
+ const result = await privateRecall({ exec: execFor('cross-current'), query: 'zzzqqq xxxvvv', topK: 10, relevanceThreshold: 0, retrieveImpl })
236
+ assert.equal(result.fusion?.crossLibrarySemantic, 'rank-only', '部分库缺分数时整体退回 rank-only')
237
+ })
238
+
239
+ test('R4: comparable raw semantic scores rank across libraries by score, not by library seat', async () => {
240
+ const libs = world()
241
+ state.updateSettings({ memoryBackend: 'api', vectorSource: 'api', crossLibraryRecall: true })
242
+ seed(libs.current.id, 'mem-hybrid-local', { title: '混合召回本地条', content: 'hybrid local body' })
243
+ seed(libs.other.id, 'mem-hybrid-foreign', { title: '混合召回外库条', content: 'hybrid foreign body' })
244
+ const retrieveImpl = async ({ db }) => ({
245
+ files: String(db).includes(libs.current.id)
246
+ ? [{ name: 'mem-hybrid-local', score: 0.4 }]
247
+ : [{ name: 'mem-hybrid-foreign', score: 0.9 }],
248
+ segments: [], resources: [],
249
+ })
250
+ const result = await privateRecall({ exec: execFor('cross-current'), query: 'zzzqqq yyyvvv', topK: 10, relevanceThreshold: 0, retrieveImpl })
251
+ assert.equal(result.fusion?.crossLibrarySemantic, 'score')
252
+ assert.equal(result.files[0].name, 'mem-hybrid-foreign', '同代际原始相似度可比:高分外库命中排在低分本库命中之前')
253
+ assert.equal(result.files[0].libraryId, libs.other.id)
254
+ })
255
+
256
+ test('R4: a scope change during cross-library recall rejects the stale result', async () => {
257
+ const libs = world()
258
+ state.updateSettings({ memoryBackend: 'api', vectorSource: 'api', crossLibraryRecall: true })
259
+ seed(libs.current.id, 'mem-hybrid-local', { title: '混合召回本地条', content: 'hybrid local body' })
260
+ const retrieveImpl = async () => {
261
+ state.setSessionBinding('cross-current', { domainOverride: 'rp' })
262
+ return { files: [], segments: [], resources: [] }
263
+ }
264
+ await assert.rejects(
265
+ privateRecall({ exec: execFor('cross-current'), query: 'zzzqqq zzzvvv', topK: 5, relevanceThreshold: 0, retrieveImpl }),
266
+ /scope changed/,
267
+ )
268
+ state.setSessionBinding('cross-current', { domainOverride: 'coding' })
269
+ })
@@ -5,6 +5,8 @@ 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-cue-'))
8
+ process.env.DSH_HOME = home
9
+ process.env.DSH_MEMU_MEMORY_HOME = home
8
10
  process.env.DSH_MEMU_HOME = home
9
11
 
10
12
  const state = await import('../lib/state.js')
@@ -22,10 +24,21 @@ test('random cue is injected once and armed', async () => {
22
24
  id: 'u-cue', role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: '今天发生了什么,你还记得吗?' }],
23
25
  }
24
26
  const decision = { kind: 'enter', messages: [user] }
25
- const agent = { session: { header: { id: 'cue-session', cwd, agentPreset: 'rp' } } }
26
- const out = await inject.injectForStep({ agent, decision, turn: 2, step: 1, signal: { aborted: false } })
27
+ const agent = { session: { header: { id: 'cue-session', cwd, agentPreset: 'rp' }, messages: [] } }
28
+ const handlers = new Map()
29
+ const ctx = { logger: { warn() {} }, on(event, fn) { handlers.set(event, fn); return () => {} } }
30
+ inject.registerInjection(ctx)
31
+ const sessionEvent = handlers.get('session/event')
32
+ assert.equal(typeof sessionEvent, 'function')
33
+ const out = await inject.injectForStep({ agent, decision, turn: 2, step: 1, signal: { aborted: false }, ctx })
27
34
  const text = out.messages[0]?.content?.[0]?.text || ''
28
35
  assert.ok(text.includes('<memory-cue id="'))
36
+ assert.equal(state.getActiveCue('cue-session'), null, 'a proposal must not arm the cue')
37
+ for (const message of out.messages) {
38
+ assert.ok(message.id && message.role === 'user', 'Native DSL requires an identified UserMessage')
39
+ if (!agent.session.messages.some(item => item.id === message.id)) agent.session.messages.push(message)
40
+ await sessionEvent(agent.session, { type: 'user/message', data: message })
41
+ }
29
42
  const active = state.getActiveCue('cue-session')
30
43
  assert.ok(active && active.id)
31
44
 
@@ -0,0 +1,191 @@
1
+ // Issue #3(dsh-memu-memory#3):宿主 0.2.2-rc.2 把 SubagentActivationSpec 扁平化
2
+ // (parent/cwd/prompt/agentOptions 平铺顶层,无 request 外层),旧契约
3
+ // (0.2.1-rc.5 / 0.2.2-rc.1)把任务字段装在 request 信封里。这里用两种形态的
4
+ // mock 宿主各跑一遍完整的 startGlobalCuration 链路(选形态 → startActivation →
5
+ // 回执 → commit),并验证 TypeError 零副作用回退与失败日志落地。
6
+ import test from 'node:test'
7
+ import assert from 'node:assert/strict'
8
+ import fs from 'node:fs'
9
+ import os from 'node:os'
10
+ import path from 'node:path'
11
+ import http from 'node:http'
12
+ import crypto from 'node:crypto'
13
+
14
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-curator-contract-'))
15
+ process.env.DSH_MEMU_HOME = home
16
+
17
+ // commit → embedding 的最小桩(与 curator.test.mjs 同款)。
18
+ function vector(text) {
19
+ const h = crypto.createHash('sha256').update(String(text)).digest()
20
+ const out = []
21
+ for (let i = 0; i < 8; i++) out.push((h[i] / 255) * 2 - 1)
22
+ const norm = Math.sqrt(out.reduce((a, b) => a + b * b, 0)) || 1
23
+ return out.map((x) => x / norm)
24
+ }
25
+ const server = http.createServer((req, res) => {
26
+ let body = ''
27
+ req.on('data', (d) => { body += d })
28
+ req.on('end', () => {
29
+ try {
30
+ const data = JSON.parse(body || '{}')
31
+ const inputs = Array.isArray(data.input) ? data.input : [data.input]
32
+ res.writeHead(200, { 'content-type': 'application/json' })
33
+ res.end(JSON.stringify({
34
+ object: 'list',
35
+ data: inputs.map((text, index) => ({ object: 'embedding', index, embedding: vector(text) })),
36
+ model: data.model || 'test-embed',
37
+ usage: { prompt_tokens: inputs.length, total_tokens: inputs.length },
38
+ }))
39
+ } catch (error) {
40
+ res.writeHead(500, { 'content-type': 'application/json' })
41
+ res.end(JSON.stringify({ error: { message: String(error) } }))
42
+ }
43
+ })
44
+ })
45
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
46
+ process.env.MEMU_EMBED_PROVIDER = 'openai'
47
+ process.env.MEMU_EMBED_MODEL = 'test-embed'
48
+ process.env.MEMU_BASE_URL = `http://127.0.0.1:${server.address().port}/v1`
49
+ process.env.MEMU_API_KEY = 'test-key'
50
+ process.env.OPENAI_API_KEY = 'test-key'
51
+
52
+ const { startGlobalCuration, getCurationJob } = await import('../lib/curator.js')
53
+ const activityLog = await import('../lib/activity-log.js')
54
+
55
+ test.after(async () => {
56
+ await new Promise((resolve) => server.close(resolve))
57
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
58
+ })
59
+
60
+ function ctxFor({ markers = false, mode = 'accept', onSpec = () => {} } = {}) {
61
+ // markers: true → mock 带新版树内省方法(flat 探测命中);false → 极简 mock
62
+ //(只能靠 TypeError 回退兜底)。mode: 'accept' 两种形态都收;'reject-request'
63
+ // 收 flat 拒 nested(老宿主);'reject-flat' 收 nested 拒 flat(模拟探测失灵)。
64
+ const parent = { id: 'parent', session: { header: { cwd: path.join(home, 'project') } } }
65
+ const calls = []
66
+ const subagents = {
67
+ ...(markers ? { rootOf: () => { throw new Error('not used by the plugin') } } : {}),
68
+ startActivation: async (spec) => {
69
+ calls.push(spec)
70
+ onSpec(spec)
71
+ const flat = !('request' in spec)
72
+ if (mode === 'reject-request' && !flat) throw new TypeError('Cannot read properties of undefined (reading \'maxDepth\')')
73
+ if (mode === 'reject-flat' && flat) throw new TypeError('Cannot read properties of undefined (reading \'id\')')
74
+ return {
75
+ result: Promise.resolve({
76
+ stopReason: 'completed',
77
+ output: [{ type: 'text', text: JSON.stringify(curatorOutput()) }],
78
+ }),
79
+ dispose: async () => {},
80
+ }
81
+ },
82
+ }
83
+ return {
84
+ parent,
85
+ calls,
86
+ get(name) {
87
+ if (name === 'agents') return { get: (id) => (id === 'parent' ? parent : undefined) }
88
+ if (name === 'subagents') return subagents
89
+ if (name === 'sessionQuery') {
90
+ return {
91
+ listSessions: async () => [{
92
+ header: { id: 's1', cwd: path.join(home, 'project'), createdAt: Date.now(), agentPreset: 'coding' },
93
+ live: false,
94
+ persisted: true,
95
+ }],
96
+ readTitleSnapshots: async () => [],
97
+ readSession: async () => ({
98
+ session: { id: 's1', cwd: path.join(home, 'project'), agentPreset: 'coding' },
99
+ inheritedEventCount: 0,
100
+ events: [
101
+ { type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: 'I prefer conclusions first.' }] } },
102
+ { type: 'assistant/message', data: { message: { content: [{ type: 'text', text: 'Understood.' }] } } },
103
+ ],
104
+ }),
105
+ }
106
+ }
107
+ return undefined
108
+ },
109
+ }
110
+ }
111
+
112
+ function curatorOutput() {
113
+ return {
114
+ sessions: [{ id: 's1', domain: 'coding', reason: 'code and tool calls' }],
115
+ memories: [{
116
+ op: 'create',
117
+ track: 'memory',
118
+ domain: 'coding',
119
+ applies_to: ['coding'],
120
+ title: 'Prefers conclusion first',
121
+ content: 'The user prefers a conclusion before details in coding tasks.',
122
+ confidence: 0.9,
123
+ evidence: [{ session_id: 's1', quote: 'I prefer conclusions first.' }],
124
+ reason: 'cross-session style',
125
+ }],
126
+ domain_summary: { coding: 'coding preference' },
127
+ skipped: [],
128
+ }
129
+ }
130
+
131
+ async function waitJob(id) {
132
+ for (let i = 0; i < 200; i += 1) {
133
+ const job = getCurationJob(id)
134
+ if (job && job.status !== 'running') return job
135
+ await new Promise((resolve) => setTimeout(resolve, 10))
136
+ }
137
+ throw new Error('curation job did not settle')
138
+ }
139
+
140
+ test('a flat host (0.2.2-rc.2+) receives the task fields at the top level', async () => {
141
+ const ctx = ctxFor({ markers: true })
142
+ const queued = startGlobalCuration(ctx, { sessionIds: ['s1'], parentSessionId: 'parent' })
143
+ const job = await waitJob(queued.id)
144
+ assert.equal(job.status, 'completed', job.error || '')
145
+ assert.equal(ctx.calls.length, 1)
146
+ const spec = ctx.calls[0]
147
+ assert.equal(spec.parent, ctx.parent, 'parent is flat at the top level')
148
+ assert.equal(spec.prompt[0].type, 'text')
149
+ assert.equal(spec.cwd, path.join(home, 'project'))
150
+ assert.ok(!('request' in spec), 'no request envelope on the flat contract')
151
+ })
152
+
153
+ test('a flat-shaped rejection falls back to the nested envelope (future host without the flat path)', async () => {
154
+ const ctx = ctxFor({ markers: true, mode: 'reject-flat' })
155
+ const queued = startGlobalCuration(ctx, { sessionIds: ['s1'], parentSessionId: 'parent' })
156
+ const job = await waitJob(queued.id)
157
+ assert.equal(job.status, 'completed', job.error || '')
158
+ assert.equal(ctx.calls.length, 2, 'one TypeError fallback retry')
159
+ assert.ok(!('request' in ctx.calls[0]), 'first attempt followed the flat detection')
160
+ assert.ok('request' in ctx.calls[1], 'retry used the nested envelope and was accepted')
161
+ assert.equal(ctx.calls[1].request.parent, ctx.parent)
162
+ })
163
+
164
+ test('a bare mock that rejects the nested shape falls back to flat (issue #3 crash path)', async () => {
165
+ const ctx = ctxFor({ markers: false, mode: 'reject-request' })
166
+ const queued = startGlobalCuration(ctx, { sessionIds: ['s1'], parentSessionId: 'parent' })
167
+ const job = await waitJob(queued.id)
168
+ assert.equal(job.status, 'completed', job.error || '')
169
+ assert.equal(ctx.calls.length, 2)
170
+ assert.ok('request' in ctx.calls[0], 'bare mock → nested first (old contract)')
171
+ assert.ok(!('request' in ctx.calls[1]), 'TypeError fallback switched to the flat shape')
172
+ })
173
+
174
+ test('a non-TypeError failure is not retried and lands in activity.jsonl', async () => {
175
+ const parent = { id: 'parent', session: { header: { cwd: path.join(home, 'project') } } }
176
+ const ctx = {
177
+ get(name) {
178
+ if (name === 'agents') return { get: (id) => (id === 'parent' ? parent : undefined) }
179
+ if (name === 'subagents') return { startActivation: async () => { throw new Error('provider spawn is not registered') } }
180
+ if (name === 'sessionQuery') return ctxFor().get('sessionQuery')
181
+ return undefined
182
+ },
183
+ }
184
+ const queued = startGlobalCuration(ctx, { sessionIds: ['s1'], parentSessionId: 'parent' })
185
+ const job = await waitJob(queued.id)
186
+ assert.equal(job.status, 'error')
187
+ assert.match(job.error, /provider spawn is not registered/)
188
+ const events = activityLog.listEvents({ kind: 'curate', limit: 10 })
189
+ const failure = events.find((entry) => entry.ok === false && /provider spawn is not registered/.test(entry.message || ''))
190
+ assert.ok(failure, 'the failure is recorded in activity.jsonl, not only in the in-memory job')
191
+ })
@@ -181,7 +181,7 @@ function ctxFor(events, onActivation) {
181
181
  get(name) {
182
182
  if (name === 'sessionQuery') return sessionQueryFor(events)
183
183
  if (name === 'agents') return { get: (id) => (id === 'parent' ? parent : undefined) }
184
- if (name === 'subagents') return { startActivation: onActivation }
184
+ if (name === 'subagents') return { rootOf: () => { throw new Error('not used by the plugin') }, startActivation: onActivation } // 0.2.2-rc.2+ 树内省标记 → 扁平激活契约
185
185
  return undefined
186
186
  },
187
187
  }
@@ -280,7 +280,7 @@ test('six channels, layer by layer: transcript -> prompt -> simulated output ->
280
280
 
281
281
  const onActivation = async (spec) => {
282
282
  captured = spec
283
- const input = promptInput(spec.request.prompt[0].text)
283
+ const input = promptInput(spec.prompt[0].text)
284
284
  const transcript = input.sessions[0].transcript
285
285
  const existing = JSON.stringify(input.existing_global_index)
286
286
  // A strict copy-through model: it can only echo markers that its prompt
@@ -320,10 +320,10 @@ test('six channels, layer by layer: transcript -> prompt -> simulated output ->
320
320
  assert.ok(captured, 'startGlobalCuration should reach subagents.startActivation')
321
321
  assert.equal(captured.provider, 'spawn')
322
322
  assert.equal(captured.delivery, 'caller')
323
- assert.equal(captured.request.prompt.length, 1)
324
- assert.equal(captured.request.parent.session.header.cwd, path.join(home, 'project'))
323
+ assert.equal(captured.prompt.length, 1)
324
+ assert.equal(captured.parent.session.header.cwd, path.join(home, 'project'))
325
325
 
326
- const prompt = captured.request.prompt[0].text
326
+ const prompt = captured.prompt[0].text
327
327
  assert.match(prompt, /全局记忆提炼任务/)
328
328
  const input = promptInput(prompt)
329
329
  assert.deepEqual(Object.keys(input).sort(), ['candidate_clusters', 'clusters_truncated', 'existing_global_index', 'index_truncated', 'sessions'])
@@ -90,8 +90,10 @@ function fakeContext() {
90
90
  if (name === 'agents') return { get: (id) => id === 'parent' ? parent : undefined }
91
91
  if (name === 'subagents') {
92
92
  return {
93
+ // 0.2.2-rc.2+ 的树内省方法(plugin 用它探测扁平化后的激活契约)。
94
+ rootOf: () => { throw new Error('not used by the plugin') },
93
95
  startActivation: async (spec) => {
94
- assert.equal(spec.request.parent, parent)
96
+ assert.equal(spec.parent, parent, 'flat SubagentActivationSpec (0.2.2-rc.2+)')
95
97
  return {
96
98
  result: Promise.resolve({
97
99
  stopReason: 'completed',