onbuzz 3.6.1 → 3.6.2

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 (83) hide show
  1. package/package.json +1 -1
  2. package/src/__test-utils__/fixtures/malformedJson.js +31 -0
  3. package/src/__test-utils__/globalSetup.js +9 -0
  4. package/src/__test-utils__/globalTeardown.js +12 -0
  5. package/src/__test-utils__/mockFactories.js +101 -0
  6. package/src/analyzers/__tests__/CSSAnalyzer.test.js +41 -0
  7. package/src/analyzers/__tests__/ConfigValidator.test.js +362 -0
  8. package/src/analyzers/__tests__/ESLintAnalyzer.test.js +271 -0
  9. package/src/analyzers/__tests__/JavaScriptAnalyzer.test.js +40 -0
  10. package/src/analyzers/__tests__/PrettierFormatter.test.js +197 -0
  11. package/src/analyzers/__tests__/PythonAnalyzer.test.js +208 -0
  12. package/src/analyzers/__tests__/SecurityAnalyzer.test.js +303 -0
  13. package/src/analyzers/__tests__/SparrowAnalyzer.test.js +270 -0
  14. package/src/analyzers/__tests__/TypeScriptAnalyzer.test.js +187 -0
  15. package/src/core/__tests__/agentPool.test.js +601 -0
  16. package/src/core/__tests__/agentScheduler.test.js +576 -0
  17. package/src/core/__tests__/contextManager.test.js +252 -0
  18. package/src/core/__tests__/flowExecutor.test.js +262 -0
  19. package/src/core/__tests__/messageProcessor.test.js +627 -0
  20. package/src/core/__tests__/orchestrator.test.js +257 -0
  21. package/src/core/__tests__/stateManager.test.js +375 -0
  22. package/src/core/agentPool.js +11 -1
  23. package/src/index.js +25 -9
  24. package/src/interfaces/terminal/__tests__/smoke/imports.test.js +3 -5
  25. package/src/services/__tests__/agentActivityService.test.js +319 -0
  26. package/src/services/__tests__/apiKeyManager.test.js +206 -0
  27. package/src/services/__tests__/benchmarkService.test.js +184 -0
  28. package/src/services/__tests__/budgetService.test.js +211 -0
  29. package/src/services/__tests__/contextInjectionService.test.js +205 -0
  30. package/src/services/__tests__/conversationCompactionService.test.js +280 -0
  31. package/src/services/__tests__/credentialVault.test.js +469 -0
  32. package/src/services/__tests__/errorHandler.test.js +314 -0
  33. package/src/services/__tests__/fileAttachmentService.test.js +278 -0
  34. package/src/services/__tests__/flowContextService.test.js +199 -0
  35. package/src/services/__tests__/memoryService.test.js +450 -0
  36. package/src/services/__tests__/modelRouterService.test.js +388 -0
  37. package/src/services/__tests__/modelsService.test.js +261 -0
  38. package/src/services/__tests__/portRegistry.test.js +123 -0
  39. package/src/services/__tests__/projectDetector.test.js +34 -0
  40. package/src/services/__tests__/promptService.test.js +242 -0
  41. package/src/services/__tests__/qualityInspector.test.js +97 -0
  42. package/src/services/__tests__/scheduleService.test.js +308 -0
  43. package/src/services/__tests__/serviceRegistry.test.js +74 -0
  44. package/src/services/__tests__/skillsService.test.js +402 -0
  45. package/src/services/__tests__/tokenCountingService.test.js +48 -0
  46. package/src/tools/__tests__/agentCommunicationTool.test.js +500 -0
  47. package/src/tools/__tests__/agentDelayTool.test.js +342 -0
  48. package/src/tools/__tests__/asyncToolManager.test.js +344 -0
  49. package/src/tools/__tests__/baseTool.test.js +420 -0
  50. package/src/tools/__tests__/codeMapTool.test.js +348 -0
  51. package/src/tools/__tests__/fileContentReplaceTool.test.js +309 -0
  52. package/src/tools/__tests__/fileTreeTool.test.js +274 -0
  53. package/src/tools/__tests__/filesystemTool.test.js +717 -0
  54. package/src/tools/__tests__/helpTool.test.js +204 -0
  55. package/src/tools/__tests__/jobDoneTool.test.js +296 -0
  56. package/src/tools/__tests__/memoryTool.test.js +297 -0
  57. package/src/tools/__tests__/seekTool.test.js +282 -0
  58. package/src/tools/__tests__/skillsTool.test.js +226 -0
  59. package/src/tools/__tests__/staticAnalysisTool.test.js +509 -0
  60. package/src/tools/__tests__/taskManagerTool.test.js +725 -0
  61. package/src/tools/__tests__/terminalTool.test.js +384 -0
  62. package/src/tools/__tests__/userPromptTool.test.js +297 -0
  63. package/src/tools/__tests__/webTool.e2e.test.js +25 -11
  64. package/src/tools/webTool.js +6 -12
  65. package/src/types/__tests__/agent.test.js +499 -0
  66. package/src/types/__tests__/contextReference.test.js +606 -0
  67. package/src/types/__tests__/conversation.test.js +555 -0
  68. package/src/types/__tests__/toolCommand.test.js +584 -0
  69. package/src/types/contextReference.js +1 -1
  70. package/src/utilities/__tests__/attachmentValidator.test.js +80 -0
  71. package/src/utilities/__tests__/configManager.test.js +397 -0
  72. package/src/utilities/__tests__/constants.test.js +49 -0
  73. package/src/utilities/__tests__/directoryAccessManager.test.js +388 -0
  74. package/src/utilities/__tests__/fileProcessor.test.js +104 -0
  75. package/src/utilities/__tests__/jsonRepair.test.js +104 -0
  76. package/src/utilities/__tests__/logger.test.js +129 -0
  77. package/src/utilities/__tests__/platformUtils.test.js +87 -0
  78. package/src/utilities/__tests__/structuredFileValidator.test.js +263 -0
  79. package/src/utilities/__tests__/tagParser.test.js +887 -0
  80. package/src/utilities/__tests__/toolConstants.test.js +94 -0
  81. package/src/utilities/tagParser.js +2 -2
  82. package/src/tools/browserTool.js +0 -897
  83. package/src/utilities/platformUtils.test.js +0 -98
