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,256 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { describe, it } from "node:test";
3
+ import { TaskQueue } from "../../src/agent-bus/TaskQueue.js";
4
+ describe("TaskQueue", () => {
5
+ describe("add", () => {
6
+ it("returns a string ID", () => {
7
+ const q = new TaskQueue();
8
+ const id = q.add("test", { foo: "bar" });
9
+ assert.equal(typeof id, "string");
10
+ assert.ok(id.length > 0);
11
+ });
12
+ it("creates a task with status pending", () => {
13
+ const q = new TaskQueue();
14
+ const id = q.add("parse", { file: "test.md" });
15
+ const task = q.get(id);
16
+ assert.ok(task);
17
+ assert.equal(task.status, "pending");
18
+ });
19
+ it("sets createdAt and updatedAt to timestamps", () => {
20
+ const before = Date.now();
21
+ const q = new TaskQueue();
22
+ const id = q.add("build", {});
23
+ const task = q.get(id);
24
+ assert.ok(task);
25
+ assert.equal(typeof task.createdAt, "number");
26
+ assert.equal(typeof task.updatedAt, "number");
27
+ assert.ok(task.createdAt >= before);
28
+ assert.ok(task.updatedAt >= before);
29
+ });
30
+ it("stores type and input on the task", () => {
31
+ const q = new TaskQueue();
32
+ const input = { path: "/tmp/foo", priority: 1 };
33
+ const id = q.add("compile", input);
34
+ const task = q.get(id);
35
+ assert.ok(task);
36
+ assert.equal(task.type, "compile");
37
+ assert.deepStrictEqual(task.input, input);
38
+ });
39
+ });
40
+ describe("get", () => {
41
+ it("returns the task by ID", () => {
42
+ const q = new TaskQueue();
43
+ const id = q.add("test", { x: 1 });
44
+ const task = q.get(id);
45
+ assert.ok(task);
46
+ assert.equal(task.id, id);
47
+ });
48
+ it("returns undefined for an unknown ID", () => {
49
+ const q = new TaskQueue();
50
+ assert.equal(q.get("nonexistent"), undefined);
51
+ });
52
+ });
53
+ describe("getAll", () => {
54
+ it("returns an empty array when no tasks exist", () => {
55
+ const q = new TaskQueue();
56
+ assert.deepStrictEqual(q.getAll(), []);
57
+ });
58
+ it("returns all tasks as an array", () => {
59
+ const q = new TaskQueue();
60
+ const id1 = q.add("a", 1);
61
+ const id2 = q.add("b", 2);
62
+ const all = q.getAll();
63
+ assert.equal(all.length, 2);
64
+ const ids = all.map((t) => t.id).sort();
65
+ assert.deepStrictEqual(ids, [id1, id2].sort());
66
+ });
67
+ });
68
+ describe("getPending", () => {
69
+ it("returns only tasks with status pending", () => {
70
+ const q = new TaskQueue();
71
+ const id1 = q.add("a", 1);
72
+ const id2 = q.add("b", 2);
73
+ q.claim(id1, "agent-1");
74
+ const pending = q.getPending();
75
+ assert.equal(pending.length, 1);
76
+ assert.equal(pending[0].id, id2);
77
+ });
78
+ it("returns empty array when all tasks are claimed", () => {
79
+ const q = new TaskQueue();
80
+ const id = q.add("a", 1);
81
+ q.claim(id, "agent-1");
82
+ assert.deepStrictEqual(q.getPending(), []);
83
+ });
84
+ });
85
+ describe("claim", () => {
86
+ it("transitions pending to in_progress and sets assignedTo", () => {
87
+ const q = new TaskQueue();
88
+ const id = q.add("test", {});
89
+ const result = q.claim(id, "agent-42");
90
+ assert.equal(result, true);
91
+ const task = q.get(id);
92
+ assert.ok(task);
93
+ assert.equal(task.status, "in_progress");
94
+ assert.equal(task.assignedTo, "agent-42");
95
+ });
96
+ it("updates updatedAt on claim", () => {
97
+ const q = new TaskQueue();
98
+ const id = q.add("test", {});
99
+ const original = q.get(id).updatedAt;
100
+ // Small delay to ensure timestamp changes
101
+ const start = Date.now();
102
+ while (Date.now() === start) {
103
+ /* spin */
104
+ }
105
+ q.claim(id, "agent-1");
106
+ const claimed = q.get(id).updatedAt;
107
+ assert.ok(claimed > original);
108
+ });
109
+ it("returns false for an already claimed task", () => {
110
+ const q = new TaskQueue();
111
+ const id = q.add("test", {});
112
+ q.claim(id, "agent-1");
113
+ const result = q.claim(id, "agent-2");
114
+ assert.equal(result, false);
115
+ // Status should still be in_progress, assignedTo unchanged
116
+ const task = q.get(id);
117
+ assert.equal(task.status, "in_progress");
118
+ assert.equal(task.assignedTo, "agent-1");
119
+ });
120
+ it("returns false for a non-existent task", () => {
121
+ const q = new TaskQueue();
122
+ assert.equal(q.claim("nonexistent", "agent-1"), false);
123
+ });
124
+ });
125
+ describe("complete", () => {
126
+ it("transitions in_progress to completed and sets result", () => {
127
+ const q = new TaskQueue();
128
+ const id = q.add("test", {});
129
+ q.claim(id, "agent-1");
130
+ q.complete(id, "agent-1", { output: 42 });
131
+ const task = q.get(id);
132
+ assert.ok(task);
133
+ assert.equal(task.status, "completed");
134
+ assert.deepStrictEqual(task.result, { output: 42 });
135
+ });
136
+ it("updates updatedAt on complete", () => {
137
+ const q = new TaskQueue();
138
+ const id = q.add("test", {});
139
+ q.claim(id, "agent-1");
140
+ const claimedAt = q.get(id).updatedAt;
141
+ const start = Date.now();
142
+ while (Date.now() === start) {
143
+ /* spin */
144
+ }
145
+ q.complete(id, "agent-1", {});
146
+ assert.ok(q.get(id).updatedAt > claimedAt);
147
+ });
148
+ it("is a no-op when the agentId does not match", () => {
149
+ const q = new TaskQueue();
150
+ const id = q.add("test", {});
151
+ q.claim(id, "agent-1");
152
+ q.complete(id, "agent-2", {});
153
+ const task = q.get(id);
154
+ assert.equal(task.status, "in_progress");
155
+ assert.equal(task.result, undefined);
156
+ });
157
+ it("is a no-op for a non-existent task", () => {
158
+ const q = new TaskQueue();
159
+ // Should not throw
160
+ q.complete("nonexistent", "agent-1", {});
161
+ });
162
+ });
163
+ describe("fail", () => {
164
+ it("transitions in_progress to failed and sets error", () => {
165
+ const q = new TaskQueue();
166
+ const id = q.add("test", {});
167
+ q.claim(id, "agent-1");
168
+ q.fail(id, "agent-1", "something went wrong");
169
+ const task = q.get(id);
170
+ assert.ok(task);
171
+ assert.equal(task.status, "failed");
172
+ assert.equal(task.error, "something went wrong");
173
+ });
174
+ it("updates updatedAt on fail", () => {
175
+ const q = new TaskQueue();
176
+ const id = q.add("test", {});
177
+ q.claim(id, "agent-1");
178
+ const claimedAt = q.get(id).updatedAt;
179
+ const start = Date.now();
180
+ while (Date.now() === start) {
181
+ /* spin */
182
+ }
183
+ q.fail(id, "agent-1", "error");
184
+ assert.ok(q.get(id).updatedAt > claimedAt);
185
+ });
186
+ it("is a no-op when the agentId does not match", () => {
187
+ const q = new TaskQueue();
188
+ const id = q.add("test", {});
189
+ q.claim(id, "agent-1");
190
+ q.fail(id, "agent-2", "error");
191
+ const task = q.get(id);
192
+ assert.equal(task.status, "in_progress");
193
+ assert.equal(task.error, undefined);
194
+ });
195
+ it("is a no-op for a non-existent task", () => {
196
+ const q = new TaskQueue();
197
+ // Should not throw
198
+ q.fail("nonexistent", "agent-1", "error");
199
+ });
200
+ });
201
+ describe("edge cases", () => {
202
+ it("claiming a non-existent task returns false", () => {
203
+ const q = new TaskQueue();
204
+ assert.equal(q.claim("no-such-id", "agent-1"), false);
205
+ });
206
+ it("completing a task not assigned to the agent is a no-op", () => {
207
+ const q = new TaskQueue();
208
+ const id = q.add("test", {});
209
+ q.claim(id, "agent-1");
210
+ q.complete(id, "agent-2", {});
211
+ const task = q.get(id);
212
+ assert.equal(task.status, "in_progress");
213
+ assert.equal(task.assignedTo, "agent-1");
214
+ });
215
+ it("failing a completed task by the assigned agent transitions to failed", () => {
216
+ const q = new TaskQueue();
217
+ const id = q.add("test", {});
218
+ q.claim(id, "agent-1");
219
+ q.complete(id, "agent-1", { done: true });
220
+ q.fail(id, "agent-1", "late error");
221
+ const task = q.get(id);
222
+ assert.equal(task.status, "failed");
223
+ assert.equal(task.error, "late error");
224
+ });
225
+ it("failing a pending (unclaimed) task is a no-op", () => {
226
+ const q = new TaskQueue();
227
+ const id = q.add("test", {});
228
+ q.fail(id, "agent-1", "error");
229
+ const task = q.get(id);
230
+ assert.equal(task.status, "pending");
231
+ assert.equal(task.error, undefined);
232
+ });
233
+ it("completing a pending (unclaimed) task is a no-op", () => {
234
+ const q = new TaskQueue();
235
+ const id = q.add("test", {});
236
+ q.complete(id, "agent-1", {});
237
+ const task = q.get(id);
238
+ assert.equal(task.status, "pending");
239
+ assert.equal(task.result, undefined);
240
+ });
241
+ it("claiming a completed task returns false", () => {
242
+ const q = new TaskQueue();
243
+ const id = q.add("test", {});
244
+ q.claim(id, "agent-1");
245
+ q.complete(id, "agent-1", {});
246
+ assert.equal(q.claim(id, "agent-2"), false);
247
+ });
248
+ it("claiming a failed task returns false", () => {
249
+ const q = new TaskQueue();
250
+ const id = q.add("test", {});
251
+ q.claim(id, "agent-1");
252
+ q.fail(id, "agent-1", "boom");
253
+ assert.equal(q.claim(id, "agent-2"), false);
254
+ });
255
+ });
256
+ });
@@ -0,0 +1,73 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { describe, it } from "node:test";
3
+ import { Agent } from "../src/agent-bus/Agent.js";
4
+ import { MessageBus } from "../src/agent-bus/MessageBus.js";
5
+ // Minimal concrete agent that exposes invokePiTool and captures the broadcast.
6
+ class TestAgent extends Agent {
7
+ lastBroadcast = null;
8
+ constructor(bus) {
9
+ super({ id: "test-agent", role: "test", capabilities: [] }, bus);
10
+ }
11
+ async tick() {
12
+ /* no-op */
13
+ }
14
+ async callTool(toolName, args) {
15
+ // invokePiTool will time out since no bridge is listening, but we can
16
+ // capture the broadcast payload via a bus subscription before it times out.
17
+ // Use a very short timeout to fail fast.
18
+ try {
19
+ return await this.invokePiTool(toolName, args, 100);
20
+ }
21
+ catch {
22
+ // Timeout is expected — no bridge is listening. The broadcast already happened.
23
+ return null;
24
+ }
25
+ }
26
+ async callToolWithDispatch(dispatchId, toolName, args) {
27
+ return this.withDispatchContext(dispatchId, () => this.callTool(toolName, args));
28
+ }
29
+ }
30
+ describe("Agent dispatch context (BC-4.3)", () => {
31
+ it("includes dispatchId in tool-call payload when withDispatchContext is active", async () => {
32
+ const bus = new MessageBus();
33
+ const agent = new TestAgent(bus);
34
+ let captured = null;
35
+ bus.subscribe("pi_tool_bridge_requests", (msg) => {
36
+ captured = msg;
37
+ });
38
+ await agent.callToolWithDispatch("dispatch-xyz", "vault_search", { query: "test" });
39
+ assert.ok(captured, "bus should have received the tool request");
40
+ const payload1 = captured.payload;
41
+ assert.equal(payload1.agentId, "test-agent");
42
+ assert.equal(payload1.toolName, "vault_search");
43
+ assert.equal(payload1.dispatchId, "dispatch-xyz");
44
+ });
45
+ it("omits dispatchId when no withDispatchContext is active", async () => {
46
+ const bus = new MessageBus();
47
+ const agent = new TestAgent(bus);
48
+ let captured = null;
49
+ bus.subscribe("pi_tool_bridge_requests", (msg) => {
50
+ captured = msg;
51
+ });
52
+ await agent.callTool("read", { path: "foo.md" });
53
+ assert.ok(captured, "bus should have received the tool request");
54
+ const payload2 = captured.payload;
55
+ assert.equal(payload2.dispatchId, undefined);
56
+ });
57
+ it("clears currentDispatchId after withDispatchContext completes", async () => {
58
+ const bus = new MessageBus();
59
+ const agent = new TestAgent(bus);
60
+ let captured = null;
61
+ bus.subscribe("pi_tool_bridge_requests", (msg) => {
62
+ captured = msg;
63
+ });
64
+ // First call with dispatch context
65
+ await agent.callToolWithDispatch("d1", "read", { path: "a.md" });
66
+ // Second call without
67
+ await agent.callTool("read", { path: "b.md" });
68
+ // The second call should NOT have dispatchId
69
+ // captured was set by the second call (last one wins)
70
+ const payload3 = captured.payload;
71
+ assert.equal(payload3.dispatchId, undefined);
72
+ });
73
+ });
@@ -2,7 +2,7 @@ import { strict as assert } from "node:assert";
2
2
  import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import { afterEach, beforeEach, describe, it } from "node:test";
