@kolivri/memoreal-mcp 1.0.2 → 1.1.0

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.
@@ -1,1039 +0,0 @@
1
- import { test, describe, beforeEach, afterEach } from "node:test"
2
- import assert from "node:assert/strict"
3
- import fs from "node:fs"
4
- import path from "node:path"
5
- import os from "node:os"
6
- import cp from "node:child_process"
7
-
8
- import {
9
- isPlaceholderApiKey as isPlaceholderDirect,
10
- ONBOARDING_WIZARD_PROMPT as ONBOARDING_PROMPT_DIRECT,
11
- resolveCloudConfig,
12
- fetchSessionStartContext,
13
- buildReadSuffix,
14
- buildWriteSuffix,
15
- buildEditSuffix,
16
- deriveNamespace,
17
- isChildSession as isChildSessionDirect,
18
- isChildSubagentSession as isChildSubagentSessionDirect,
19
- MemorealHooksPlugin,
20
- setup,
21
- } from "../opencode/memoreal-hooks.js"
22
- import memorealDefault from "../opencode/memoreal-hooks.js"
23
-
24
- import {
25
- isPlaceholderApiKey as isPlaceholderReexported,
26
- ONBOARDING_WIZARD_PROMPT as ONBOARDING_PROMPT_REEXPORTED,
27
- deriveNamespace as deriveNamespaceReexported,
28
- isChildSession as isChildSessionReexported,
29
- isChildSubagentSession as isChildSubagentSessionReexported,
30
- MemorealHooksPlugin as PluginReexported,
31
- MemoriaHooksPlugin,
32
- setup as setupReexported,
33
- } from "../opencode/memoria-hooks.js"
34
- import memoriaDefault from "../opencode/memoria-hooks.js"
35
-
36
- describe("WS-3: Silent-When-Unregistered Hooks, Doctor Sync & Onboarding Wizard", () => {
37
- let tempHome
38
- let originalEnv
39
-
40
- beforeEach(() => {
41
- originalEnv = { ...process.env }
42
- tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "memoreal-hooks-test-"))
43
- delete process.env.MEMOREAL_API_KEY
44
- delete process.env.MEMORIA_API_KEY
45
- delete process.env.MEMOREAL_KEY
46
- delete process.env.MEMORIA_KEY
47
- delete process.env.MEMOREAL_API_URL
48
- delete process.env.MEMORIA_API_URL
49
- delete process.env.MEMOREAL_URL
50
- delete process.env.MEMORIA_URL
51
- delete process.env.PRD_FLASH_LEAF_WORKER
52
- process.env.MEMOREAL_HOME = tempHome
53
- })
54
-
55
- afterEach(() => {
56
- process.env = originalEnv
57
- try {
58
- fs.rmSync(tempHome, { recursive: true, force: true })
59
- } catch {}
60
- })
61
-
62
- describe("Atomic Change 3: Re-exports in opencode/memoria-hooks.js", () => {
63
- test("exports isPlaceholderApiKey and ONBOARDING_WIZARD_PROMPT identically", () => {
64
- assert.equal(typeof isPlaceholderDirect, "function")
65
- assert.equal(isPlaceholderDirect, isPlaceholderReexported)
66
- assert.equal(typeof ONBOARDING_PROMPT_DIRECT, "string")
67
- assert.equal(ONBOARDING_PROMPT_DIRECT, ONBOARDING_PROMPT_REEXPORTED)
68
- assert.equal(typeof isChildSessionDirect, "function")
69
- assert.equal(isChildSessionDirect, isChildSessionReexported)
70
- assert.equal(isChildSubagentSessionDirect, isChildSubagentSessionReexported)
71
- assert.equal(isChildSessionDirect, isChildSubagentSessionDirect)
72
- assert.equal(memorealDefault.isChildSession, isChildSessionDirect)
73
- assert.equal(memorealDefault.isChildSubagentSession, isChildSubagentSessionDirect)
74
- assert.equal(memoriaDefault.isChildSession, isChildSessionDirect)
75
- assert.equal(memoriaDefault.isChildSubagentSession, isChildSubagentSessionDirect)
76
- assert.equal(PluginReexported, MemorealHooksPlugin)
77
- assert.equal(MemoriaHooksPlugin, MemorealHooksPlugin)
78
- assert.equal(setupReexported, setup)
79
- })
80
-
81
- test("ONBOARDING_WIZARD_PROMPT contains 3-Click Wizard instructions across all steps and includes ?tool=opencode", () => {
82
- assert.match(ONBOARDING_PROMPT_DIRECT, /3-Click Interactive In-Chat Wizard/)
83
- assert.match(ONBOARDING_PROMPT_DIRECT, /AskUserQuestion \(Claude Code\) or question \(OpenCode & Cursor\)/)
84
- assert.match(ONBOARDING_PROMPT_DIRECT, /Step 1: Present choice card "Connect in 1 Click via Google \/ Browser \(Recommended\)" vs "Skip for this session"/)
85
- assert.match(ONBOARDING_PROMPT_DIRECT, /Step 2: Call connect_account\(\{ action: "start" \}\)/)
86
- assert.match(ONBOARDING_PROMPT_DIRECT, /https:\/\/memoreal\.kolivri\.com\/connect\?code=XXXX-YYYY/)
87
- assert.match(ONBOARDING_PROMPT_DIRECT, /"I clicked Authorize — Verify"/)
88
- assert.match(ONBOARDING_PROMPT_DIRECT, /Step 3: Once connected, present choice card "Yes — Index repo now \(Recommended\)" vs "Later"/)
89
- assert.match(ONBOARDING_PROMPT_DIRECT, /Never ask the user to paste their raw API key into chat/)
90
- assert.match(ONBOARDING_PROMPT_DIRECT, /https:\/\/memoreal\.kolivri\.com\/connect\?tool=opencode/)
91
- assert.match(ONBOARDING_PROMPT_DIRECT, /tool: "opencode"/)
92
- assert.match(ONBOARDING_PROMPT_DIRECT, /client_name: "OpenCode"/)
93
- })
94
- })
95
-
96
- describe("Atomic Change 2: Placeholder Filtering & resolveCloudConfig in opencode/memoreal-hooks.js", () => {
97
- test("isPlaceholderApiKey identifies common placeholder patterns", () => {
98
- assert.equal(isPlaceholderDirect("mem_dev_your_key_here"), true)
99
- assert.equal(isPlaceholderDirect("YOUR_API_KEY"), true)
100
- assert.equal(isPlaceholderDirect("your_api_key"), true)
101
- assert.equal(isPlaceholderDirect("your-memoreal-api-key"), true)
102
- assert.equal(isPlaceholderDirect("mem_dev_..."), true)
103
- assert.equal(isPlaceholderDirect("<MEMOREAL_API_KEY>"), true)
104
- assert.equal(isPlaceholderDirect("${MEMOREAL_API_KEY}"), true)
105
- assert.equal(isPlaceholderDirect('"YOUR_API_KEY"'), true)
106
- assert.equal(isPlaceholderDirect(""), true)
107
- assert.equal(isPlaceholderDirect(null), true)
108
- assert.equal(isPlaceholderDirect(undefined), true)
109
-
110
- // Valid keys should not be treated as placeholders
111
- assert.equal(isPlaceholderDirect("mem_dev_live_1234567890abcdef"), false)
112
- assert.equal(isPlaceholderDirect("sk_real_token_value"), false)
113
- })
114
-
115
- test("resolveCloudConfig returns empty apiKey for empty directory or placeholder keys", () => {
116
- // 1. Unregistered empty dir
117
- const unreg = resolveCloudConfig(tempHome)
118
- assert.equal(unreg.apiKey, "")
119
-
120
- // 2. Env placeholder
121
- process.env.MEMOREAL_API_KEY = "mem_dev_your_key_here"
122
- const envPlaceholder = resolveCloudConfig(tempHome)
123
- assert.equal(envPlaceholder.apiKey, "")
124
-
125
- // 3. Config file placeholder
126
- delete process.env.MEMOREAL_API_KEY
127
- const configDir = path.join(tempHome, ".memoreal")
128
- fs.mkdirSync(configDir, { recursive: true })
129
- fs.writeFileSync(path.join(configDir, "config.env"), 'MEMOREAL_API_KEY="YOUR_API_KEY"\n')
130
- const filePlaceholder = resolveCloudConfig(tempHome)
131
- assert.equal(filePlaceholder.apiKey, "")
132
-
133
- // 4. Valid key
134
- fs.writeFileSync(path.join(configDir, "config.env"), 'MEMOREAL_API_KEY="mem_dev_valid_token_xyz"\n')
135
- const valid = resolveCloudConfig(tempHome)
136
- assert.equal(valid.apiKey, "mem_dev_valid_token_xyz")
137
- })
138
-
139
- test("resolveCloudConfig falls through from placeholder MEMOREAL_API_KEY to valid MEMORIA_API_KEY or config.env", () => {
140
- // 1. Env fall-through from placeholder MEMOREAL_API_KEY to valid MEMORIA_API_KEY
141
- process.env.MEMOREAL_API_KEY = "mem_dev_your_key_here"
142
- process.env.MEMORIA_API_KEY = "mem_dev_valid_env_key"
143
- const res1 = resolveCloudConfig(tempHome)
144
- assert.equal(res1.apiKey, "mem_dev_valid_env_key")
145
-
146
- // 2. File fall-through when all env candidates are placeholders
147
- delete process.env.MEMORIA_API_KEY
148
- const configDir = path.join(tempHome, ".memoreal")
149
- fs.mkdirSync(configDir, { recursive: true })
150
- fs.writeFileSync(path.join(configDir, "config.env"), 'MEMOREAL_API_KEY="mem_dev_valid_file_key"\n')
151
- const res2 = resolveCloudConfig(tempHome)
152
- assert.equal(res2.apiKey, "mem_dev_valid_file_key")
153
- })
154
-
155
- test("resolveCloudConfig honors explicit empty MEMOREAL_API_KEY with unset MEMOREAL_HOME", () => {
156
- delete process.env.MEMOREAL_HOME
157
- process.env.MEMOREAL_API_KEY = ""
158
- const cfg = resolveCloudConfig()
159
- assert.equal(cfg.apiKey, "")
160
- })
161
-
162
- test("fetchSessionStartContext returns ONBOARDING_WIZARD_PROMPT without calling health when unconfigured", async () => {
163
- const res = await fetchSessionStartContext(process.cwd(), tempHome)
164
- assert.equal(res, ONBOARDING_PROMPT_DIRECT)
165
- })
166
-
167
- test("buildReadSuffix, buildWriteSuffix, buildEditSuffix return empty string when unregistered", () => {
168
- assert.equal(buildReadSuffix("README.md", "my-ns", tempHome), "")
169
- assert.equal(buildWriteSuffix("src/main.ts", "my-ns", tempHome), "")
170
- assert.equal(buildEditSuffix("src/main.ts", "my-ns", tempHome), "")
171
- })
172
-
173
- test("deriveNamespace strips /.worktrees/.*, /.claude/worktrees/.*, and /.opencode/worktrees/.*", () => {
174
- assert.equal(
175
- deriveNamespace("/Users/alice/projects/repo/.worktrees/feat-branch"),
176
- "-Users-alice-projects-repo"
177
- )
178
- assert.equal(
179
- deriveNamespace("/Users/alice/projects/repo/.claude/worktrees/feat-branch"),
180
- "-Users-alice-projects-repo"
181
- )
182
- assert.equal(
183
- deriveNamespace("/Users/alice/projects/repo/.opencode/worktrees/feat-branch"),
184
- "-Users-alice-projects-repo"
185
- )
186
- })
187
-
188
- test("isChildSession identifies child sessions via parentID, agent: flash-worker, cache, and PRD_FLASH_LEAF_WORKER", async () => {
189
- const cache = new Map()
190
- const mockCtx = {
191
- session: {
192
- get: async ({ sessionID }) => {
193
- if (sessionID === "child-p") return { id: "child-p", parentID: "root-1" }
194
- if (sessionID === "child-a") return { id: "child-a", agent: "flash-worker" }
195
- if (sessionID === "root-1") return { id: "root-1" }
196
- throw new Error("unknown session")
197
- },
198
- },
199
- }
200
-
201
- // Root session
202
- assert.equal(await isChildSessionDirect(mockCtx, "root-1", cache), false)
203
- assert.equal(cache.get("root-1"), false)
204
- // Hits cache
205
- assert.equal(await isChildSessionDirect(mockCtx, "root-1", cache), false)
206
-
207
- // Child with parentID
208
- assert.equal(await isChildSessionDirect(mockCtx, "child-p", cache), true)
209
- assert.equal(cache.get("child-p"), true)
210
-
211
- // Child with agent: flash-worker
212
- assert.equal(await isChildSessionDirect(mockCtx, "child-a", cache), true)
213
-
214
- // Fallback to PRD_FLASH_LEAF_WORKER when ctx has no session.get
215
- assert.equal(await isChildSessionDirect({}, "any"), false)
216
- process.env.PRD_FLASH_LEAF_WORKER = "1"
217
- assert.equal(await isChildSessionDirect({}, "any"), true)
218
- delete process.env.PRD_FLASH_LEAF_WORKER
219
- })
220
- })
221
-
222
- describe("Atomic Change 2: OpenCode Plugin Hook Suppression when Unregistered", () => {
223
- test("MemorealHooksPlugin stays silent on tool execution, compaction, and stop when unregistered", async () => {
224
- const plugin = await MemorealHooksPlugin({ directory: process.cwd() })
225
-
226
- // tool.execute.after stays silent
227
- const readOutput = { output: "file contents" }
228
- await plugin["tool.execute.after"]({ tool: "read", args: { path: "README.md" } }, readOutput)
229
- assert.equal(readOutput.output, "file contents")
230
-
231
- const writeOutput = { output: "ok" }
232
- await plugin["tool.execute.after"]({ tool: "write", args: { path: "main.ts" } }, writeOutput)
233
- assert.equal(writeOutput.output, "ok")
234
-
235
- const editOutput = { output: "ok" }
236
- await plugin["tool.execute.after"]({ tool: "edit", args: { path: "main.ts" } }, editOutput)
237
- assert.equal(editOutput.output, "ok")
238
-
239
- const todoOutput = { output: "todos" }
240
- await plugin["tool.execute.after"]({ tool: "todowrite", args: { todos: [{ content: "task1" }] } }, todoOutput)
241
- assert.equal(todoOutput.output, "todos")
242
-
243
- // compaction stays silent
244
- const compactOutput = { context: [] }
245
- await plugin["experimental.session.compacting"]({}, compactOutput)
246
- assert.deepEqual(compactOutput.context, [])
247
-
248
- // session.idle stays silent
249
- await plugin.event({ event: { type: "session.idle", sessionID: "s1" } })
250
-
251
- // chat.message with correction does not produce correction output when unregistered
252
- await plugin["chat.message"]({ sessionID: "s1" }, { parts: [{ type: "text", text: "no, that is wrong" }] })
253
- const systemOutput = { system: [] }
254
- await plugin["experimental.chat.system.transform"]({ sessionID: "s1" }, systemOutput)
255
- // Only the one-time onboarding wizard prompt is injected, NO correction message!
256
- assert.equal(systemOutput.system.length, 1)
257
- assert.equal(systemOutput.system[0], ONBOARDING_PROMPT_DIRECT)
258
- })
259
-
260
- test("setup (V2) stays silent on tool execution, compaction, and stop when unregistered", async () => {
261
- const hooksRegistered = new Map()
262
- const mockCtx = {
263
- location: { directory: process.cwd() },
264
- session: {
265
- hook: async (name, handler) => {
266
- hooksRegistered.set(`session.${name}`, handler)
267
- },
268
- },
269
- tool: {
270
- hook: async (name, handler) => {
271
- hooksRegistered.set(`tool.${name}`, handler)
272
- },
273
- },
274
- event: {
275
- subscribe: async function* () {
276
- // empty async iterator
277
- },
278
- },
279
- }
280
-
281
- await setup(mockCtx)
282
-
283
- // tool.execute.after stays silent
284
- const toolHook = hooksRegistered.get("tool.execute.after")
285
- const resultObj = { content: "initial content" }
286
- await toolHook({ status: "completed", tool: "read", input: { path: "README.md" }, result: resultObj })
287
- assert.equal(resultObj.content, "initial content")
288
-
289
- // compaction stays silent
290
- const compactionHook = hooksRegistered.get("session.compaction")
291
- const compactionEvent = { system: [] }
292
- await compactionHook(compactionEvent)
293
- assert.deepEqual(compactionEvent.system, [])
294
-
295
- // context hook produces only the wizard prompt
296
- const contextHook = hooksRegistered.get("session.context")
297
- const contextEvent = { sessionID: "s2", system: [] }
298
- await contextHook(contextEvent)
299
- assert.equal(contextEvent.system.length, 1)
300
- assert.equal(contextEvent.system[0].text, ONBOARDING_PROMPT_DIRECT)
301
- })
302
-
303
- test("MemorealHooksPlugin emits ONBOARDING_WIZARD_PROMPT only once per session across multiple turns", async () => {
304
- const plugin = await MemorealHooksPlugin({ directory: process.cwd() })
305
- const sessionID = "session-multiturn-test"
306
-
307
- // Turn 1
308
- const turn1Output = { system: [] }
309
- await plugin["experimental.chat.system.transform"]({ sessionID }, turn1Output)
310
- assert.equal(turn1Output.system.length, 1)
311
- assert.equal(turn1Output.system[0], ONBOARDING_PROMPT_DIRECT)
312
-
313
- // Turn 2 in same session
314
- const turn2Output = { system: [] }
315
- await plugin["experimental.chat.system.transform"]({ sessionID }, turn2Output)
316
- assert.equal(turn2Output.system.length, 0, "Turn 2 must not re-emit ONBOARDING_WIZARD_PROMPT")
317
-
318
- // Turn 3 in same session
319
- const turn3Output = { system: [] }
320
- await plugin["experimental.chat.system.transform"]({ sessionID }, turn3Output)
321
- assert.equal(turn3Output.system.length, 0, "Turn 3 must not re-emit ONBOARDING_WIZARD_PROMPT")
322
-
323
- // Different session starts fresh
324
- const otherSessionOutput = { system: [] }
325
- await plugin["experimental.chat.system.transform"]({ sessionID: "different-session" }, otherSessionOutput)
326
- assert.equal(otherSessionOutput.system.length, 1)
327
- assert.equal(otherSessionOutput.system[0], ONBOARDING_PROMPT_DIRECT)
328
- })
329
-
330
- test("setup (V2) emits ONBOARDING_WIZARD_PROMPT only once per session across multiple turns", async () => {
331
- const hooksRegistered = new Map()
332
- const mockCtx = {
333
- location: { directory: process.cwd() },
334
- session: {
335
- hook: async (name, handler) => {
336
- hooksRegistered.set(`session.${name}`, handler)
337
- },
338
- },
339
- tool: {
340
- hook: async (name, handler) => {
341
- hooksRegistered.set(`tool.${name}`, handler)
342
- },
343
- },
344
- event: {
345
- subscribe: async function* () {},
346
- },
347
- }
348
-
349
- await setup(mockCtx)
350
- const contextHook = hooksRegistered.get("session.context")
351
- const sessionID = "setup-multiturn-test"
352
-
353
- // Turn 1
354
- const event1 = { sessionID, system: [] }
355
- await contextHook(event1)
356
- assert.equal(event1.system.length, 1)
357
- assert.equal(event1.system[0].text, ONBOARDING_PROMPT_DIRECT)
358
-
359
- // Turn 2
360
- const event2 = { sessionID, system: [] }
361
- await contextHook(event2)
362
- assert.equal(event2.system.length, 0, "Turn 2 must not re-emit ONBOARDING_WIZARD_PROMPT")
363
-
364
- // Turn 3
365
- const event3 = { sessionID, system: [] }
366
- await contextHook(event3)
367
- assert.equal(event3.system.length, 0, "Turn 3 must not re-emit ONBOARDING_WIZARD_PROMPT")
368
- })
369
- })
370
-
371
- describe("Atomic Change 1: hooks/hooks.json Shell Execution", () => {
372
- const hooksJsonPath = path.resolve("hooks/hooks.json")
373
- const hooksData = JSON.parse(fs.readFileSync(hooksJsonPath, "utf8"))
374
-
375
- test("hooks/hooks.json is valid and contains all expected hook types", () => {
376
- assert.ok(hooksData.hooks.SessionStart)
377
- assert.ok(hooksData.hooks.PreCompact)
378
- assert.ok(hooksData.hooks.PostCompact)
379
- assert.ok(hooksData.hooks.UserPromptSubmit)
380
- assert.ok(hooksData.hooks.PostToolUse)
381
- assert.ok(hooksData.hooks.TaskCompleted)
382
- assert.ok(hooksData.hooks.Stop)
383
- })
384
-
385
- test("SessionStart hook emits the 3-Click Wizard prompt and exits 0 when unregistered", () => {
386
- const cmd = hooksData.hooks.SessionStart[0].hooks[0].command
387
- const res = cp.spawnSync("sh", ["-c", cmd], {
388
- env: {
389
- ...process.env,
390
- MEMOREAL_HOME: tempHome,
391
- MEMOREAL_API_KEY: "",
392
- MEMORIA_API_KEY: "",
393
- MEMOREAL_KEY: "",
394
- MEMORIA_KEY: "",
395
- },
396
- encoding: "utf8",
397
- })
398
-
399
- assert.equal(res.status, 0)
400
- assert.equal(res.stderr, "", `SessionStart produced stderr when unregistered: ${res.stderr}`)
401
- assert.match(res.stdout, /\[memoreal-session-start\] Memoreal Cloud is not yet connected\./)
402
- assert.match(res.stdout, /Drive the 3-Click Interactive In-Chat Wizard/)
403
- assert.match(res.stdout, /Step 1: Present choice card "Connect in 1 Click via Google \/ Browser \(Recommended\)"/)
404
- assert.match(res.stdout, /Step 2: Call connect_account\(\{ action: "start" \}\)/)
405
- assert.match(res.stdout, /Step 3: Once connected, present choice card "Yes — Index repo now \(Recommended\)"/)
406
- assert.match(res.stdout, /Never ask the user to paste a raw API key into chat\./)
407
- assert.doesNotMatch(res.stdout, /build_context/)
408
- })
409
-
410
- test("SessionStart hook emits the 3-Click Wizard prompt when placeholder key is used", () => {
411
- const cmd = hooksData.hooks.SessionStart[0].hooks[0].command
412
- const res = cp.spawnSync("sh", ["-c", cmd], {
413
- env: {
414
- ...process.env,
415
- MEMOREAL_HOME: tempHome,
416
- MEMOREAL_API_KEY: "mem_dev_your_key_here",
417
- },
418
- encoding: "utf8",
419
- })
420
-
421
- assert.equal(res.status, 0)
422
- assert.equal(res.stderr, "", `SessionStart with placeholder produced stderr: ${res.stderr}`)
423
- assert.match(res.stdout, /\[memoreal-session-start\] Memoreal Cloud is not yet connected\./)
424
- assert.match(res.stdout, /Drive the 3-Click Interactive In-Chat Wizard/)
425
- })
426
-
427
- test("Non-SessionStart hooks stay 100% silent (exit 0, stdout empty) when unregistered", () => {
428
- const silentHooks = [
429
- { name: "PreCompact", cmd: hooksData.hooks.PreCompact[0].hooks[0].command },
430
- { name: "PostCompact", cmd: hooksData.hooks.PostCompact[0].hooks[0].command },
431
- {
432
- name: "UserPromptSubmit",
433
- cmd: hooksData.hooks.UserPromptSubmit[0].hooks[0].command,
434
- stdin: JSON.stringify({ prompt: "no, that is wrong, stop" }),
435
- },
436
- {
437
- name: "PostToolUse (TaskCreate)",
438
- cmd: hooksData.hooks.PostToolUse.find((h) => h.matcher === "TaskCreate").hooks[0].command,
439
- },
440
- {
441
- name: "PostToolUse (Write)",
442
- cmd: hooksData.hooks.PostToolUse.find((h) => h.matcher === "Write").hooks[0].command,
443
- stdin: JSON.stringify({ tool_input: { file_path: "src/main.ts" } }),
444
- },
445
- {
446
- name: "PostToolUse (Edit)",
447
- cmd: hooksData.hooks.PostToolUse.find((h) => h.matcher === "Edit").hooks[0].command,
448
- stdin: JSON.stringify({ tool_input: { file_path: "src/main.ts" } }),
449
- },
450
- {
451
- name: "PostToolUse (Read)",
452
- cmd: hooksData.hooks.PostToolUse.find((h) => h.matcher === "Read").hooks[0].command,
453
- stdin: JSON.stringify({ tool_input: { file_path: "README.md" } }),
454
- },
455
- { name: "TaskCompleted", cmd: hooksData.hooks.TaskCompleted[0].hooks[0].command },
456
- { name: "Stop", cmd: hooksData.hooks.Stop[0].hooks[0].command },
457
- ]
458
-
459
- for (const { name, cmd, stdin } of silentHooks) {
460
- const res = cp.spawnSync("sh", ["-c", cmd], {
461
- input: stdin || "",
462
- env: {
463
- ...process.env,
464
- MEMOREAL_HOME: tempHome,
465
- MEMOREAL_API_KEY: "",
466
- MEMORIA_API_KEY: "",
467
- MEMOREAL_KEY: "",
468
- MEMORIA_KEY: "",
469
- },
470
- encoding: "utf8",
471
- })
472
-
473
- assert.equal(res.status, 0, `Hook ${name} failed with status ${res.status}: ${res.stderr}`)
474
- assert.equal(res.stderr, "", `Hook ${name} produced stderr when unregistered: ${res.stderr}`)
475
- assert.equal(res.stdout, "", `Hook ${name} produced unexpected stdout when unregistered: ${res.stdout}`)
476
- }
477
- })
478
-
479
- test("Non-SessionStart hooks stay 100% silent when placeholder key is in environment or config.env", () => {
480
- const readCmd = hooksData.hooks.PostToolUse.find((h) => h.matcher === "Read").hooks[0].command
481
- const writeCmd = hooksData.hooks.PostToolUse.find((h) => h.matcher === "Write").hooks[0].command
482
- const editCmd = hooksData.hooks.PostToolUse.find((h) => h.matcher === "Edit").hooks[0].command
483
-
484
- const placeholderKeys = [
485
- "mem_dev_your_key_here",
486
- "YOUR_API_KEY",
487
- "your-memoreal-api-key",
488
- "mem_dev_...",
489
- "<MEMOREAL_API_KEY>",
490
- "${MEMOREAL_API_KEY}",
491
- ]
492
-
493
- for (const placeholder of placeholderKeys) {
494
- // Test Read
495
- const readRes = cp.spawnSync("sh", ["-c", readCmd], {
496
- input: JSON.stringify({ tool_input: { file_path: "README.md" } }),
497
- env: { ...process.env, MEMOREAL_HOME: tempHome, MEMOREAL_API_KEY: placeholder },
498
- encoding: "utf8",
499
- })
500
- assert.equal(readRes.status, 0)
501
- assert.equal(readRes.stderr, "")
502
- assert.equal(readRes.stdout, "", `Read hook with placeholder ${placeholder} emitted stdout`)
503
-
504
- // Test Write
505
- const writeRes = cp.spawnSync("sh", ["-c", writeCmd], {
506
- input: JSON.stringify({ tool_input: { file_path: "src/app.ts" } }),
507
- env: { ...process.env, MEMOREAL_HOME: tempHome, MEMOREAL_API_KEY: placeholder },
508
- encoding: "utf8",
509
- })
510
- assert.equal(writeRes.status, 0)
511
- assert.equal(writeRes.stderr, "")
512
- assert.equal(writeRes.stdout, "", `Write hook with placeholder ${placeholder} emitted stdout`)
513
-
514
- // Test Edit
515
- const editRes = cp.spawnSync("sh", ["-c", editCmd], {
516
- input: JSON.stringify({ tool_input: { file_path: "src/app.ts" } }),
517
- env: { ...process.env, MEMOREAL_HOME: tempHome, MEMOREAL_API_KEY: placeholder },
518
- encoding: "utf8",
519
- })
520
- assert.equal(editRes.status, 0)
521
- assert.equal(editRes.stderr, "")
522
- assert.equal(editRes.stdout, "", `Edit hook with placeholder ${placeholder} emitted stdout`)
523
- }
524
- })
525
-
526
- test("Hooks emit contextual memory prompts when valid API key is present", () => {
527
- let p = process.cwd()
528
- p = p.replace(/\/\.worktrees\/.*$/, "").replace(/\/\.claude\/worktrees\/.*$/, "").replace(/\/\.opencode\/worktrees\/.*$/, "")
529
- const expectedNs = p.replace(/\//g, "-")
530
- assert.ok(expectedNs.length > 0)
531
-
532
- const readCmd = hooksData.hooks.PostToolUse.find((h) => h.matcher === "Read").hooks[0].command
533
- const writeCmd = hooksData.hooks.PostToolUse.find((h) => h.matcher === "Write").hooks[0].command
534
- const editCmd = hooksData.hooks.PostToolUse.find((h) => h.matcher === "Edit").hooks[0].command
535
-
536
- const validEnv = {
537
- ...process.env,
538
- MEMOREAL_HOME: tempHome,
539
- MEMOREAL_API_KEY: "mem_dev_valid_authenticated_key_123",
540
- }
541
-
542
- // Read on Markdown
543
- const readRes = cp.spawnSync("sh", ["-c", readCmd], {
544
- input: JSON.stringify({ tool_input: { file_path: "README.md" } }),
545
- env: validEnv,
546
- encoding: "utf8",
547
- })
548
- assert.equal(readRes.status, 0)
549
- assert.equal(readRes.stderr, "")
550
- assert.match(readRes.stdout, /\[memoreal-recall-doc\] Reading: README\.md/)
551
- assert.match(readRes.stdout, new RegExp(`\\(namespace: ${expectedNs}\\)`))
552
-
553
- // Write on code file
554
- const writeRes = cp.spawnSync("sh", ["-c", writeCmd], {
555
- input: JSON.stringify({ tool_input: { file_path: "src/index.ts" } }),
556
- env: validEnv,
557
- encoding: "utf8",
558
- })
559
- assert.equal(writeRes.status, 0)
560
- assert.equal(writeRes.stderr, "")
561
- assert.match(writeRes.stdout, /\[memoreal-encode-code\] Code file written: src\/index\.ts/)
562
- assert.match(writeRes.stdout, new RegExp(`\\(namespace: ${expectedNs}\\)`))
563
-
564
- // Edit on code file
565
- const editRes = cp.spawnSync("sh", ["-c", editCmd], {
566
- input: JSON.stringify({ tool_input: { file_path: "src/index.ts" } }),
567
- env: validEnv,
568
- encoding: "utf8",
569
- })
570
- assert.equal(editRes.status, 0)
571
- assert.equal(editRes.stderr, "")
572
- assert.match(editRes.stdout, /\[memoreal-encode-code\] Code file edited: src\/index\.ts/)
573
- assert.match(editRes.stdout, new RegExp(`\\(namespace: ${expectedNs}\\)`))
574
- })
575
-
576
- test("ALL 10 hooks: fallback NS matches PWD (stripping worktrees) with zero stderr when registered without bin/memoreal-ns", () => {
577
- let p = process.cwd()
578
- p = p.replace(/\/\.worktrees\/.*$/, "").replace(/\/\.claude\/worktrees\/.*$/, "").replace(/\/\.opencode\/worktrees\/.*$/, "")
579
- const expectedNs = p.replace(/\//g, "-")
580
- assert.ok(expectedNs.length > 0)
581
-
582
- const validEnv = {
583
- ...process.env,
584
- MEMOREAL_HOME: tempHome,
585
- MEMOREAL_API_KEY: "mem_dev_valid_authenticated_key_123",
586
- }
587
-
588
- // 1. SessionStart
589
- const startRes = cp.spawnSync("sh", ["-c", hooksData.hooks.SessionStart[0].hooks[0].command], {
590
- env: validEnv,
591
- encoding: "utf8",
592
- })
593
- assert.equal(startRes.status, 0)
594
- assert.equal(startRes.stderr, "")
595
- assert.match(startRes.stdout, new RegExp(`namespace[=:\\s"]+${expectedNs}`))
596
-
597
- // 2. PreCompact
598
- const preCompactRes = cp.spawnSync("sh", ["-c", hooksData.hooks.PreCompact[0].hooks[0].command], {
599
- env: validEnv,
600
- encoding: "utf8",
601
- })
602
- assert.equal(preCompactRes.status, 0)
603
- assert.equal(preCompactRes.stderr, "")
604
- assert.match(preCompactRes.stdout, new RegExp(`namespace[=:\\s"]+${expectedNs}`))
605
-
606
- // 3. PostCompact
607
- const postCompactRes = cp.spawnSync("sh", ["-c", hooksData.hooks.PostCompact[0].hooks[0].command], {
608
- env: validEnv,
609
- encoding: "utf8",
610
- })
611
- assert.equal(postCompactRes.status, 0)
612
- assert.equal(postCompactRes.stderr, "")
613
- assert.match(postCompactRes.stdout, new RegExp(`namespace[=:\\s"]+${expectedNs}`))
614
-
615
- // 4. UserPromptSubmit
616
- const promptRes = cp.spawnSync("sh", ["-c", hooksData.hooks.UserPromptSubmit[0].hooks[0].command], {
617
- input: JSON.stringify({ prompt: "no, that is wrong, please fix it" }),
618
- env: validEnv,
619
- encoding: "utf8",
620
- })
621
- assert.equal(promptRes.status, 0)
622
- assert.equal(promptRes.stderr, "")
623
- assert.match(promptRes.stdout, new RegExp(`namespace[=:\\s"]+${expectedNs}`))
624
-
625
- // 5. PostToolUse (TaskCreate)
626
- const taskCreateRes = cp.spawnSync("sh", ["-c", hooksData.hooks.PostToolUse.find((h) => h.matcher === "TaskCreate").hooks[0].command], {
627
- env: validEnv,
628
- encoding: "utf8",
629
- })
630
- assert.equal(taskCreateRes.status, 0)
631
- assert.equal(taskCreateRes.stderr, "")
632
- assert.match(taskCreateRes.stdout, new RegExp(`namespace[=:\\s"]+${expectedNs}`))
633
-
634
- // 6. PostToolUse (Write)
635
- const writeRes = cp.spawnSync("sh", ["-c", hooksData.hooks.PostToolUse.find((h) => h.matcher === "Write").hooks[0].command], {
636
- input: JSON.stringify({ tool_input: { file_path: "src/file.ts" } }),
637
- env: validEnv,
638
- encoding: "utf8",
639
- })
640
- assert.equal(writeRes.status, 0)
641
- assert.equal(writeRes.stderr, "")
642
- assert.match(writeRes.stdout, new RegExp(`namespace[=:\\s"]+${expectedNs}`))
643
-
644
- // 7. PostToolUse (Edit)
645
- const editRes = cp.spawnSync("sh", ["-c", hooksData.hooks.PostToolUse.find((h) => h.matcher === "Edit").hooks[0].command], {
646
- input: JSON.stringify({ tool_input: { file_path: "src/file.ts" } }),
647
- env: validEnv,
648
- encoding: "utf8",
649
- })
650
- assert.equal(editRes.status, 0)
651
- assert.equal(editRes.stderr, "")
652
- assert.match(editRes.stdout, new RegExp(`namespace[=:\\s"]+${expectedNs}`))
653
-
654
- // 8. PostToolUse (Read)
655
- const readRes = cp.spawnSync("sh", ["-c", hooksData.hooks.PostToolUse.find((h) => h.matcher === "Read").hooks[0].command], {
656
- input: JSON.stringify({ tool_input: { file_path: "README.md" } }),
657
- env: validEnv,
658
- encoding: "utf8",
659
- })
660
- assert.equal(readRes.status, 0)
661
- assert.equal(readRes.stderr, "")
662
- assert.match(readRes.stdout, new RegExp(`namespace[=:\\s"]+${expectedNs}`))
663
-
664
- // 9. TaskCompleted
665
- const taskCompletedRes = cp.spawnSync("sh", ["-c", hooksData.hooks.TaskCompleted[0].hooks[0].command], {
666
- env: validEnv,
667
- encoding: "utf8",
668
- })
669
- assert.equal(taskCompletedRes.status, 0)
670
- assert.equal(taskCompletedRes.stderr, "")
671
- assert.match(taskCompletedRes.stdout, new RegExp(`namespace[=:\\s"]+${expectedNs}`))
672
-
673
- // 10. Stop
674
- const stopRes = cp.spawnSync("sh", ["-c", hooksData.hooks.Stop[0].hooks[0].command], {
675
- env: validEnv,
676
- encoding: "utf8",
677
- })
678
- assert.equal(stopRes.status, 0)
679
- assert.equal(stopRes.stderr, "")
680
- assert.match(stopRes.stdout, new RegExp(`namespace[=:\\s"]+${expectedNs}`))
681
- })
682
-
683
- test("hooks.json: placeholder MEMOREAL_API_KEY in environment falls through to valid MEMORIA_API_KEY", () => {
684
- let p = process.cwd()
685
- p = p.replace(/\/\.worktrees\/.*$/, "").replace(/\/\.claude\/worktrees\/.*$/, "").replace(/\/\.opencode\/worktrees\/.*$/, "")
686
- const expectedNs = p.replace(/\//g, "-")
687
-
688
- const readCmd = hooksData.hooks.PostToolUse.find((h) => h.matcher === "Read").hooks[0].command
689
- const res = cp.spawnSync("sh", ["-c", readCmd], {
690
- input: JSON.stringify({ tool_input: { file_path: "README.md" } }),
691
- env: {
692
- ...process.env,
693
- MEMOREAL_HOME: tempHome,
694
- MEMOREAL_API_KEY: "mem_dev_your_key_here",
695
- MEMORIA_API_KEY: "mem_dev_valid_authenticated_key_123",
696
- },
697
- encoding: "utf8",
698
- })
699
- assert.equal(res.status, 0)
700
- assert.equal(res.stderr, "")
701
- assert.match(res.stdout, /\[memoreal-recall-doc\] Reading: README\.md/)
702
- assert.match(res.stdout, new RegExp(`\\(namespace: ${expectedNs}\\)`))
703
- })
704
-
705
- test("hooks.json: placeholder MEMOREAL_API_KEY in environment falls through to valid config.env key", () => {
706
- let p = process.cwd()
707
- p = p.replace(/\/\.worktrees\/.*$/, "").replace(/\/\.claude\/worktrees\/.*$/, "").replace(/\/\.opencode\/worktrees\/.*$/, "")
708
- const expectedNs = p.replace(/\//g, "-")
709
-
710
- const configDir = path.join(tempHome, ".memoreal")
711
- fs.mkdirSync(configDir, { recursive: true })
712
- fs.writeFileSync(path.join(configDir, "config.env"), 'MEMOREAL_API_KEY="mem_dev_valid_token_from_file"\n')
713
-
714
- const readCmd = hooksData.hooks.PostToolUse.find((h) => h.matcher === "Read").hooks[0].command
715
- const res = cp.spawnSync("sh", ["-c", readCmd], {
716
- input: JSON.stringify({ tool_input: { file_path: "README.md" } }),
717
- env: {
718
- ...process.env,
719
- MEMOREAL_HOME: tempHome,
720
- MEMOREAL_API_KEY: "mem_dev_your_key_here",
721
- },
722
- encoding: "utf8",
723
- })
724
- assert.equal(res.status, 0)
725
- assert.equal(res.stderr, "")
726
- assert.match(res.stdout, /\[memoreal-recall-doc\] Reading: README\.md/)
727
- assert.match(res.stdout, new RegExp(`\\(namespace: ${expectedNs}\\)`))
728
- })
729
- })
730
-
731
- describe("Atomic Change 4: skills/memoreal-doctor/SKILL.md", () => {
732
- test("memoreal-doctor contains zero brain.kolivri.com references and guides to 3-Click Wizard", () => {
733
- const doctorPath = path.resolve("skills/memoreal-doctor/SKILL.md")
734
- const content = fs.readFileSync(doctorPath, "utf8")
735
-
736
- assert.equal(content.includes("brain.kolivri.com"), false, "Must not contain brain.kolivri.com")
737
- assert.match(content, /connect_account/, "Must mention connect_account tool")
738
- assert.match(content, /npx -y @kolivri\/memoreal-mcp setup/, "Must mention npx setup wizard")
739
- assert.match(content, /Placeholder key detection/i, "Must describe placeholder detection")
740
- assert.match(content, /NEVER ask the user to paste their raw API key into chat/i, "Must enforce no raw key pasting")
741
- })
742
- })
743
-
744
- describe("Atomic Change 5: OpenCode v2 setup & v1 MemorealHooksPlugin in Root vs Child Sessions (Registered)", () => {
745
- let origFetch
746
-
747
- beforeEach(() => {
748
- origFetch = globalThis.fetch
749
- globalThis.fetch = async () => ({
750
- ok: true,
751
- status: 200,
752
- text: async () => '{"status":"ok"}',
753
- })
754
- })
755
-
756
- afterEach(() => {
757
- globalThis.fetch = origFetch
758
- })
759
-
760
- test("v2 setup executes hooks in root session without ReferenceError and suppresses in child sessions", async () => {
761
- process.env.MEMOREAL_API_KEY = "mem_dev_valid123"
762
- const hooksRegistered = new Map()
763
- const eventQueue = []
764
-
765
- const mockCtx = {
766
- location: { directory: tempHome },
767
- session: {
768
- get: async ({ sessionID }) => {
769
- if (sessionID === "ses_root") {
770
- return { id: "ses_root", parentID: null, agent: "default" }
771
- }
772
- if (sessionID === "ses_child_parent") {
773
- return { id: "ses_child_parent", parentID: "ses_root", agent: "default" }
774
- }
775
- if (sessionID === "ses_child_agent") {
776
- return { id: "ses_child_agent", parentID: null, agent: "flash-worker" }
777
- }
778
- return null
779
- },
780
- hook: async (name, handler) => {
781
- hooksRegistered.set(`session.${name}`, handler)
782
- },
783
- },
784
- tool: {
785
- hook: async (name, handler) => {
786
- hooksRegistered.set(`tool.${name}`, handler)
787
- },
788
- },
789
- event: {
790
- subscribe: async function* ({ types, signal }) {
791
- while (!signal?.aborted) {
792
- if (eventQueue.length > 0) {
793
- yield eventQueue.shift()
794
- } else {
795
- await new Promise((r) => setTimeout(r, 10))
796
- }
797
- }
798
- },
799
- },
800
- }
801
-
802
- const cleanup = await setup(mockCtx)
803
-
804
- const toolHook = hooksRegistered.get("tool.execute.after")
805
- const compactionHook = hooksRegistered.get("session.compaction")
806
- const contextHook = hooksRegistered.get("session.context")
807
- const promptHook = hooksRegistered.get("session.prompt")
808
-
809
- // --- 1. ROOT SESSION (ses_root) ---
810
- // Read tool on markdown
811
- const rootReadResult = { content: "root read file" }
812
- await toolHook({
813
- status: "completed",
814
- tool: "read",
815
- input: { path: "README.md" },
816
- result: rootReadResult,
817
- sessionID: "ses_root",
818
- })
819
- assert.match(rootReadResult.content, /\[memoreal-recall-doc\]/)
820
-
821
- // Write tool on prd plan file
822
- const rootWriteResult = { content: "root write file" }
823
- await toolHook({
824
- status: "completed",
825
- tool: "write",
826
- input: { path: "prd/001.md" },
827
- result: rootWriteResult,
828
- sessionID: "ses_root",
829
- })
830
- assert.match(rootWriteResult.content, /\[memoreal-encode-plan\]/)
831
-
832
- // Edit tool on code file
833
- const rootEditResult = { content: "root edit file" }
834
- await toolHook({
835
- status: "completed",
836
- tool: "edit",
837
- input: { path: "src/main.ts" },
838
- result: rootEditResult,
839
- sessionID: "ses_root",
840
- })
841
- assert.match(rootEditResult.content, /\[memoreal-encode-code\]/)
842
-
843
- // Compaction hook
844
- const rootCompactionEvent = { sessionID: "ses_root", system: [] }
845
- await compactionHook(rootCompactionEvent)
846
- assert.equal(rootCompactionEvent.system.length, 1)
847
- assert.match(rootCompactionEvent.system[0].text, /\[memoreal-pre-compact\]/)
848
-
849
- // Session execution succeeded event
850
- eventQueue.push({
851
- type: "session.execution.succeeded",
852
- data: { sessionID: "ses_root" },
853
- })
854
- await new Promise((r) => setTimeout(r, 30))
855
- const rootContextEvent = { sessionID: "ses_root", system: [] }
856
- await contextHook(rootContextEvent)
857
- const stopText = rootContextEvent.system.find((s) => s.text?.includes("[memoreal-session-end]"))
858
- assert.ok(stopText, "session.execution.succeeded must cache stop summary for root session")
859
-
860
- // --- 2. CHILD SESSION via parentID (ses_child_parent) ---
861
- const childParentRead = { content: "child read" }
862
- await toolHook({
863
- status: "completed",
864
- tool: "read",
865
- input: { path: "README.md" },
866
- result: childParentRead,
867
- sessionID: "ses_child_parent",
868
- })
869
- assert.equal(childParentRead.content, "child read", "Must suppress read in child session (parentID)")
870
-
871
- const childParentWrite = { content: "child write" }
872
- await toolHook({
873
- status: "completed",
874
- tool: "write",
875
- input: { path: "prd/001.md" },
876
- result: childParentWrite,
877
- sessionID: "ses_child_parent",
878
- })
879
- assert.equal(childParentWrite.content, "child write", "Must suppress write in child session (parentID)")
880
-
881
- const childParentEdit = { content: "child edit" }
882
- await toolHook({
883
- status: "completed",
884
- tool: "edit",
885
- input: { path: "src/main.ts" },
886
- result: childParentEdit,
887
- sessionID: "ses_child_parent",
888
- })
889
- assert.equal(childParentEdit.content, "child edit", "Must suppress edit in child session (parentID)")
890
-
891
- const childParentCompaction = { sessionID: "ses_child_parent", system: [] }
892
- await compactionHook(childParentCompaction)
893
- assert.equal(childParentCompaction.system.length, 0, "Must suppress compaction in child session (parentID)")
894
-
895
- eventQueue.push({
896
- type: "session.execution.succeeded",
897
- data: { sessionID: "ses_child_parent" },
898
- })
899
- await new Promise((r) => setTimeout(r, 30))
900
- const childParentContext = { sessionID: "ses_child_parent", system: [] }
901
- await contextHook(childParentContext)
902
- const childStop = childParentContext.system.find((s) => s.text?.includes("[memoreal-session-end]"))
903
- assert.equal(childStop, undefined, "Must not cache stop summary for child session (parentID)")
904
-
905
- // --- 3. CHILD SESSION via agent: flash-worker (ses_child_agent) ---
906
- const childAgentRead = { content: "agent read" }
907
- await toolHook({
908
- status: "completed",
909
- tool: "read",
910
- input: { path: "README.md" },
911
- result: childAgentRead,
912
- sessionID: "ses_child_agent",
913
- })
914
- assert.equal(childAgentRead.content, "agent read", "Must suppress read in child session (agent: flash-worker)")
915
-
916
- const childAgentCompaction = { sessionID: "ses_child_agent", system: [] }
917
- await compactionHook(childAgentCompaction)
918
- assert.equal(childAgentCompaction.system.length, 0, "Must suppress compaction in child session (agent: flash-worker)")
919
-
920
- // --- 4. CHILD SESSION via PRD_FLASH_LEAF_WORKER="1" ---
921
- process.env.PRD_FLASH_LEAF_WORKER = "1"
922
- const envLeafRead = { content: "leaf read" }
923
- await toolHook({
924
- status: "completed",
925
- tool: "read",
926
- input: { path: "README.md" },
927
- result: envLeafRead,
928
- })
929
- assert.equal(envLeafRead.content, "leaf read", "Must suppress when PRD_FLASH_LEAF_WORKER=1")
930
- delete process.env.PRD_FLASH_LEAF_WORKER
931
-
932
- cleanup()
933
- })
934
-
935
- test("v1 MemorealHooksPlugin executes in root session without ReferenceError and suppresses in child sessions", async () => {
936
- process.env.MEMOREAL_API_KEY = "mem_dev_valid123"
937
-
938
- const client = {
939
- session: {
940
- get: async ({ sessionID }) => {
941
- if (sessionID === "ses_root") {
942
- return { id: "ses_root", parentID: null, agent: "default" }
943
- }
944
- if (sessionID === "ses_child_parent") {
945
- return { id: "ses_child_parent", parentID: "ses_root", agent: "default" }
946
- }
947
- if (sessionID === "ses_child_agent") {
948
- return { id: "ses_child_agent", parentID: null, agent: "flash-worker" }
949
- }
950
- return null
951
- },
952
- },
953
- }
954
-
955
- const plugin = await MemorealHooksPlugin({ directory: tempHome, client })
956
-
957
- // --- 1. ROOT SESSION ---
958
- const rootReadOutput = { output: "root output" }
959
- await plugin["tool.execute.after"](
960
- { tool: "read", args: { path: "README.md" }, sessionID: "ses_root" },
961
- rootReadOutput
962
- )
963
- assert.match(rootReadOutput.output, /\[memoreal-recall-doc\]/)
964
-
965
- const rootWriteOutput = { output: "root write" }
966
- await plugin["tool.execute.after"](
967
- { tool: "write", args: { path: "prd/001.md" }, sessionID: "ses_root" },
968
- rootWriteOutput
969
- )
970
- assert.match(rootWriteOutput.output, /\[memoreal-encode-plan\]/)
971
-
972
- const rootEditOutput = { output: "root edit" }
973
- await plugin["tool.execute.after"](
974
- { tool: "edit", args: { path: "src/main.ts" }, sessionID: "ses_root" },
975
- rootEditOutput
976
- )
977
- assert.match(rootEditOutput.output, /\[memoreal-encode-code\]/)
978
-
979
- const rootCompact = { context: [] }
980
- await plugin["experimental.session.compacting"]({ sessionID: "ses_root" }, rootCompact)
981
- assert.equal(rootCompact.context.length, 1)
982
- assert.match(rootCompact.context[0], /\[memoreal-pre-compact\]/)
983
-
984
- await plugin.event({ event: { type: "session.idle", sessionID: "ses_root" } })
985
- const rootTransform = { system: [] }
986
- await plugin["experimental.chat.system.transform"]({ sessionID: "ses_root" }, rootTransform)
987
- assert.ok(rootTransform.system.some((s) => typeof s === "string" && s.includes("[memoreal-session-end]")))
988
-
989
- // --- 2. CHILD SESSION (parentID) ---
990
- const childReadOutput = { output: "child output" }
991
- await plugin["tool.execute.after"](
992
- { tool: "read", args: { path: "README.md" }, sessionID: "ses_child_parent" },
993
- childReadOutput
994
- )
995
- assert.equal(childReadOutput.output, "child output")
996
-
997
- const childWriteOutput = { output: "child write" }
998
- await plugin["tool.execute.after"](
999
- { tool: "write", args: { path: "prd/001.md" }, sessionID: "ses_child_parent" },
1000
- childWriteOutput
1001
- )
1002
- assert.equal(childWriteOutput.output, "child write")
1003
-
1004
- const childEditOutput = { output: "child edit" }
1005
- await plugin["tool.execute.after"](
1006
- { tool: "edit", args: { path: "src/main.ts" }, sessionID: "ses_child_parent" },
1007
- childEditOutput
1008
- )
1009
- assert.equal(childEditOutput.output, "child edit")
1010
-
1011
- const childCompact = { context: [] }
1012
- await plugin["experimental.session.compacting"]({ sessionID: "ses_child_parent" }, childCompact)
1013
- assert.equal(childCompact.context.length, 0)
1014
-
1015
- await plugin.event({ event: { type: "session.idle", sessionID: "ses_child_parent" } })
1016
- const childTransform = { system: [] }
1017
- await plugin["experimental.chat.system.transform"]({ sessionID: "ses_child_parent" }, childTransform)
1018
- assert.equal(childTransform.system.length, 0)
1019
-
1020
- // --- 3. CHILD SESSION (agent: flash-worker) ---
1021
- const agentReadOutput = { output: "agent output" }
1022
- await plugin["tool.execute.after"](
1023
- { tool: "read", args: { path: "README.md" }, sessionID: "ses_child_agent" },
1024
- agentReadOutput
1025
- )
1026
- assert.equal(agentReadOutput.output, "agent output")
1027
-
1028
- // --- 4. CHILD SESSION (PRD_FLASH_LEAF_WORKER="1") ---
1029
- process.env.PRD_FLASH_LEAF_WORKER = "1"
1030
- const leafReadOutput = { output: "leaf output" }
1031
- await plugin["tool.execute.after"](
1032
- { tool: "read", args: { path: "README.md" } },
1033
- leafReadOutput
1034
- )
1035
- assert.equal(leafReadOutput.output, "leaf output")
1036
- delete process.env.PRD_FLASH_LEAF_WORKER
1037
- })
1038
- })
1039
- })