@@ -0,0 +1,601 @@
1
+ /**
2
+ * AgentPool - Comprehensive unit tests (target: 80%+ line coverage)
3
+ * Tests agent lifecycle, state transitions, message queuing, pause/resume,
4
+ * conversation management, directory access, and edge cases.
5
+ */
6
+ import { jest, describe, test, expect, beforeEach } from '@jest/globals';
7
+ import { createMockLogger, createMockConfig, createMockStateManager } from '../../__test-utils__/mockFactories.js';
8
+
9
+ // ── Mocks ────────────────────────────────────────────────────────────────────
10
+ const mockValidateAccessConfiguration = jest.fn().mockReturnValue({ valid: true });
11
+ const mockCreateProjectDefaults = jest.fn().mockReturnValue({
12
+ workingDirectory: '/tmp/project',
13
+ readOnlyDirectories: [],
14
+ writeEnabledDirectories: ['/tmp/project']
15
+ });
16
+
17
+ jest.unstable_mockModule('../../utilities/directoryAccessManager.js', () => {
18
+ const MockDAM = jest.fn().mockImplementation(() => ({
19
+ validateAccessConfiguration: mockValidateAccessConfiguration
20
+ }));
21
+ MockDAM.createProjectDefaults = mockCreateProjectDefaults;
22
+ return { default: MockDAM };
23
+ });
24
+
25
+ jest.unstable_mockModule('../../services/visualEditorBridge.js', () => ({
26
+ getVisualEditorBridge: jest.fn().mockReturnValue({
27
+ hasInstance: jest.fn().mockReturnValue(false),
28
+ stopInstance: jest.fn().mockResolvedValue(undefined)
29
+ })
30
+ }));
31
+
32
+ const { default: AgentPool } = await import('../agentPool.js');
33
+
34
+ // ── Helpers ──────────────────────────────────────────────────────────────────
35
+ function makePool(overrides = {}) {
36
+ const config = createMockConfig(overrides.config);
37
+ const logger = createMockLogger();
38
+ const stateManager = createMockStateManager();
39
+ const contextManager = { getContext: jest.fn() };
40
+ const toolsRegistry = overrides.toolsRegistry || null;
41
+ const pool = new AgentPool(config, logger, stateManager, contextManager, toolsRegistry);
42
+ return { pool, config, logger, stateManager, contextManager };
43
+ }
44
+
45
+ function agentCfg(overrides = {}) {
46
+ return {
47
+ name: 'TestAgent',
48
+ systemPrompt: 'You are a test agent.',
49
+ preferredModel: 'test-model',
50
+ capabilities: [],
51
+ projectDir: '/tmp/project',
52
+ ...overrides
53
+ };
54
+ }
55
+
56
+ // ── Tests ────────────────────────────────────────────────────────────────────
57
+ describe('AgentPool', () => {
58
+ let pool, logger, stateManager;
59
+
60
+ beforeEach(() => {
61
+ jest.clearAllMocks();
62
+ ({ pool, logger, stateManager } = makePool());
63
+ });
64
+
65
+ // ─── createAgent ───────────────────────────────────────────────────────
66
+ describe('createAgent', () => {
67
+ test('creates agent with correct default fields', async () => {
68
+ const agent = await pool.createAgent(agentCfg());
69
+ expect(agent.id).toMatch(/^agent-testagent-/);
70
+ expect(agent.name).toBe('TestAgent');
71
+ expect(agent.status).toBe('active');
72
+ expect(agent.mode).toBe('chat');
73
+ expect(agent.preferredModel).toBe('test-model');
74
+ expect(agent.conversations.full.messages).toEqual([]);
75
+ expect(agent.messageQueues.userMessages).toEqual([]);
76
+ expect(agent.messageQueues.interAgentMessages).toEqual([]);
77
+ expect(agent.messageQueues.toolResults).toEqual([]);
78
+ expect(agent.iterationCount).toBe(0);
79
+ expect(agent.maxIterations).toBe(10);
80
+ expect(agent.stopRequested).toBe(false);
81
+ expect(agent.taskList.tasks).toEqual([]);
82
+ });
83
+
84
+ test('generates unique IDs for different agents', async () => {
85
+ const a1 = await pool.createAgent(agentCfg({ name: 'Alpha' }));
86
+ const a2 = await pool.createAgent(agentCfg({ name: 'Beta' }));
87
+ expect(a1.id).not.toBe(a2.id);
88
+ expect(a1.id).toMatch(/^agent-alpha-/);
89
+ expect(a2.id).toMatch(/^agent-beta-/);
90
+ });
91
+
92
+ test('applies mode from config', async () => {
93
+ const agent = await pool.createAgent(agentCfg({ mode: 'agent' }));
94
+ expect(agent.mode).toBe('agent');
95
+ });
96
+
97
+ test('initializes model-specific conversation for preferredModel', async () => {
98
+ const agent = await pool.createAgent(agentCfg({ preferredModel: 'gpt-4' }));
99
+ expect(agent.conversations['gpt-4']).toBeDefined();
100
+ expect(agent.conversations['gpt-4'].messages).toEqual([]);
101
+ expect(agent.conversations['gpt-4'].compactizedMessages).toBeNull();
102
+ expect(agent.conversations['gpt-4'].compactizationCount).toBe(0);
103
+ });
104
+
105
+ test('persists agent state after creation', async () => {
106
+ await pool.createAgent(agentCfg());
107
+ expect(stateManager.persistAgentState).toHaveBeenCalled();
108
+ });
109
+
110
+ test('enhances system prompt via toolsRegistry when capabilities present', async () => {
111
+ const toolsRegistry = {
112
+ enhanceSystemPrompt: jest.fn().mockReturnValue('enhanced prompt')
113
+ };
114
+ const { pool: p2 } = makePool({ toolsRegistry });
115
+ const agent = await p2.createAgent(agentCfg({ capabilities: ['terminal'] }));
116
+ expect(toolsRegistry.enhanceSystemPrompt).toHaveBeenCalledWith(
117
+ 'You are a test agent.',
118
+ ['terminal'],
119
+ expect.objectContaining({ compact: false })
120
+ );
121
+ expect(agent.systemPrompt).toBe('enhanced prompt');
122
+ expect(agent.originalSystemPrompt).toBe('You are a test agent.');
123
+ });
124
+
125
+ test('falls back to original prompt when enhancement throws', async () => {
126
+ const toolsRegistry = {
127
+ enhanceSystemPrompt: jest.fn().mockImplementation(() => { throw new Error('boom'); })
128
+ };
129
+ const { pool: p2 } = makePool({ toolsRegistry });
130
+ const agent = await p2.createAgent(agentCfg({ capabilities: ['terminal'] }));
131
+ expect(agent.systemPrompt).toBe('You are a test agent.');
132
+ });
133
+
134
+ test('skips enhancement when capabilities is empty', async () => {
135
+ const toolsRegistry = { enhanceSystemPrompt: jest.fn() };
136
+ const { pool: p2 } = makePool({ toolsRegistry });
137
+ await p2.createAgent(agentCfg({ capabilities: [] }));
138
+ expect(toolsRegistry.enhanceSystemPrompt).not.toHaveBeenCalled();
139
+ });
140
+
141
+ test('validates directory access configuration when provided', async () => {
142
+ const dirAccess = { workingDirectory: '/custom', readOnlyDirectories: [], writeEnabledDirectories: ['/custom'] };
143
+ const agent = await pool.createAgent(agentCfg({ directoryAccess: dirAccess }));
144
+ expect(mockValidateAccessConfiguration).toHaveBeenCalledWith(dirAccess);
145
+ expect(agent.directoryAccess).toBe(dirAccess);
146
+ });
147
+
148
+ test('throws on invalid directory access configuration', async () => {
149
+ mockValidateAccessConfiguration.mockReturnValueOnce({ valid: false, errors: ['bad path'] });
150
+ await expect(pool.createAgent(agentCfg({
151
+ directoryAccess: { workingDirectory: '/bad' }
152
+ }))).rejects.toThrow('Invalid directory access configuration');
153
+ });
154
+
155
+ test('creates default directory access when none provided', async () => {
156
+ await pool.createAgent(agentCfg());
157
+ expect(mockCreateProjectDefaults).toHaveBeenCalledWith('/tmp/project');
158
+ });
159
+
160
+ test('enforces MAX_AGENTS limit', async () => {
161
+ const { pool: p2 } = makePool({ config: { system: { maxAgentsPerProject: 2 } } });
162
+ await p2.createAgent(agentCfg({ name: 'A1' }));
163
+ await p2.createAgent(agentCfg({ name: 'A2' }));
164
+ await expect(p2.createAgent(agentCfg({ name: 'A3' }))).rejects.toThrow('Maximum agents per project exceeded');
165
+ });
166
+
167
+ test('stores sessionId, metadata, and platformProvided', async () => {
168
+ const agent = await pool.createAgent(agentCfg({
169
+ sessionId: 'sess-123',
170
+ metadata: { foo: 'bar' },
171
+ platformProvided: false
172
+ }));
173
+ expect(agent.sessionId).toBe('sess-123');
174
+ expect(agent.metadata).toEqual({ foo: 'bar' });
175
+ expect(agent.platformProvided).toBe(false);
176
+ });
177
+
178
+ test('uses process.cwd when no projectDir specified and no directoryAccess', async () => {
179
+ mockCreateProjectDefaults.mockClear();
180
+ await pool.createAgent(agentCfg({ projectDir: undefined }));
181
+ // Should call with process.cwd() as fallback
182
+ expect(mockCreateProjectDefaults).toHaveBeenCalled();
183
+ });
184
+ });
185
+
186
+ // ─── getAgent ──────────────────────────────────────────────────────────
187
+ describe('getAgent', () => {
188
+ test('returns agent by ID after creation', async () => {
189
+ const created = await pool.createAgent(agentCfg());
190
+ const found = await pool.getAgent(created.id);
191
+ expect(found).toBe(created);
192
+ });
193
+
194
+ test('returns null for non-existent agent', async () => {
195
+ expect(await pool.getAgent('nonexistent')).toBeNull();
196
+ });
197
+ });
198
+
199
+ // ─── updateAgent ──────────────────────────────────────────────────────
200
+ describe('updateAgent', () => {
201
+ test('updates fields and preserves ID', async () => {
202
+ const agent = await pool.createAgent(agentCfg());
203
+ const updated = await pool.updateAgent(agent.id, { name: 'Updated', id: 'should-be-ignored' });
204
+ expect(updated.name).toBe('Updated');
205
+ expect(updated.id).toBe(agent.id);
206
+ expect(updated.lastModified).toBeDefined();
207
+ });
208
+
209
+ test('throws for non-existent agent', async () => {
210
+ await expect(pool.updateAgent('nonexistent', { name: 'X' })).rejects.toThrow('Agent not found');
211
+ });
212
+
213
+ test('persists state after update', async () => {
214
+ const agent = await pool.createAgent(agentCfg());
215
+ stateManager.persistAgentState.mockClear();
216
+ await pool.updateAgent(agent.id, { name: 'Updated' });
217
+ expect(stateManager.persistAgentState).toHaveBeenCalled();
218
+ });
219
+
220
+ test('validates directory access in updates', async () => {
221
+ const agent = await pool.createAgent(agentCfg());
222
+ mockValidateAccessConfiguration.mockReturnValueOnce({ valid: false, errors: ['invalid'] });
223
+ await expect(pool.updateAgent(agent.id, {
224
+ directoryAccess: { workingDirectory: '/bad' }
225
+ })).rejects.toThrow('Invalid directory access configuration');
226
+ });
227
+
228
+ test('updates currentModel when preferredModel changes and copies conversation', async () => {
229
+ const agent = await pool.createAgent(agentCfg({ preferredModel: 'model-a' }));
230
+ // Add a message to old model conversation
231
+ agent.conversations['model-a'].messages.push({ role: 'user', content: 'old msg' });
232
+ const updated = await pool.updateAgent(agent.id, { preferredModel: 'model-b' });
233
+ expect(updated.currentModel).toBe('model-b');
234
+ expect(updated.conversations['model-b']).toBeDefined();
235
+ // Conversation should have been copied
236
+ expect(updated.conversations['model-b'].messages).toHaveLength(1);
237
+ });
238
+
239
+ test('regenerates system prompt when capabilities change', async () => {
240
+ const toolsRegistry = { enhanceSystemPrompt: jest.fn().mockReturnValue('new enhanced') };
241
+ const { pool: p2 } = makePool({ toolsRegistry });
242
+ const agent = await p2.createAgent(agentCfg());
243
+ toolsRegistry.enhanceSystemPrompt.mockClear();
244
+ await p2.updateAgent(agent.id, { capabilities: ['terminal'] });
245
+ expect(toolsRegistry.enhanceSystemPrompt).toHaveBeenCalled();
246
+ });
247
+
248
+ test('regenerates system prompt when originalSystemPrompt is updated', async () => {
249
+ const toolsRegistry = { enhanceSystemPrompt: jest.fn().mockReturnValue('re-enhanced') };
250
+ const { pool: p2 } = makePool({ toolsRegistry });
251
+ const agent = await p2.createAgent(agentCfg());
252
+ toolsRegistry.enhanceSystemPrompt.mockClear();
253
+ const updated = await p2.updateAgent(agent.id, { originalSystemPrompt: 'Brand new prompt' });
254
+ expect(toolsRegistry.enhanceSystemPrompt).toHaveBeenCalled();
255
+ expect(updated.originalSystemPrompt).toBe('Brand new prompt');
256
+ });
257
+ });
258
+
259
+ // ─── deleteAgent ──────────────────────────────────────────────────────
260
+ describe('deleteAgent', () => {
261
+ test('removes agent from pool and returns success', async () => {
262
+ const agent = await pool.createAgent(agentCfg());
263
+ const result = await pool.deleteAgent(agent.id);
264
+ expect(result.success).toBe(true);
265
+ expect(result.remainingAgents).toBe(0);
266
+ expect(await pool.getAgent(agent.id)).toBeNull();
267
+ });
268
+
269
+ test('throws for non-existent agent', async () => {
270
+ await expect(pool.deleteAgent('nonexistent')).rejects.toThrow('Agent not found');
271
+ });
272
+
273
+ test('cleans up maps (directory, paused, notification)', async () => {
274
+ const agent = await pool.createAgent(agentCfg());
275
+ pool.pausedAgents.set(agent.id, {});
276
+ pool.notificationQueue.set(agent.id, []);
277
+ await pool.deleteAgent(agent.id);
278
+ expect(pool.pausedAgents.has(agent.id)).toBe(false);
279
+ expect(pool.notificationQueue.has(agent.id)).toBe(false);
280
+ expect(pool.agentDirectory.has(agent.id)).toBe(false);
281
+ });
282
+
283
+ test('agent is no longer retrievable after delete', async () => {
284
+ const agent = await pool.createAgent(agentCfg());
285
+ await pool.deleteAgent(agent.id);
286
+ const retrieved = await pool.getAgent(agent.id);
287
+ expect(retrieved).toBeFalsy();
288
+ });
289
+ });
290
+
291
+ // ─── unloadAgent ──────────────────────────────────────────────────────
292
+ describe('unloadAgent', () => {
293
+ test('removes from memory but persists state first', async () => {
294
+ const agent = await pool.createAgent(agentCfg());
295
+ stateManager.persistAgentState.mockClear();
296
+ const result = await pool.unloadAgent(agent.id);
297
+ expect(result.success).toBe(true);
298
+ expect(result.agentName).toBe('TestAgent');
299
+ expect(result.message).toContain('unloaded');
300
+ expect(await pool.getAgent(agent.id)).toBeNull();
301
+ expect(stateManager.persistAgentState).toHaveBeenCalled();
302
+ });
303
+
304
+ test('throws for non-existent agent', async () => {
305
+ await expect(pool.unloadAgent('nonexistent')).rejects.toThrow('Agent not found');
306
+ });
307
+
308
+ test('calls scheduler.removeAgent if scheduler is set', async () => {
309
+ const mockScheduler = { removeAgent: jest.fn() };
310
+ pool.setScheduler(mockScheduler);
311
+ const agent = await pool.createAgent(agentCfg());
312
+ await pool.unloadAgent(agent.id);
313
+ expect(mockScheduler.removeAgent).toHaveBeenCalledWith(agent.id, 'unloaded');
314
+ });
315
+ });
316
+
317
+ // ─── pauseAgent / resumeAgent ─────────────────────────────────────────
318
+ describe('pauseAgent', () => {
319
+ test('sets paused status and pausedUntil with seconds duration', async () => {
320
+ const agent = await pool.createAgent(agentCfg());
321
+ const result = await pool.pauseAgent(agent.id, 60, 'test pause');
322
+ expect(result.success).toBe(true);
323
+ expect(agent.status).toBe('paused');
324
+ expect(agent.pausedUntil).toBeDefined();
325
+ expect(pool.pausedAgents.has(agent.id)).toBe(true);
326
+ const pauseInfo = pool.pausedAgents.get(agent.id);
327
+ expect(pauseInfo.reason).toBe('test pause');
328
+ });
329
+
330
+ test('accepts Date as duration', async () => {
331
+ const agent = await pool.createAgent(agentCfg());
332
+ const future = new Date(Date.now() + 60000);
333
+ const result = await pool.pauseAgent(agent.id, future);
334
+ expect(result.success).toBe(true);
335
+ expect(new Date(agent.pausedUntil).getTime()).toBe(future.getTime());
336
+ });
337
+
338
+ test('caps duration to maxPauseDuration config', async () => {
339
+ const { pool: p2 } = makePool({ config: { system: { maxPauseDuration: 10 } } });
340
+ const agent = await p2.createAgent(agentCfg());
341
+ await p2.pauseAgent(agent.id, 9999, 'long pause');
342
+ const pauseEnd = new Date(agent.pausedUntil).getTime();
343
+ expect(pauseEnd).toBeLessThan(Date.now() + 15000);
344
+ });
345
+
346
+ test('throws for non-existent agent', async () => {
347
+ await expect(pool.pauseAgent('nonexistent', 60)).rejects.toThrow('Agent not found');
348
+ });
349
+ });
350
+
351
+ describe('resumeAgent (unpause)', () => {
352
+ test('resumes paused agent to active', async () => {
353
+ const agent = await pool.createAgent(agentCfg());
354
+ await pool.pauseAgent(agent.id, 300, 'test');
355
+ const result = await pool.resumeAgent(agent.id);
356
+ expect(result.success).toBe(true);
357
+ expect(agent.status).toBe('active');
358
+ expect(agent.pausedUntil).toBeNull();
359
+ expect(pool.pausedAgents.has(agent.id)).toBe(false);
360
+ });
361
+
362
+ test('no-op for non-paused agent', async () => {
363
+ const agent = await pool.createAgent(agentCfg());
364
+ const result = await pool.resumeAgent(agent.id);
365
+ expect(result.success).toBe(true);
366
+ expect(result.message).toContain('not paused');
367
+ });
368
+
369
+ test('throws for non-existent agent', async () => {
370
+ await expect(pool.resumeAgent('nonexistent')).rejects.toThrow('Agent not found');
371
+ });
372
+ });
373
+
374
+ // ─── Message queue methods ────────────────────────────────────────────
375
+ describe('addUserMessage', () => {
376
+ test('pushes message with generated ID and timestamps', async () => {
377
+ const agent = await pool.createAgent(agentCfg());
378
+ await pool.addUserMessage(agent.id, { content: 'hello', role: 'user' });
379
+ expect(agent.messageQueues.userMessages).toHaveLength(1);
380
+ const msg = agent.messageQueues.userMessages[0];
381
+ expect(msg.content).toBe('hello');
382
+ expect(msg.id).toBeDefined();
383
+ expect(msg.queuedAt).toBeDefined();
384
+ });
385
+
386
+ test('auto-creates task for AGENT mode agents', async () => {
387
+ const agent = await pool.createAgent(agentCfg({ mode: 'agent' }));
388
+ await pool.addUserMessage(agent.id, { content: 'do something' });
389
+ expect(agent.taskList.tasks).toHaveLength(1);
390
+ expect(agent.taskList.tasks[0].source).toBe('auto-created');
391
+ });
392
+
393
+ test('throws for non-existent agent', async () => {
394
+ await expect(pool.addUserMessage('nonexistent', { content: 'hi' })).rejects.toThrow('Agent not found');
395
+ });
396
+ });
397
+
398
+ describe('addInterAgentMessage', () => {
399
+ test('pushes message with sender info', async () => {
400
+ const agent = await pool.createAgent(agentCfg());
401
+ await pool.addInterAgentMessage(agent.id, { content: 'inter-msg', sender: 'agent-x', senderName: 'AgentX' });
402
+ expect(agent.messageQueues.interAgentMessages).toHaveLength(1);
403
+ expect(agent.messageQueues.interAgentMessages[0].content).toBe('inter-msg');
404
+ });
405
+
406
+ test('auto-creates task for AGENT mode agents with sender label', async () => {
407
+ const agent = await pool.createAgent(agentCfg({ mode: 'agent' }));
408
+ await pool.addInterAgentMessage(agent.id, { content: 'help', sender: 'other', senderName: 'OtherAgent' });
409
+ expect(agent.taskList.tasks).toHaveLength(1);
410
+ expect(agent.taskList.tasks[0].title).toContain('inter-agent');
411
+ });
412
+
413
+ test('throws for non-existent agent', async () => {
414
+ await expect(pool.addInterAgentMessage('nonexistent', { content: 'hi' })).rejects.toThrow('Agent not found');
415
+ });
416
+ });
417
+
418
+ describe('addToolResult', () => {
419
+ test('pushes result with generated ID and timestamps', async () => {
420
+ const agent = await pool.createAgent(agentCfg());
421
+ await pool.addToolResult(agent.id, { toolId: 'terminal', status: 'completed', result: 'ok' });
422
+ expect(agent.messageQueues.toolResults).toHaveLength(1);
423
+ const r = agent.messageQueues.toolResults[0];
424
+ expect(r.toolId).toBe('terminal');
425
+ expect(r.id).toBeDefined();
426
+ expect(r.queuedAt).toBeDefined();
427
+ });
428
+
429
+ test('throws for non-existent agent', async () => {
430
+ await expect(pool.addToolResult('nonexistent', {})).rejects.toThrow('Agent not found');
431
+ });
432
+ });
433
+
434
+ // ─── clearConversation ────────────────────────────────────────────────
435
+ describe('clearConversation', () => {
436
+ test('empties all conversation history, queues, and task list', async () => {
437
+ const agent = await pool.createAgent(agentCfg());
438
+ agent.conversations.full.messages.push({ role: 'user', content: 'old' });
439
+ agent.messageQueues.userMessages.push({ content: 'queued' });
440
+ agent.messageQueues.toolResults.push({ toolId: 'x' });
441
+ agent.messageQueues.interAgentMessages.push({ content: 'inter' });
442
+ agent.taskList.tasks.push({ id: 'task1', title: 'do thing' });
443
+
444
+ const result = await pool.clearConversation(agent.id);
445
+ expect(result.success).toBe(true);
446
+ expect(result.previousMessageCount).toBe(1);
447
+ expect(agent.conversations.full.messages).toEqual([]);
448
+ expect(agent.messageQueues.userMessages).toEqual([]);
449
+ expect(agent.messageQueues.toolResults).toEqual([]);
450
+ expect(agent.messageQueues.interAgentMessages).toEqual([]);
451
+ expect(agent.taskList.tasks).toEqual([]);
452
+ expect(agent.currentTask).toBeNull();
453
+ expect(agent.iterationCount).toBe(0);
454
+ });
455
+
456
+ test('resets model-specific conversations', async () => {
457
+ const agent = await pool.createAgent(agentCfg({ preferredModel: 'model-a' }));
458
+ agent.conversations['model-a'].messages.push({ role: 'user', content: 'msg' });
459
+ await pool.clearConversation(agent.id);
460
+ expect(agent.conversations['model-a'].messages).toEqual([]);
461
+ expect(agent.conversations['model-a'].compactizedMessages).toBeNull();
462
+ });
463
+
464
+ test('throws for non-existent agent', async () => {
465
+ await expect(pool.clearConversation('nonexistent')).rejects.toThrow('Agent not found');
466
+ });
467
+ });
468
+
469
+ // ─── listActiveAgents / getAllAgents ───────────────────────────────────
470
+ describe('listActiveAgents', () => {
471
+ test('returns shaped array of all agents', async () => {
472
+ await pool.createAgent(agentCfg({ name: 'A1' }));
473
+ await pool.createAgent(agentCfg({ name: 'A2' }));
474
+ const list = await pool.listActiveAgents();
475
+ expect(list).toHaveLength(2);
476
+ expect(list[0]).toHaveProperty('id');
477
+ expect(list[0]).toHaveProperty('name');
478
+ expect(list[0]).toHaveProperty('mode');
479
+ expect(list[0]).toHaveProperty('capabilities');
480
+ expect(list[0]).toHaveProperty('isPaused');
481
+ expect(list[0]).toHaveProperty('messageCount');
482
+ });
483
+ });
484
+
485
+ describe('getAllAgents', () => {
486
+ test('returns all agents and auto-resumes expired pauses', async () => {
487
+ const agent = await pool.createAgent(agentCfg());
488
+ agent.status = 'paused';
489
+ agent.pausedUntil = new Date(Date.now() - 1000).toISOString();
490
+ const all = await pool.getAllAgents();
491
+ const found = all.find(a => a.id === agent.id);
492
+ expect(found.status).toBe('active');
493
+ expect(found.pausedUntil).toBeNull();
494
+ });
495
+ });
496
+
497
+ // ─── persistAgentState ────────────────────────────────────────────────
498
+ describe('persistAgentState', () => {
499
+ test('delegates to stateManager with agent object', async () => {
500
+ const agent = await pool.createAgent(agentCfg());
501
+ stateManager.persistAgentState.mockClear();
502
+ await pool.persistAgentState(agent.id);
503
+ expect(stateManager.persistAgentState).toHaveBeenCalledWith(agent);
504
+ });
505
+
506
+ test('throws for non-existent agent', async () => {
507
+ await expect(pool.persistAgentState('nonexistent')).rejects.toThrow('Agent not found');
508
+ });
509
+ });
510
+
511
+ // ─── Private helpers ──────────────────────────────────────────────────
512
+ describe('private helpers', () => {
513
+ test('_generateAgentId sanitizes name', () => {
514
+ const id = pool._generateAgentId('Hello World!');
515
+ expect(id).toMatch(/^agent-hello-world--\d+$/);
516
+ });
517
+
518
+ test('_isAgentPaused returns false for active agent', () => {
519
+ expect(pool._isAgentPaused({ status: 'active', pausedUntil: null })).toBe(false);
520
+ });
521
+
522
+ test('_isAgentPaused returns true for future pause', () => {
523
+ const future = new Date(Date.now() + 60000).toISOString();
524
+ expect(pool._isAgentPaused({ status: 'paused', pausedUntil: future })).toBe(true);
525
+ });
526
+
527
+ test('_isAgentPaused returns false for expired pause', () => {
528
+ const past = new Date(Date.now() - 60000).toISOString();
529
+ expect(pool._isAgentPaused({ status: 'paused', pausedUntil: past })).toBe(false);
530
+ });
531
+
532
+ test('_isPauseExpired returns true when no pausedUntil', () => {
533
+ expect(pool._isPauseExpired({})).toBe(true);
534
+ });
535
+
536
+ test('_isPauseExpired returns false when future pause', () => {
537
+ const future = new Date(Date.now() + 60000).toISOString();
538
+ expect(pool._isPauseExpired({ pausedUntil: future })).toBe(false);
539
+ });
540
+
541
+ test('_getFirstUserMessageSnippet returns null for empty conversations', () => {
542
+ const agent = { conversations: { full: { messages: [] } } };
543
+ expect(pool._getFirstUserMessageSnippet(agent)).toBeNull();
544
+ });
545
+
546
+ test('_getFirstUserMessageSnippet returns snippet for first user message', () => {
547
+ const agent = {
548
+ conversations: { full: { messages: [
549
+ { role: 'assistant', content: 'hi' },
550
+ { role: 'user', content: 'Build me a web app', type: 'consolidated-input' }
551
+ ] } }
552
+ };
553
+ expect(pool._getFirstUserMessageSnippet(agent)).toBe('Build me a web app');
554
+ });
555
+
556
+ test('_getFirstUserMessageSnippet truncates long snippets', () => {
557
+ const longMsg = 'A'.repeat(200);
558
+ const agent = {
559
+ conversations: { full: { messages: [
560
+ { role: 'user', content: longMsg }
561
+ ] } }
562
+ };
563
+ const snippet = pool._getFirstUserMessageSnippet(agent);
564
+ expect(snippet.length).toBeLessThanOrEqual(120);
565
+ expect(snippet).toContain('...');
566
+ });
567
+
568
+ test('_queueNotification stores notification for agent', () => {
569
+ pool._queueNotification('agent-1', { content: 'test' });
570
+ expect(pool.notificationQueue.has('agent-1')).toBe(true);
571
+ expect(pool.notificationQueue.get('agent-1')).toHaveLength(1);
572
+ });
573
+
574
+ test('_generateAgentDescription includes capabilities', () => {
575
+ const desc = pool._generateAgentDescription({ name: 'Bot', type: 'user-created', capabilities: ['terminal', 'filesystem'] });
576
+ expect(desc).toContain('Bot');
577
+ expect(desc).toContain('terminal');
578
+ });
579
+ });
580
+
581
+ // ─── setters ──────────────────────────────────────────────────────────
582
+ describe('setter methods', () => {
583
+ test('setToolsRegistry stores the registry', () => {
584
+ const registry = { getTool: jest.fn() };
585
+ pool.setToolsRegistry(registry);
586
+ expect(pool.toolsRegistry).toBe(registry);
587
+ });
588
+
589
+ test('setMessageProcessor stores the reference', () => {
590
+ const mp = { processMessage: jest.fn() };
591
+ pool.setMessageProcessor(mp);
592
+ expect(pool.messageProcessor).toBe(mp);
593
+ });
594
+
595
+ test('setScheduler stores the scheduler reference', () => {
596
+ const sched = { addAgent: jest.fn() };
597
+ pool.setScheduler(sched);
598
+ expect(pool.scheduler).toBe(sched);
599
+ });
600
+ });
601
+ });