pi-vault-mind 0.14.2 → 0.16.3

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 (164) hide show
  1. package/CHANGELOG.md +293 -0
  2. package/README.md +5 -5
  3. package/agents/broadcaster.agent.md +2 -2
  4. package/agents/heavy-lifter.agent.md +1 -1
  5. package/agents/main.agent.md +29 -0
  6. package/agents/manager.agent.md +1 -1
  7. package/agents/miner.agent.md +1 -1
  8. package/dist/packages/obsidian/src/client.js +331 -0
  9. package/dist/packages/obsidian/src/types.js +1 -0
  10. package/dist/src/activity.d.ts +49 -0
  11. package/dist/src/activity.js +175 -0
  12. package/dist/src/agent-bus/Agent.d.ts +9 -1
  13. package/dist/src/agent-bus/Agent.js +18 -2
  14. package/dist/src/agent-bus/index.d.ts +5 -5
  15. package/dist/src/agent-bus/index.js +1 -1
  16. package/dist/src/agent-queue.js +12 -3
  17. package/dist/src/agents/BroadcasterAgent.d.ts +1 -1
  18. package/dist/src/agents/BroadcasterAgent.js +2 -2
  19. package/dist/src/agents/HeavyLifterAgent.d.ts +1 -1
  20. package/dist/src/agents/HeavyLifterAgent.js +2 -2
  21. package/dist/src/agents/ManagerAgent.js +1 -1
  22. package/dist/src/agents/MinerAgent.d.ts +1 -1
  23. package/dist/src/agents/MinerAgent.js +2 -2
  24. package/dist/src/agents/index.d.ts +2 -2
  25. package/dist/src/agents/index.js +2 -2
  26. package/dist/src/auth.d.ts +17 -15
  27. package/dist/src/auth.js +26 -37
  28. package/dist/src/autosync.js +2 -2
  29. package/dist/src/commands.d.ts +2 -19
  30. package/dist/src/commands.js +301 -231
  31. package/dist/src/config-keys.d.ts +16 -0
  32. package/dist/src/config-keys.js +45 -0
  33. package/dist/src/discover-schema.js +4 -4
  34. package/dist/src/edits.d.ts +21 -0
  35. package/dist/src/edits.js +75 -0
  36. package/dist/src/embedding-probe.d.ts +34 -0
  37. package/dist/src/embedding-probe.js +142 -0
  38. package/dist/src/embedding-providers.d.ts +133 -0
  39. package/dist/src/embedding-providers.js +173 -0
  40. package/dist/src/embedding-secrets.d.ts +38 -0
  41. package/dist/src/embedding-secrets.js +291 -0
  42. package/dist/src/engine.d.ts +6 -0
  43. package/dist/src/engine.js +78 -6
  44. package/dist/src/events.js +7 -10
  45. package/dist/src/extension-packages.d.ts +9 -0
  46. package/dist/src/extension-packages.js +14 -0
  47. package/dist/src/git.d.ts +19 -0
  48. package/dist/src/git.js +78 -0
  49. package/dist/src/graph.d.ts +2 -1
  50. package/dist/src/graph.js +47 -13
  51. package/dist/src/identities-config.d.ts +6 -0
  52. package/dist/src/identities-config.js +39 -0
  53. package/dist/src/identity-injector.js +1 -1
  54. package/dist/src/index.js +9 -26
  55. package/dist/src/lance.d.ts +9 -0
  56. package/dist/src/lance.js +143 -203
  57. package/dist/src/modal-client.d.ts +16 -0
  58. package/dist/src/modal-client.js +16 -0
  59. package/dist/src/modal-config.d.ts +37 -14
  60. package/dist/src/modal-config.js +59 -32
  61. package/dist/src/model-router.d.ts +27 -0
  62. package/dist/src/model-router.js +67 -0
  63. package/dist/src/models.d.ts +42 -0
  64. package/dist/src/models.js +78 -0
  65. package/dist/src/personalize.js +17 -3
  66. package/dist/src/scaffold.d.ts +48 -0
  67. package/dist/src/scaffold.js +246 -0
  68. package/dist/src/server.d.ts +47 -4
  69. package/dist/src/server.js +988 -221
  70. package/dist/src/session-search.d.ts +63 -0
  71. package/dist/src/session-search.js +379 -0
  72. package/dist/src/settings-ui.d.ts +2 -2
  73. package/dist/src/settings-ui.js +76 -135
  74. package/dist/src/sync.d.ts +3 -3
  75. package/dist/src/sync.js +19 -15
  76. package/dist/src/tool-catalog.d.ts +18 -0
  77. package/dist/src/tool-catalog.js +232 -0
  78. package/dist/src/tools/marksman.js +1 -1
  79. package/dist/src/tools.js +111 -65
  80. package/dist/src/types.d.ts +127 -71
  81. package/dist/src/utils.d.ts +57 -6
  82. package/dist/src/utils.js +114 -28
  83. package/dist/src/vault-tools.d.ts +34 -0
  84. package/dist/src/vault-tools.js +99 -0
  85. package/dist/src/vault-writer.js +4 -1
  86. package/dist/src/vm-handlers.js +140 -43
  87. package/dist/src/watcher.js +9 -9
  88. package/dist/test/activity-tool.test.js +54 -0
  89. package/dist/test/agent-bus/Agent.test.js +174 -0
  90. package/dist/test/agent-bus/AgentLoader.test.js +180 -0
  91. package/dist/test/agent-bus/AgentRegistry.test.js +86 -0
  92. package/dist/test/agent-bus/LLMProvider.test.js +162 -0
  93. package/dist/test/agent-bus/TaskQueue.test.js +256 -0
  94. package/dist/test/agent-dispatch-context.test.js +73 -0
  95. package/dist/test/agent-queue.test.js +1 -1
  96. package/dist/test/agents/Agents.test.js +282 -0
  97. package/dist/test/auth.test.js +57 -56
  98. package/dist/test/bridge-identity.test.js +34 -3
  99. package/dist/test/classify-search-mode.test.js +51 -0
  100. package/dist/test/commands.test.js +410 -0
  101. package/dist/test/config-merge.test.js +98 -0
  102. package/dist/test/context-capture.test.js +56 -0
  103. package/dist/test/discover-schema.test.js +8 -5
  104. package/dist/test/dispatch.test.js +45 -91
  105. package/dist/test/edits.test.js +144 -0
  106. package/dist/test/embedding-probe.test.js +424 -0
  107. package/dist/test/embedding-providers.test.js +157 -0
  108. package/dist/test/embedding-secrets.test.js +210 -0
  109. package/dist/test/engine-identity.test.js +1 -1
  110. package/dist/test/events.test.js +675 -0
  111. package/dist/test/git-bridge.test.js +160 -0
  112. package/dist/test/graph.test.js +464 -0
  113. package/dist/test/helpers/server.js +81 -0
  114. package/dist/test/identity-injector.test.js +197 -0
  115. package/dist/test/index.test.js +5 -7
  116. package/dist/test/lance-modal.test.js +67 -2
  117. package/dist/test/lance.test.js +429 -0
  118. package/dist/test/modal-client.test.js +1 -1
  119. package/dist/test/modal-config.test.js +92 -79
  120. package/dist/test/model-readiness.test.js +122 -0
  121. package/dist/test/model-router.test.js +99 -0
  122. package/dist/test/obsidian-client.test.js +42 -0
  123. package/dist/test/personalize.test.js +1 -1
  124. package/dist/test/rest-models.test.js +153 -0
  125. package/dist/test/rest-queue.test.js +135 -87
  126. package/dist/test/rest-setup.test.js +625 -115
  127. package/dist/test/rest-vm.test.js +355 -94
  128. package/dist/test/server-cors.test.js +48 -0
  129. package/dist/test/server-ws.test.js +61 -34
  130. package/dist/test/session-crud.test.js +323 -0
  131. package/dist/test/session-search.test.js +139 -0
  132. package/dist/test/settings-ui.test.js +113 -4
  133. package/dist/test/sync.test.js +12 -12
  134. package/dist/test/tombstone.test.js +8 -10
  135. package/dist/test/tool-catalog.test.js +86 -0
  136. package/dist/test/utils.test.js +588 -0
  137. package/dist/test/vault-tools.test.js +103 -12
  138. package/dist/test/vault-writer.test.js +371 -0
  139. package/dist/test/vm-handlers.test.js +620 -0
  140. package/extension-packages.json +9 -0
  141. package/package.json +107 -90
  142. package/pi-vault-mind.config.example.json +24 -2
  143. package/scripts/check-deps.sh +35 -32
  144. package/scripts/cli-e2e.mjs +215 -0
  145. package/scripts/configuration-e2e.mjs +783 -0
  146. package/scripts/e2e-commands.mjs +391 -0
  147. package/scripts/e2e-ws.mjs +3 -2
  148. package/scripts/fetch-modal-token.sh +4 -3
  149. package/scripts/generate-config-keys-json.mjs +45 -0
  150. package/scripts/generate-extension-packages-json.mjs +55 -0
  151. package/scripts/pi-session-query +0 -0
  152. package/scripts/publish-obsidian-plugin.sh +0 -0
  153. package/scripts/reset-test-vault.sh +2 -2
  154. package/scripts/setup-test-config.sh +0 -0
  155. package/scripts/setup-vault-pi.sh +48 -9
  156. package/scripts/test-slash-commands.mjs +2 -2
  157. package/scripts/vault-pi.sh +12 -3
  158. package/skills/github-release-notes-file/SKILL.md +42 -0
  159. package/skills/obsidian-guided-test-session/SKILL.md +110 -0
  160. package/skills/obsidian-interactive-test/SKILL.md +88 -0
  161. package/skills/obsidian-plugin-publish/SKILL.md +58 -0
  162. package/skills/pi-vault-mind-release/SKILL.md +141 -0
  163. package/skills/pre-test-release/SKILL.md +116 -0
  164. package/dist/test/auto-indexer.test.js +0 -2