5
- import { cancelJob, createJob, getJob, listJobs, listPendingByRole, markBatchRunning, markJobFailed, markJobRunning, markerStillPresent, sweepCompletedJobs, } from "../src/agent-queue.js";
5
+ import { cancelJob, createJob, getJob, listJobs, listPendingByRole, markBatchRunning, markerStillPresent, markJobFailed, markJobRunning, sweepCompletedJobs, } from "../src/agent-queue.js";
6
6
  const tmpDir = () => path.join(process.cwd(), ".tmp-agent-queue-test");
7
7
  const makeTestFile = (vaultPath, content) => {
8
8
  const dir = path.join(vaultPath, "Agent");
@@ -0,0 +1,282 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { describe, it } from "node:test";
3
+ import { LLMProvider } from "../../src/agent-bus/LLMProvider.js";
4
+ import { MessageBus } from "../../src/agent-bus/MessageBus.js";
5
+ import { TaskQueue } from "../../src/agent-bus/TaskQueue.js";
6
+ import { BroadcasterAgent } from "../../src/agents/BroadcasterAgent.js";
7
+ import { HeavyLifterAgent } from "../../src/agents/HeavyLifterAgent.js";
8
+ import { ManagerAgent } from "../../src/agents/ManagerAgent.js";
9
+ import { MinerAgent } from "../../src/agents/MinerAgent.js";
10
+ class MockMessageBus extends MessageBus {
11
+ publishCalls = [];
12
+ subscriptions = new Map();
13
+ subscribe(topic, handler) {
14
+ if (!this.subscriptions.has(topic)) {
15
+ this.subscriptions.set(topic, new Set());
16
+ }
17
+ this.subscriptions.get(topic).add(handler);
18
+ }
19
+ unsubscribe(topic, handler) {
20
+ this.subscriptions.get(topic)?.delete(handler);
21
+ }
22
+ async publish(topic, senderId, payload) {
23
+ this.publishCalls.push({ topic, senderId, payload });
24
+ const handlers = this.subscriptions.get(topic);
25
+ if (handlers) {
26
+ const message = {
27
+ id: `msg-${this.publishCalls.length}`,
28
+ topic,
29
+ payload,
30
+ senderId,
31
+ timestamp: Date.now(),
32
+ };
33
+ const promises = Array.from(handlers).map((h) => h(message));
34
+ await Promise.allSettled(promises);
35
+ }
36
+ }
37
+ }
38
+ class MockLLMProvider extends LLMProvider {
39
+ response;
40
+ constructor(response) {
41
+ super({ model: "mock" });
42
+ this.response = response;
43
+ }
44
+ async prompt(_text, _options) {
45
+ return this.response;
46
+ }
47
+ }
48
+ // ---------------------------------------------------------------------------
49
+ // Helpers
50
+ // ---------------------------------------------------------------------------
51
+ function makeConfig(overrides) {
52
+ return { id: "test-agent-1", role: "tester", capabilities: ["test"], ...overrides };
53
+ }
54
+ function makeDispatchJob(overrides) {
55
+ return {
56
+ dispatchId: "dispatch-001",
57
+ role: "miner",
58
+ filePath: "/vault/notes/test.md",
59
+ instruction: "Extract entities from this file",
60
+ vaultPath: "/vault",
61
+ ...overrides,
62
+ };
63
+ }
64
+ function makeJobMessage(job) {
65
+ return {
66
+ id: "msg-job-1",
67
+ topic: "JOB_AVAILABLE",
68
+ payload: job,
69
+ senderId: "dispatcher",
70
+ timestamp: Date.now(),
71
+ };
72
+ }
73
+ function callOnJobAvailable(agent, message) {
74
+ return agent.onJobAvailable(message);
75
+ }
76
+ function callExecuteJob(agent, job) {
77
+ return agent.executeJob(job);
78
+ }
79
+ // ---------------------------------------------------------------------------
80
+ // Test subclasses that override invokePiTool to avoid 30s timeout
81
+ // ---------------------------------------------------------------------------
82
+ class TestMinerAgent extends MinerAgent {
83
+ piToolCalls = [];
84
+ async invokePiTool(toolName, args, _timeoutMs) {
85
+ this.piToolCalls.push({ toolName, args });
86
+ return { ok: true };
87
+ }
88
+ }
89
+ class TestManagerAgent extends ManagerAgent {
90
+ piToolCalls = [];
91
+ async invokePiTool(toolName, args, _timeoutMs) {
92
+ this.piToolCalls.push({ toolName, args });
93
+ return { ok: true };
94
+ }
95
+ }
96
+ class TestBroadcasterAgent extends BroadcasterAgent {
97
+ piToolCalls = [];
98
+ async invokePiTool(toolName, args, _timeoutMs) {
99
+ this.piToolCalls.push({ toolName, args });
100
+ return { ok: true };
101
+ }
102
+ }
103
+ class TestHeavyLifterAgent extends HeavyLifterAgent {
104
+ piToolCalls = [];
105
+ async invokePiTool(toolName, args, _timeoutMs) {
106
+ this.piToolCalls.push({ toolName, args });
107
+ return { ok: true };
108
+ }
109
+ }
110
+ function runAgentTests(factory) {
111
+ describe(factory.name, () => {
112
+ // 1. Constructor subscribes to JOB_AVAILABLE on the bus
113
+ it("subscribes to JOB_AVAILABLE on construction", () => {
114
+ const bus = new MockMessageBus();
115
+ factory.create(bus);
116
+ assert.ok(bus.subscriptions.has("JOB_AVAILABLE"));
117
+ });
118
+ // 2. setTaskQueue stores the task queue
119
+ it("setTaskQueue stores the task queue", () => {
120
+ const bus = new MockMessageBus();
121
+ const agent = factory.create(bus);
122
+ const tq = new TaskQueue();
123
+ agent.setTaskQueue(tq);
124
+ // Verify by triggering onJobAvailable — it should use the stored queue
125
+ const job = makeDispatchJob({ role: factory.role });
126
+ const msg = makeJobMessage(job);
127
+ // onJobAvailable should not bail early (taskQueue is set)
128
+ // It will try to claim, which succeeds since the task is pending
129
+ callOnJobAvailable(agent, msg).catch(() => {
130
+ /* may fail if executeJob internals throw, but taskQueue was used */
131
+ });
132
+ });
133
+ // 3. onJobAvailable ignores jobs for other roles
134
+ it("ignores jobs for other roles", async () => {
135
+ const bus = new MockMessageBus();
136
+ const agent = factory.create(bus);
137
+ const tq = new TaskQueue();
138
+ agent.setTaskQueue(tq);
139
+ const wrongRole = factory.role === "miner" ? "manager" : "miner";
140
+ const job = makeDispatchJob({ role: wrongRole });
141
+ const msg = makeJobMessage(job);
142
+ await callOnJobAvailable(agent, msg);
143
+ // No task should have been added to the queue
144
+ assert.equal(tq.getAll().length, 0);
145
+ // No JOB_COMPLETED broadcast
146
+ const completions = bus.publishCalls.filter((c) => c.topic === "JOB_COMPLETED");
147
+ assert.equal(completions.length, 0);
148
+ });
149
+ // 4. onJobAvailable ignores when taskQueue is null
150
+ it("ignores when taskQueue is null", async () => {
151
+ const bus = new MockMessageBus();
152
+ const agent = factory.create(bus);
153
+ // Do NOT call setTaskQueue
154
+ const job = makeDispatchJob({ role: factory.role });
155
+ const msg = makeJobMessage(job);
156
+ await callOnJobAvailable(agent, msg);
157
+ // No JOB_COMPLETED broadcast
158
+ const completions = bus.publishCalls.filter((c) => c.topic === "JOB_COMPLETED");
159
+ assert.equal(completions.length, 0);
160
+ });
161
+ // 5. onJobAvailable claims task, executes, completes, broadcasts JOB_COMPLETED with status "done"
162
+ it("claims task, executes, completes, broadcasts JOB_COMPLETED with status done", async () => {
163
+ const bus = new MockMessageBus();
164
+ const agent = factory.create(bus);
165
+ const tq = new TaskQueue();
166
+ agent.setTaskQueue(tq);
167
+ const job = makeDispatchJob({ role: factory.role });
168
+ const msg = makeJobMessage(job);
169
+ await callOnJobAvailable(agent, msg);
170
+ // Task was added and completed
171
+ const tasks = tq.getAll();
172
+ assert.equal(tasks.length, 1);
173
+ assert.equal(tasks[0].status, "completed");
174
+ assert.equal(tasks[0].type, "agent-dispatch");
175
+ // JOB_COMPLETED was broadcast with status "done"
176
+ const completions = bus.publishCalls.filter((c) => c.topic === "JOB_COMPLETED");
177
+ assert.equal(completions.length, 1);
178
+ assert.equal(completions[0].payload.dispatchId, "dispatch-001");
179
+ assert.equal(completions[0].payload.status, "done");
180
+ });
181
+ // 6. onJobAvailable on failure: fails task, broadcasts JOB_COMPLETED with status "failed" and error
182
+ it("on failure: fails task, broadcasts JOB_COMPLETED with status failed and error", async () => {
183
+ const bus = new MockMessageBus();
184
+ const agent = factory.create(bus);
185
+ const tq = new TaskQueue();
186
+ agent.setTaskQueue(tq);
187
+ // Make invokePiTool throw to trigger the catch branch
188
+ agent.invokePiTool = async (_toolName, _args, _timeoutMs) => {
189
+ throw new Error("simulated tool failure");
190
+ };
191
+ const job = makeDispatchJob({ role: factory.role });
192
+ const msg = makeJobMessage(job);
193
+ await callOnJobAvailable(agent, msg);
194
+ // Task was added and failed
195
+ const tasks = tq.getAll();
196
+ assert.equal(tasks.length, 1);
197
+ assert.equal(tasks[0].status, "failed");
198
+ assert.equal(tasks[0].error, "simulated tool failure");
199
+ // JOB_COMPLETED was broadcast with status "failed"
200
+ const completions = bus.publishCalls.filter((c) => c.topic === "JOB_COMPLETED");
201
+ assert.equal(completions.length, 1);
202
+ assert.equal(completions[0].payload.dispatchId, "dispatch-001");
203
+ assert.equal(completions[0].payload.status, "failed");
204
+ assert.equal(completions[0].payload.error, "simulated tool failure");
205
+ });
206
+ // 7. executeJob calls invokePiTool("read") then invokePiTool("edit") to replace dispatch marker
207
+ it("executeJob calls read then edit to replace dispatch marker", async () => {
208
+ const bus = new MockMessageBus();
209
+ const agent = factory.create(bus);
210
+ const job = makeDispatchJob({ role: factory.role });
211
+ await callExecuteJob(agent, job);
212
+ // First call: read
213
+ assert.ok(agent.piToolCalls.length >= 2);
214
+ assert.equal(agent.piToolCalls[0].toolName, "read");
215
+ assert.deepEqual(agent.piToolCalls[0].args, { path: job.filePath });
216
+ // Last call: edit with dispatch marker replacement
217
+ const editCall = agent.piToolCalls[agent.piToolCalls.length - 1];
218
+ assert.equal(editCall.toolName, "edit");
219
+ assert.equal(editCall.args.path, job.filePath);
220
+ assert.ok(Array.isArray(editCall.args.edits));
221
+ const edits = editCall.args.edits;
222
+ assert.equal(edits.length, 1);
223
+ assert.equal(edits[0].oldText, `<!-- pi-dispatch:${job.dispatchId} -->`);
224
+ assert.equal(edits[0].newText, factory.expectedEditText);
225
+ });
226
+ // 8. executeJob with LLM: calls askLLM, invokes each tool from the plan
227
+ it("executeJob with LLM: calls askLLM and invokes each tool from the plan", async () => {
228
+ const bus = new MockMessageBus();
229
+ const planTools = [
230
+ { name: "vm_append", args: { collection: "main", data: { entity: "test" } } },
231
+ { name: "write", args: { path: "/output.md", content: "result" } },
232
+ ];
233
+ const llm = new MockLLMProvider(JSON.stringify({ tools: planTools }));
234
+ const agent = factory.create(bus, llm);
235
+ const job = makeDispatchJob({ role: factory.role });
236
+ await callExecuteJob(agent, job);
237
+ // First call is always "read"
238
+ assert.equal(agent.piToolCalls[0].toolName, "read");
239
+ // Then the two tools from the LLM plan
240
+ assert.equal(agent.piToolCalls[1].toolName, "vm_append");
241
+ assert.deepEqual(agent.piToolCalls[1].args, { collection: "main", data: { entity: "test" } });
242
+ assert.equal(agent.piToolCalls[2].toolName, "write");
243
+ assert.deepEqual(agent.piToolCalls[2].args, { path: "/output.md", content: "result" });
244
+ // Last call is always "edit"
245
+ const lastCall = agent.piToolCalls[agent.piToolCalls.length - 1];
246
+ assert.equal(lastCall.toolName, "edit");
247
+ });
248
+ // 9. tick() is a no-op (doesn't throw)
249
+ it("tick() is a no-op and does not throw", async () => {
250
+ const bus = new MockMessageBus();
251
+ const agent = factory.create(bus);
252
+ await assert.doesNotReject(() => agent.tick());
253
+ });
254
+ });
255
+ }
256
+ // ---------------------------------------------------------------------------
257
+ // Run the shared suite for each agent
258
+ // ---------------------------------------------------------------------------
259
+ runAgentTests({
260
+ name: "MinerAgent",
261
+ role: "miner",
262
+ create: (bus, llm) => new TestMinerAgent(makeConfig({ id: "miner-1", role: "miner" }), bus, llm),
263
+ expectedEditText: "> Miner extracted findings. See dispatch dispatch-001.",
264
+ });
265
+ runAgentTests({
266
+ name: "ManagerAgent",
267
+ role: "manager",
268
+ create: (bus, llm) => new TestManagerAgent(makeConfig({ id: "manager-1", role: "manager" }), bus, llm),
269
+ expectedEditText: "> Manager completed. See dispatch dispatch-001.",
270
+ });
271
+ runAgentTests({
272
+ name: "BroadcasterAgent",
273
+ role: "broadcaster",
274
+ create: (bus, llm) => new TestBroadcasterAgent(makeConfig({ id: "broadcaster-1", role: "broadcaster" }), bus, llm),
275
+ expectedEditText: "> Broadcaster completed. See dispatch dispatch-001.",
276
+ });
277
+ runAgentTests({
278
+ name: "HeavyLifterAgent",
279
+ role: "heavy-lifter",
280
+ create: (bus, llm) => new TestHeavyLifterAgent(makeConfig({ id: "heavy-1", role: "heavy-lifter" }), bus, llm),
281
+ expectedEditText: "> Heavy-Lifter completed. See dispatch dispatch-001.",
282
+ });