@@ -0,0 +1,675 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { randomUUID } from "node:crypto";
3
+ import * as fs from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import * as path from "node:path";
6
+ import { afterEach, beforeEach, describe, it } from "node:test";
7
+ import { handleBeforeAgentStart, handleTurnEnd } from "../src/events.js";
8
+ import { setActiveCollection } from "../src/state.js";
9
+ // ---------------------------------------------------------------------------
10
+ // Helpers
11
+ // ---------------------------------------------------------------------------
12
+ const makeCtx = (cwd) => ({ cwd, ui: { notify: () => { } } });
13
+ const makeCtxWithNotify = (cwd, notifyFn) => ({ cwd, ui: { notify: notifyFn } });
14
+ const makePi = (tools = []) => ({ getAllTools: () => tools });
15
+ const makeEvent = (prompt, systemPrompt = "base system prompt") => ({ type: "before_agent_start", prompt, systemPrompt });
16
+ const makeTurnEndEvent = () => ({ type: "turn_end", turnIndex: 0, message: {} });
17
+ const writeConfig = (dir, overrides) => {
18
+ const configDir = path.join(dir, ".vault-mind");
19
+ fs.mkdirSync(configDir, { recursive: true });
20
+ fs.writeFileSync(path.join(configDir, "vault-mind.config.json"), JSON.stringify({
21
+ version: 2,
22
+ collections: {
23
+ main: {
24
+ path: "collections/main.jsonl",
25
+ schema: ["id", "domain", "source", "fact", "tag", "artifact"],
26
+ dedupField: "fact",
27
+ },
28
+ },
29
+ injectors: [],
30
+ vaultMind: {
31
+ dataDir: ".lancedb",
32
+ embedding: {},
33
+ ftsEnabled: false,
34
+ graph: { enabled: false },
35
+ },
36
+ ...overrides,
37
+ }), "utf-8");
38
+ };
39
+ // ---------------------------------------------------------------------------
40
+ // handleBeforeAgentStart
41
+ // ---------------------------------------------------------------------------
42
+ describe("handleBeforeAgentStart", () => {
43
+ let testDir;
44
+ beforeEach(() => {
45
+ testDir = path.join(tmpdir(), `events-before-${randomUUID()}`);
46
+ fs.mkdirSync(testDir, { recursive: true });
47
+ fs.mkdirSync(path.join(testDir, "collections"), { recursive: true });
48
+ // Reset active collection to ensure clean state per test
49
+ setActiveCollection("main");
50
+ });
51
+ afterEach(() => {
52
+ try {
53
+ fs.rmSync(testDir, { recursive: true, force: true });
54
+ }
55
+ catch {
56
+ /* ignore */
57
+ }
58
+ });
59
+ it("always returns systemPrompt with active collection context (even with no injectors)", async () => {
60
+ writeConfig(testDir, { injectors: [] });
61
+ const ctx = makeCtx(testDir);
62
+ const pi = makePi();
63
+ const event = makeEvent("hello world");
64
+ const result = await handleBeforeAgentStart(pi, event, ctx);
65
+ assert.ok(result);
66
+ const sp = result.systemPrompt;
67
+ assert.ok(sp.includes("[Active Collection Context]"), "should include active collection context header");
68
+ assert.ok(sp.includes('"main"'), "should reference the active collection name");
69
+ assert.ok(sp.startsWith(event.systemPrompt), "should prepend additions to the original system prompt");
70
+ });
71
+ it("injects matching collection entries when injector regex matches the prompt", async () => {
72
+ const entries = [
73
+ { id: "1", domain: "auth", fact: "login works", tag: "security" },
74
+ { id: "2", domain: "auth", fact: "logout works", tag: "security" },
75
+ ];
76
+ fs.writeFileSync(path.join(testDir, "collections", "main.jsonl"), entries.map((e) => JSON.stringify(e)).join("\n"));
77
+ writeConfig(testDir, {
78
+ injectors: [
79
+ {
80
+ name: "auth-context",
81
+ regex: "\\bauth\\b",
82
+ collection: "main",
83
+ },
84
+ ],
85
+ });
86
+ const ctx = makeCtx(testDir);
87
+ const pi = makePi();
88
+ const event = makeEvent("help me with auth please");
89
+ const result = await handleBeforeAgentStart(pi, event, ctx);
90
+ assert.ok(result);
91
+ const sp = result.systemPrompt;
92
+ assert.ok(sp.includes("auth-context"));
93
+ assert.ok(sp.includes("login works"));
94
+ assert.ok(sp.includes("logout works"));
95
+ });
96
+ it("skips injector when regex does not match the prompt", async () => {
97
+ const entries = [{ id: "1", domain: "auth", fact: "login works", tag: "security" }];
98
+ fs.writeFileSync(path.join(testDir, "collections", "main.jsonl"), entries.map((e) => JSON.stringify(e)).join("\n"));
99
+ writeConfig(testDir, {
100
+ injectors: [
101
+ {
102
+ name: "auth-context",
103
+ regex: "\\bauth\\b",
104
+ collection: "main",
105
+ },
106
+ ],
107
+ });
108
+ const ctx = makeCtx(testDir);
109
+ const pi = makePi();
110
+ const event = makeEvent("help me with database stuff");
111
+ const result = await handleBeforeAgentStart(pi, event, ctx);
112
+ assert.ok(result);
113
+ const sp = result.systemPrompt;
114
+ // Should NOT contain the injector content since regex didn't match
115
+ assert.ok(!sp.includes("auth-context"));
116
+ assert.ok(!sp.includes("login works"));
117
+ // But should still have the active collection context
118
+ assert.ok(sp.includes("[Active Collection Context]"));
119
+ });
120
+ it("filters entries by filterField matching the regex capture group", async () => {
121
+ const entries = [
122
+ { id: "1", domain: "auth", fact: "login works", tag: "security" },
123
+ { id: "2", domain: "billing", fact: "invoice sent", tag: "finance" },
124
+ { id: "3", domain: "auth", fact: "password reset", tag: "security" },
125
+ ];
126
+ fs.writeFileSync(path.join(testDir, "collections", "main.jsonl"), entries.map((e) => JSON.stringify(e)).join("\n"));
127
+ writeConfig(testDir, {
128
+ injectors: [
129
+ {
130
+ name: "domain-filter",
131
+ regex: "domain:(\\w+)",
132
+ captureGroup: 1,
133
+ collection: "main",
134
+ filterField: "domain",
135
+ },
136
+ ],
137
+ });
138
+ const ctx = makeCtx(testDir);
139
+ const pi = makePi();
140
+ const event = makeEvent("show me domain:auth entries");
141
+ const result = await handleBeforeAgentStart(pi, event, ctx);
142
+ assert.ok(result);
143
+ const sp = result.systemPrompt;
144
+ assert.ok(sp.includes("login works"));
145
+ assert.ok(sp.includes("password reset"));
146
+ assert.ok(!sp.includes("invoice sent"));
147
+ });
148
+ it("includes artifact content when injector has artifactPath", async () => {
149
+ const entries = [{ id: "1", domain: "docs", fact: "api reference", tag: "docs" }];
150
+ fs.writeFileSync(path.join(testDir, "collections", "main.jsonl"), entries.map((e) => JSON.stringify(e)).join("\n"));
151
+ const artifactContent = "# API Reference\n\n## Endpoints\n- GET /users\n- POST /users\n";
152
+ fs.writeFileSync(path.join(testDir, "api-docs.md"), artifactContent);
153
+ writeConfig(testDir, {
154
+ injectors: [
155
+ {
156
+ name: "docs-context",
157
+ regex: "\\bdocs\\b",
158
+ collection: "main",
159
+ artifactPath: "api-docs.md",
160
+ },
161
+ ],
162
+ });
163
+ const ctx = makeCtx(testDir);
164
+ const pi = makePi();
165
+ const event = makeEvent("help with docs");
166
+ const result = await handleBeforeAgentStart(pi, event, ctx);
167
+ assert.ok(result);
168
+ const sp = result.systemPrompt;
169
+ assert.ok(sp.includes("ARTIFACT:"));
170
+ assert.ok(sp.includes("GET /users"));
171
+ assert.ok(sp.includes("POST /users"));
172
+ });
173
+ it("uses custom template when injector has template field", async () => {
174
+ const entries = [{ id: "1", domain: "test", fact: "custom template test", tag: "test" }];
175
+ fs.writeFileSync(path.join(testDir, "collections", "main.jsonl"), entries.map((e) => JSON.stringify(e)).join("\n"));
176
+ writeConfig(testDir, {
177
+ injectors: [
178
+ {
179
+ name: "custom-tmpl",
180
+ regex: "(test)",
181
+ collection: "main",
182
+ template: ">>> {{injector}} matched {{capture}}: {{entries}} <<<",
183
+ },
184
+ ],
185
+ });
186
+ const ctx = makeCtx(testDir);
187
+ const pi = makePi();
188
+ const event = makeEvent("run a test please");
189
+ const result = await handleBeforeAgentStart(pi, event, ctx);
190
+ assert.ok(result);
191
+ const sp = result.systemPrompt;
192
+ assert.ok(sp.includes(">>> custom-tmpl matched test:"));
193
+ assert.ok(sp.includes("custom template test"));
194
+ assert.ok(!sp.includes("{{injector}}"), "template placeholders should be replaced");
195
+ assert.ok(!sp.includes("{{entries}}"), "template placeholders should be replaced");
196
+ });
197
+ it("skips injector when referenced collection is missing from config", async () => {
198
+ writeConfig(testDir, {
199
+ injectors: [
200
+ {
201
+ name: "missing-collection",
202
+ regex: "\\btest\\b",
203
+ collection: "nonexistent",
204
+ },
205
+ ],
206
+ });
207
+ const ctx = makeCtx(testDir);
208
+ const pi = makePi();
209
+ const event = makeEvent("run a test");
210
+ const result = await handleBeforeAgentStart(pi, event, ctx);
211
+ assert.ok(result);
212
+ const sp = result.systemPrompt;
213
+ assert.ok(!sp.includes("missing-collection"));
214
+ assert.ok(sp.includes("[Active Collection Context]"));
215
+ });
216
+ it("handles missing collection file gracefully (entries = '(none)')", async () => {
217
+ // Don't create the collection file — the path exists in config but file doesn't
218
+ writeConfig(testDir, {
219
+ injectors: [
220
+ {
221
+ name: "missing-file",
222
+ regex: "\\btest\\b",
223
+ collection: "main",
224
+ },
225
+ ],
226
+ });
227
+ const ctx = makeCtx(testDir);
228
+ const pi = makePi();
229
+ const event = makeEvent("run a test");
230
+ const result = await handleBeforeAgentStart(pi, event, ctx);
231
+ assert.ok(result);
232
+ const sp = result.systemPrompt;
233
+ assert.ok(sp.includes("missing-file"));
234
+ assert.ok(sp.includes("(none)"), "entries should show (none) when file is missing");
235
+ });
236
+ it("handles artifactPath pointing to missing file gracefully (artifact = '(none)')", async () => {
237
+ const entries = [{ id: "1", domain: "test", fact: "artifact test", tag: "test" }];
238
+ fs.writeFileSync(path.join(testDir, "collections", "main.jsonl"), entries.map((e) => JSON.stringify(e)).join("\n"));
239
+ writeConfig(testDir, {
240
+ injectors: [
241
+ {
242
+ name: "missing-artifact",
243
+ regex: "\\btest\\b",
244
+ collection: "main",
245
+ artifactPath: "nonexistent.md",
246
+ },
247
+ ],
248
+ });
249
+ const ctx = makeCtx(testDir);
250
+ const pi = makePi();
251
+ const event = makeEvent("run a test");
252
+ const result = await handleBeforeAgentStart(pi, event, ctx);
253
+ assert.ok(result);
254
+ const sp = result.systemPrompt;
255
+ assert.ok(sp.includes("missing-artifact"));
256
+ assert.ok(sp.includes("artifact test"), "entries should still be present");
257
+ // The default template has ARTIFACT: section — should show (none)
258
+ assert.ok(sp.includes("ARTIFACT:") && sp.includes("(none)"), "artifact should show (none) when file is missing");
259
+ });
260
+ it("handles multiple injectors, injecting only those that match", async () => {
261
+ const authEntries = [{ id: "1", domain: "auth", fact: "login works", tag: "security" }];
262
+ const billingEntries = [{ id: "2", domain: "billing", fact: "invoice sent", tag: "finance" }];
263
+ fs.writeFileSync(path.join(testDir, "collections", "main.jsonl"), [...authEntries, ...billingEntries].map((e) => JSON.stringify(e)).join("\n"));
264
+ writeConfig(testDir, {
265
+ injectors: [
266
+ {
267
+ name: "auth-injector",
268
+ regex: "(auth)",
269
+ collection: "main",
270
+ filterField: "domain",
271
+ },
272
+ {
273
+ name: "billing-injector",
274
+ regex: "\\bbilling\\b",
275
+ collection: "main",
276
+ },
277
+ ],
278
+ });
279
+ const ctx = makeCtx(testDir);
280
+ const pi = makePi();
281
+ const event = makeEvent("help with auth please");
282
+ const result = await handleBeforeAgentStart(pi, event, ctx);
283
+ assert.ok(result);
284
+ const sp = result.systemPrompt;
285
+ assert.ok(sp.includes("auth-injector"));
286
+ assert.ok(sp.includes("login works"));
287
+ assert.ok(!sp.includes("billing-injector"));
288
+ assert.ok(!sp.includes("invoice sent"));
289
+ });
290
+ it("uses default captureGroup 1 when not specified", async () => {
291
+ const entries = [{ id: "1", domain: "auth", fact: "default capture", tag: "security" }];
292
+ fs.writeFileSync(path.join(testDir, "collections", "main.jsonl"), entries.map((e) => JSON.stringify(e)).join("\n"));
293
+ writeConfig(testDir, {
294
+ injectors: [
295
+ {
296
+ name: "default-capture",
297
+ regex: "find:(\\w+)",
298
+ // captureGroup not specified → defaults to 1
299
+ collection: "main",
300
+ },
301
+ ],
302
+ });
303
+ const ctx = makeCtx(testDir);
304
+ const pi = makePi();
305
+ const event = makeEvent("find:something");
306
+ const result = await handleBeforeAgentStart(pi, event, ctx);
307
+ assert.ok(result);
308
+ const sp = result.systemPrompt;
309
+ // The default template includes {{capture}} — should show "something"
310
+ assert.ok(sp.includes("capture=something"));
311
+ });
312
+ });
313
+ // ---------------------------------------------------------------------------
314
+ // handleTurnEnd
315
+ // ---------------------------------------------------------------------------
316
+ describe("handleTurnEnd", () => {
317
+ let testDir;
318
+ beforeEach(() => {
319
+ testDir = path.join(tmpdir(), `events-turn-${randomUUID()}`);
320
+ fs.mkdirSync(testDir, { recursive: true });
321
+ fs.mkdirSync(path.join(testDir, "collections"), { recursive: true });
322
+ });
323
+ afterEach(() => {
324
+ try {
325
+ fs.rmSync(testDir, { recursive: true, force: true });
326
+ }
327
+ catch {
328
+ /* ignore */
329
+ }
330
+ });
331
+ it("captures pi-context tag events and appends to context_events collection", async () => {
332
+ const logText = [
333
+ "abc123 (tag: security) [AI] security review completed",
334
+ "def456 (tag: bugfix) [USER] fixed the login issue",
335
+ "789abc (ROOT summary from main) [SUMMARY] All tests passing",
336
+ ].join("\n");
337
+ const contextLogTool = {
338
+ name: "context_log",
339
+ execute: async () => ({ content: [{ text: logText }] }),
340
+ };
341
+ const contextCheckoutTool = {
342
+ name: "context_checkout",
343
+ execute: async () => ({}),
344
+ };
345
+ const contextTagTool = { name: "context_tag" };
346
+ const pi = makePi([contextLogTool, contextCheckoutTool, contextTagTool]);
347
+ writeConfig(testDir, {
348
+ collections: {
349
+ main: {
350
+ path: "collections/main.jsonl",
351
+ schema: ["id", "domain", "source", "fact", "tag", "artifact"],
352
+ dedupField: "fact",
353
+ },
354
+ context_events: {
355
+ path: "collections/context_events.jsonl",
356
+ schema: ["id", "type", "session_entry_id", "content", "timestamp", "tags"],
357
+ dedupField: "id",
358
+ },
359
+ },
360
+ extensionCompatibility: {
361
+ "pi-context": {
362
+ enabled: true,
363
+ indexContextEvents: true,
364
+ },
365
+ },
366
+ });
367
+ const ctx = makeCtx(testDir);
368
+ const event = makeTurnEndEvent();
369
+ await handleTurnEnd(pi, event, ctx);
370
+ // Verify the collection file was created and contains events
371
+ const collectionPath = path.join(testDir, "collections", "context_events.jsonl");
372
+ assert.ok(fs.existsSync(collectionPath), "context_events collection file should exist");
373
+ const content = fs.readFileSync(collectionPath, "utf-8");
374
+ const lines = content.split("\n").filter(Boolean);
375
+ assert.ok(lines.length >= 2, "should have captured at least 2 events");
376
+ const events = lines.map((l) => JSON.parse(l));
377
+ const tagEvents = events.filter((e) => e.type === "tag_created");
378
+ const summaryEvents = events.filter((e) => e.type === "checkout_summary");
379
+ assert.equal(tagEvents.length, 2, "should capture 2 tag events");
380
+ assert.equal(summaryEvents.length, 1, "should capture 1 summary event");
381
+ // Verify tag event structure
382
+ const securityEvent = tagEvents.find((e) => e.details?.tag_name === "security");
383
+ assert.ok(securityEvent, "should capture security tag event");
384
+ assert.equal(securityEvent.type, "tag_created");
385
+ assert.ok(securityEvent.tags.includes("pi-context"));
386
+ assert.equal(securityEvent.details.entry_type, "AI");
387
+ // Verify summary event structure
388
+ const summaryEvent = summaryEvents[0];
389
+ assert.equal(summaryEvent.type, "checkout_summary");
390
+ assert.ok(summaryEvent.tags.includes("checkout"));
391
+ assert.equal(summaryEvent.details.origin, "main");
392
+ });
393
+ it("deduplicates events by id on subsequent calls", async () => {
394
+ const logText = "abc123 (tag: security) [AI] security review completed\n";
395
+ const contextLogTool = {
396
+ name: "context_log",
397
+ execute: async () => ({ content: [{ text: logText }] }),
398
+ };
399
+ const contextCheckoutTool = {
400
+ name: "context_checkout",
401
+ execute: async () => ({}),
402
+ };
403
+ const contextTagTool = { name: "context_tag" };
404
+ const pi = makePi([contextLogTool, contextCheckoutTool, contextTagTool]);
405
+ writeConfig(testDir, {
406
+ collections: {
407
+ main: {
408
+ path: "collections/main.jsonl",
409
+ schema: ["id", "domain", "source", "fact", "tag", "artifact"],
410
+ dedupField: "fact",
411
+ },
412
+ context_events: {
413
+ path: "collections/context_events.jsonl",
414
+ schema: ["id", "type", "session_entry_id", "content", "timestamp", "tags"],
415
+ dedupField: "id",
416
+ },
417
+ },
418
+ extensionCompatibility: {
419
+ "pi-context": {
420
+ enabled: true,
421
+ indexContextEvents: true,
422
+ },
423
+ },
424
+ });
425
+ const ctx = makeCtx(testDir);
426
+ const event = makeTurnEndEvent();
427
+ // First call
428
+ await handleTurnEnd(pi, event, ctx);
429
+ const collectionPath = path.join(testDir, "collections", "context_events.jsonl");
430
+ const firstContent = fs.readFileSync(collectionPath, "utf-8");
431
+ const firstLines = firstContent.split("\n").filter(Boolean);
432
+ assert.equal(firstLines.length, 1, "first call should append 1 event");
433
+ // Second call with same log — should deduplicate
434
+ await handleTurnEnd(pi, event, ctx);
435
+ const secondContent = fs.readFileSync(collectionPath, "utf-8");
436
+ const secondLines = secondContent.split("\n").filter(Boolean);
437
+ assert.equal(secondLines.length, 1, "second call should not duplicate the same event");
438
+ });
439
+ it("skips when pi-context is disabled", async () => {
440
+ const pi = makePi([
441
+ { name: "context_log" },
442
+ { name: "context_checkout" },
443
+ { name: "context_tag" },
444
+ ]);
445
+ writeConfig(testDir, {
446
+ collections: {
447
+ main: {
448
+ path: "collections/main.jsonl",
449
+ schema: ["id", "domain", "source", "fact", "tag", "artifact"],
450
+ dedupField: "fact",
451
+ },
452
+ context_events: {
453
+ path: "collections/context_events.jsonl",
454
+ schema: ["id", "type", "session_entry_id", "content", "timestamp", "tags"],
455
+ dedupField: "id",
456
+ },
457
+ },
458
+ extensionCompatibility: {
459
+ "pi-context": {
460
+ enabled: false,
461
+ indexContextEvents: true,
462
+ },
463
+ },
464
+ });
465
+ const ctx = makeCtx(testDir);
466
+ const event = makeTurnEndEvent();
467
+ await handleTurnEnd(pi, event, ctx);
468
+ const collectionPath = path.join(testDir, "collections", "context_events.jsonl");
469
+ assert.ok(!fs.existsSync(collectionPath), "should not create collection file when disabled");
470
+ });
471
+ it("skips when indexContextEvents is false", async () => {
472
+ const pi = makePi([
473
+ { name: "context_log" },
474
+ { name: "context_checkout" },
475
+ { name: "context_tag" },
476
+ ]);
477
+ writeConfig(testDir, {
478
+ collections: {
479
+ main: {
480
+ path: "collections/main.jsonl",
481
+ schema: ["id", "domain", "source", "fact", "tag", "artifact"],
482
+ dedupField: "fact",
483
+ },
484
+ context_events: {
485
+ path: "collections/context_events.jsonl",
486
+ schema: ["id", "type", "session_entry_id", "content", "timestamp", "tags"],
487
+ dedupField: "id",
488
+ },
489
+ },
490
+ extensionCompatibility: {
491
+ "pi-context": {
492
+ enabled: true,
493
+ indexContextEvents: false,
494
+ },
495
+ },
496
+ });
497
+ const ctx = makeCtx(testDir);
498
+ const event = makeTurnEndEvent();
499
+ await handleTurnEnd(pi, event, ctx);
500
+ const collectionPath = path.join(testDir, "collections", "context_events.jsonl");
501
+ assert.ok(!fs.existsSync(collectionPath), "should not create collection file when indexContextEvents is false");
502
+ });
503
+ it("skips when pi-context tools are not available", async () => {
504
+ // No context_log or context_checkout tools
505
+ const pi = makePi([{ name: "some_other_tool" }]);
506
+ writeConfig(testDir, {
507
+ collections: {
508
+ main: {
509
+ path: "collections/main.jsonl",
510
+ schema: ["id", "domain", "source", "fact", "tag", "artifact"],
511
+ dedupField: "fact",
512
+ },
513
+ context_events: {
514
+ path: "collections/context_events.jsonl",
515
+ schema: ["id", "type", "session_entry_id", "content", "timestamp", "tags"],
516
+ dedupField: "id",
517
+ },
518
+ },
519
+ extensionCompatibility: {
520
+ "pi-context": {
521
+ enabled: true,
522
+ indexContextEvents: true,
523
+ },
524
+ },
525
+ });
526
+ const ctx = makeCtx(testDir);
527
+ const event = makeTurnEndEvent();
528
+ await handleTurnEnd(pi, event, ctx);
529
+ const collectionPath = path.join(testDir, "collections", "context_events.jsonl");
530
+ assert.ok(!fs.existsSync(collectionPath), "should not create collection file when tools are unavailable");
531
+ });
532
+ it("handles missing context_events collection gracefully", async () => {
533
+ const pi = makePi([
534
+ { name: "context_log" },
535
+ { name: "context_checkout" },
536
+ { name: "context_tag" },
537
+ ]);
538
+ // No context_events collection in config
539
+ writeConfig(testDir, {
540
+ extensionCompatibility: {
541
+ "pi-context": {
542
+ enabled: true,
543
+ indexContextEvents: true,
544
+ },
545
+ },
546
+ });
547
+ const ctx = makeCtx(testDir);
548
+ const event = makeTurnEndEvent();
549
+ // Should not throw
550
+ await handleTurnEnd(pi, event, ctx);
551
+ // No file should be created
552
+ const collectionPath = path.join(testDir, "collections", "context_events.jsonl");
553
+ assert.ok(!fs.existsSync(collectionPath));
554
+ });
555
+ it("notifies UI when events are captured", async () => {
556
+ const logText = "abc123 (tag: security) [AI] security review completed\n";
557
+ const contextLogTool = {
558
+ name: "context_log",
559
+ execute: async () => ({ content: [{ text: logText }] }),
560
+ };
561
+ const contextCheckoutTool = {
562
+ name: "context_checkout",
563
+ execute: async () => ({}),
564
+ };
565
+ const contextTagTool = { name: "context_tag" };
566
+ const pi = makePi([contextLogTool, contextCheckoutTool, contextTagTool]);
567
+ const notifications = [];
568
+ const ctx = makeCtxWithNotify(testDir, (msg, level) => {
569
+ notifications.push({ msg, level });
570
+ });
571
+ writeConfig(testDir, {
572
+ collections: {
573
+ main: {
574
+ path: "collections/main.jsonl",
575
+ schema: ["id", "domain", "source", "fact", "tag", "artifact"],
576
+ dedupField: "fact",
577
+ },
578
+ context_events: {
579
+ path: "collections/context_events.jsonl",
580
+ schema: ["id", "type", "session_entry_id", "content", "timestamp", "tags"],
581
+ dedupField: "id",
582
+ },
583
+ },
584
+ extensionCompatibility: {
585
+ "pi-context": {
586
+ enabled: true,
587
+ indexContextEvents: true,
588
+ },
589
+ },
590
+ });
591
+ const event = makeTurnEndEvent();
592
+ await handleTurnEnd(pi, event, ctx);
593
+ assert.equal(notifications.length, 1, "should send one notification");
594
+ assert.ok(notifications[0].msg.includes("captured 1 event"));
595
+ assert.equal(notifications[0].level, "info");
596
+ });
597
+ it("handles empty log output gracefully", async () => {
598
+ const contextLogTool = {
599
+ name: "context_log",
600
+ execute: async () => ({ content: [] }),
601
+ };
602
+ const contextCheckoutTool = {
603
+ name: "context_checkout",
604
+ execute: async () => ({}),
605
+ };
606
+ const contextTagTool = { name: "context_tag" };
607
+ const pi = makePi([contextLogTool, contextCheckoutTool, contextTagTool]);
608
+ writeConfig(testDir, {
609
+ collections: {
610
+ main: {
611
+ path: "collections/main.jsonl",
612
+ schema: ["id", "domain", "source", "fact", "tag", "artifact"],
613
+ dedupField: "fact",
614
+ },
615
+ context_events: {
616
+ path: "collections/context_events.jsonl",
617
+ schema: ["id", "type", "session_entry_id", "content", "timestamp", "tags"],
618
+ dedupField: "id",
619
+ },
620
+ },
621
+ extensionCompatibility: {
622
+ "pi-context": {
623
+ enabled: true,
624
+ indexContextEvents: true,
625
+ },
626
+ },
627
+ });
628
+ const ctx = makeCtx(testDir);
629
+ const event = makeTurnEndEvent();
630
+ await handleTurnEnd(pi, event, ctx);
631
+ // Should not throw, and no file should be created (no events to append)
632
+ const collectionPath = path.join(testDir, "collections", "context_events.jsonl");
633
+ // ensureDir may create the dir, but the file won't be created if no events
634
+ assert.ok(!fs.existsSync(collectionPath) || fs.readFileSync(collectionPath, "utf-8").trim() === "", "should not append events when log is empty");
635
+ });
636
+ it("handles log with no matching patterns gracefully", async () => {
637
+ const logText = "just some random text\nnothing to match here\n";
638
+ const contextLogTool = {
639
+ name: "context_log",
640
+ execute: async () => ({ content: [{ text: logText }] }),
641
+ };
642
+ const contextCheckoutTool = {
643
+ name: "context_checkout",
644
+ execute: async () => ({}),
645
+ };
646
+ const contextTagTool = { name: "context_tag" };
647
+ const pi = makePi([contextLogTool, contextCheckoutTool, contextTagTool]);
648
+ writeConfig(testDir, {
649
+ collections: {
650
+ main: {
651
+ path: "collections/main.jsonl",
652
+ schema: ["id", "domain", "source", "fact", "tag", "artifact"],
653
+ dedupField: "fact",
654
+ },
655
+ context_events: {
656
+ path: "collections/context_events.jsonl",
657
+ schema: ["id", "type", "session_entry_id", "content", "timestamp", "tags"],
658
+ dedupField: "id",
659
+ },
660
+ },
661
+ extensionCompatibility: {
662
+ "pi-context": {
663
+ enabled: true,
664
+ indexContextEvents: true,
665
+ },
666
+ },
667
+ });
668
+ const ctx = makeCtx(testDir);
669
+ const event = makeTurnEndEvent();
670
+ await handleTurnEnd(pi, event, ctx);
671
+ // Should not throw
672
+ const collectionPath = path.join(testDir, "collections", "context_events.jsonl");
673
+ assert.ok(!fs.existsSync(collectionPath) || fs.readFileSync(collectionPath, "utf-8").trim() === "", "should not append events when no patterns match");
674
+ });
675
+ });