@vibescope/mcp-server 0.2.5 → 0.2.6

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 (82) hide show
  1. package/CHANGELOG.md +84 -84
  2. package/README.md +194 -194
  3. package/dist/cli.js +26 -26
  4. package/dist/handlers/tool-docs.js +828 -828
  5. package/dist/index.js +73 -73
  6. package/dist/templates/agent-guidelines.js +185 -185
  7. package/dist/token-tracking.js +4 -2
  8. package/dist/tools.js +65 -65
  9. package/dist/utils.js +11 -11
  10. package/docs/TOOLS.md +2053 -2053
  11. package/package.json +1 -1
  12. package/scripts/generate-docs.ts +212 -212
  13. package/scripts/version-bump.ts +203 -203
  14. package/src/api-client.test.ts +723 -723
  15. package/src/api-client.ts +2499 -2499
  16. package/src/cli.ts +212 -212
  17. package/src/handlers/__test-setup__.ts +236 -236
  18. package/src/handlers/__test-utils__.ts +87 -87
  19. package/src/handlers/blockers.test.ts +468 -468
  20. package/src/handlers/blockers.ts +163 -163
  21. package/src/handlers/bodies-of-work.test.ts +704 -704
  22. package/src/handlers/bodies-of-work.ts +526 -526
  23. package/src/handlers/connectors.test.ts +834 -834
  24. package/src/handlers/connectors.ts +229 -229
  25. package/src/handlers/cost.test.ts +462 -462
  26. package/src/handlers/cost.ts +285 -285
  27. package/src/handlers/decisions.test.ts +382 -382
  28. package/src/handlers/decisions.ts +153 -153
  29. package/src/handlers/deployment.test.ts +551 -551
  30. package/src/handlers/deployment.ts +541 -541
  31. package/src/handlers/discovery.test.ts +206 -206
  32. package/src/handlers/discovery.ts +390 -390
  33. package/src/handlers/fallback.test.ts +537 -537
  34. package/src/handlers/fallback.ts +194 -194
  35. package/src/handlers/file-checkouts.test.ts +750 -750
  36. package/src/handlers/file-checkouts.ts +185 -185
  37. package/src/handlers/findings.test.ts +633 -633
  38. package/src/handlers/findings.ts +239 -239
  39. package/src/handlers/git-issues.test.ts +631 -631
  40. package/src/handlers/git-issues.ts +136 -136
  41. package/src/handlers/ideas.test.ts +644 -644
  42. package/src/handlers/ideas.ts +207 -207
  43. package/src/handlers/index.ts +84 -84
  44. package/src/handlers/milestones.test.ts +475 -475
  45. package/src/handlers/milestones.ts +180 -180
  46. package/src/handlers/organizations.test.ts +826 -826
  47. package/src/handlers/organizations.ts +315 -315
  48. package/src/handlers/progress.test.ts +269 -269
  49. package/src/handlers/progress.ts +77 -77
  50. package/src/handlers/project.test.ts +546 -546
  51. package/src/handlers/project.ts +239 -239
  52. package/src/handlers/requests.test.ts +303 -303
  53. package/src/handlers/requests.ts +99 -99
  54. package/src/handlers/roles.test.ts +303 -303
  55. package/src/handlers/roles.ts +226 -226
  56. package/src/handlers/session.test.ts +875 -875
  57. package/src/handlers/session.ts +738 -738
  58. package/src/handlers/sprints.test.ts +732 -732
  59. package/src/handlers/sprints.ts +537 -537
  60. package/src/handlers/tasks.test.ts +907 -907
  61. package/src/handlers/tasks.ts +945 -945
  62. package/src/handlers/tool-categories.test.ts +66 -66
  63. package/src/handlers/tool-docs.ts +1096 -1096
  64. package/src/handlers/types.test.ts +259 -259
  65. package/src/handlers/types.ts +175 -175
  66. package/src/handlers/validation.test.ts +582 -582
  67. package/src/handlers/validation.ts +97 -97
  68. package/src/index.ts +792 -792
  69. package/src/setup.test.ts +233 -231
  70. package/src/setup.ts +370 -370
  71. package/src/templates/agent-guidelines.ts +210 -210
  72. package/src/token-tracking.test.ts +463 -453
  73. package/src/token-tracking.ts +166 -164
  74. package/src/tools.ts +3562 -3562
  75. package/src/utils.test.ts +683 -683
  76. package/src/utils.ts +436 -436
  77. package/src/validators.test.ts +223 -223
  78. package/src/validators.ts +249 -249
  79. package/tsconfig.json +16 -16
  80. package/vitest.config.ts +14 -14
  81. package/dist/knowledge.d.ts +0 -6
  82. package/dist/knowledge.js +0 -218
@@ -1,875 +1,875 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import {
3
- startWorkSession,
4
- heartbeat,
5
- endWorkSession,
6
- getHelp,
7
- getTokenUsage,
8
- reportTokenUsage,
9
- } from './session.js';
10
- import { createMockContext } from './__test-utils__.js';
11
- import { mockApiClient } from './__test-setup__.js';
12
-
13
- // ============================================================================
14
- // heartbeat Tests
15
- // ============================================================================
16
-
17
- describe('heartbeat', () => {
18
- beforeEach(() => vi.clearAllMocks());
19
-
20
- it('should record heartbeat successfully', async () => {
21
- const ctx = createMockContext();
22
- mockApiClient.heartbeat.mockResolvedValue({
23
- ok: true,
24
- data: { timestamp: '2026-01-14T10:00:00Z' },
25
- });
26
- mockApiClient.syncSession.mockResolvedValue({ ok: true });
27
-
28
- const result = await heartbeat({}, ctx);
29
-
30
- expect(result.result).toMatchObject({
31
- success: true,
32
- session_id: 'session-123',
33
- });
34
- expect(result.result).toHaveProperty('timestamp');
35
- expect(mockApiClient.heartbeat).toHaveBeenCalledWith('session-123', expect.objectContaining({ current_worktree_path: undefined }));
36
- });
37
-
38
- it('should use provided session_id over current session', async () => {
39
- const ctx = createMockContext();
40
- mockApiClient.heartbeat.mockResolvedValue({
41
- ok: true,
42
- data: { timestamp: '2026-01-14T10:00:00Z' },
43
- });
44
- mockApiClient.syncSession.mockResolvedValue({ ok: true });
45
-
46
- const result = await heartbeat({ session_id: 'other-session-456' }, ctx);
47
-
48
- expect(result.result).toMatchObject({
49
- success: true,
50
- session_id: 'other-session-456',
51
- });
52
- expect(mockApiClient.heartbeat).toHaveBeenCalledWith('other-session-456', expect.objectContaining({ current_worktree_path: undefined }));
53
- });
54
-
55
- it('should pass worktree_path to API', async () => {
56
- const ctx = createMockContext();
57
- mockApiClient.heartbeat.mockResolvedValue({
58
- ok: true,
59
- data: { timestamp: '2026-01-14T10:00:00Z' },
60
- });
61
- mockApiClient.syncSession.mockResolvedValue({ ok: true });
62
-
63
- await heartbeat({ current_worktree_path: '../project-task-abc123' }, ctx);
64
-
65
- expect(mockApiClient.heartbeat).toHaveBeenCalledWith('session-123', expect.objectContaining({ current_worktree_path: '../project-task-abc123' }));
66
- });
67
-
68
- it('should return error when no active session', async () => {
69
- const ctx = createMockContext({ sessionId: null });
70
-
71
- const result = await heartbeat({}, ctx);
72
-
73
- expect(result.result).toMatchObject({
74
- error: 'No active session. Call start_work_session first.',
75
- });
76
- });
77
-
78
- it('should sync session with token usage', async () => {
79
- const ctx = createMockContext({
80
- tokenUsage: {
81
- callCount: 10,
82
- totalTokens: 5000,
83
- byTool: {
84
- get_task: { calls: 3, tokens: 1500 },
85
- update_task: { calls: 4, tokens: 2000 },
86
- complete_task: { calls: 3, tokens: 1500 },
87
- },
88
- byModel: {},
89
- currentModel: null,
90
- },
91
- });
92
- mockApiClient.heartbeat.mockResolvedValue({
93
- ok: true,
94
- data: { timestamp: '2026-01-14T10:00:00Z' },
95
- });
96
- mockApiClient.syncSession.mockResolvedValue({ ok: true });
97
-
98
- await heartbeat({}, ctx);
99
-
100
- expect(mockApiClient.syncSession).toHaveBeenCalledWith(
101
- 'session-123',
102
- expect.objectContaining({
103
- total_tokens: 5000,
104
- })
105
- );
106
- });
107
- });
108
-
109
- // ============================================================================
110
- // getHelp Tests
111
- // ============================================================================
112
-
113
- describe('getHelp', () => {
114
- beforeEach(() => vi.clearAllMocks());
115
-
116
- it('should return help content for valid topic', async () => {
117
- const ctx = createMockContext();
118
- mockApiClient.getHelpTopic.mockResolvedValue({
119
- ok: true,
120
- data: { slug: 'tasks', title: 'Task Workflow', content: '# Task Workflow\nTest content' },
121
- });
122
-
123
- const result = await getHelp({ topic: 'tasks' }, ctx);
124
-
125
- expect(result.result).toHaveProperty('topic', 'tasks');
126
- expect(result.result).toHaveProperty('content');
127
- });
128
-
129
- it('should return getting_started help', async () => {
130
- const ctx = createMockContext();
131
- mockApiClient.getHelpTopic.mockResolvedValue({
132
- ok: true,
133
- data: { slug: 'getting_started', title: 'Getting Started', content: '# Getting Started\nTest content' },
134
- });
135
-
136
- const result = await getHelp({ topic: 'getting_started' }, ctx);
137
-
138
- expect(result.result).toHaveProperty('topic', 'getting_started');
139
- expect(result.result).toHaveProperty('content');
140
- });
141
-
142
- it('should return error for unknown topic', async () => {
143
- const ctx = createMockContext();
144
- mockApiClient.getHelpTopic.mockResolvedValue({ ok: true, data: null });
145
- mockApiClient.getHelpTopics.mockResolvedValue({
146
- ok: true,
147
- data: [{ slug: 'tasks', title: 'Tasks' }, { slug: 'getting_started', title: 'Getting Started' }],
148
- });
149
-
150
- const result = await getHelp({ topic: 'unknown_topic' }, ctx);
151
-
152
- expect(result.result).toMatchObject({
153
- error: 'Unknown topic: unknown_topic',
154
- });
155
- expect(result.result).toHaveProperty('available');
156
- });
157
-
158
- it('should list available topics for unknown topic', async () => {
159
- const ctx = createMockContext();
160
- mockApiClient.getHelpTopic.mockResolvedValue({ ok: true, data: null });
161
- mockApiClient.getHelpTopics.mockResolvedValue({
162
- ok: true,
163
- data: [
164
- { slug: 'tasks', title: 'Tasks' },
165
- { slug: 'getting_started', title: 'Getting Started' },
166
- { slug: 'validation', title: 'Validation' },
167
- ],
168
- });
169
-
170
- const result = await getHelp({ topic: 'nonexistent' }, ctx);
171
-
172
- const available = (result.result as { available: string[] }).available;
173
- expect(Array.isArray(available)).toBe(true);
174
- expect(available.length).toBeGreaterThan(0);
175
- });
176
- });
177
-
178
- // ============================================================================
179
- // getTokenUsage Tests
180
- // ============================================================================
181
-
182
- describe('getTokenUsage', () => {
183
- beforeEach(() => vi.clearAllMocks());
184
-
185
- it('should return token usage stats', async () => {
186
- const ctx = createMockContext();
187
-
188
- const result = await getTokenUsage({}, ctx);
189
-
190
- expect(result.result).toHaveProperty('session');
191
- expect(result.result).toHaveProperty('top_tools');
192
- expect(result.result).toHaveProperty('note');
193
- });
194
-
195
- it('should return correct session stats', async () => {
196
- const ctx = createMockContext({
197
- tokenUsage: {
198
- callCount: 10,
199
- totalTokens: 5000,
200
- byTool: {},
201
- byModel: {},
202
- currentModel: null,
203
- },
204
- });
205
-
206
- const result = await getTokenUsage({}, ctx);
207
- const session = (result.result as { session: { calls: number; tokens: number; avg_per_call: number } }).session;
208
-
209
- expect(session.calls).toBe(10);
210
- expect(session.tokens).toBe(5000);
211
- expect(session.avg_per_call).toBe(500);
212
- });
213
-
214
- it('should return top tools sorted by tokens', async () => {
215
- const ctx = createMockContext({
216
- tokenUsage: {
217
- callCount: 10,
218
- totalTokens: 5000,
219
- byTool: {
220
- tool_a: { calls: 2, tokens: 1000 },
221
- tool_b: { calls: 5, tokens: 3000 },
222
- tool_c: { calls: 3, tokens: 1000 },
223
- },
224
- byModel: {},
225
- currentModel: null,
226
- },
227
- });
228
-
229
- const result = await getTokenUsage({}, ctx);
230
- const topTools = (result.result as { top_tools: Array<{ tool: string; tokens: number }> }).top_tools;
231
-
232
- // Should be sorted by tokens descending
233
- expect(topTools[0].tool).toBe('tool_b');
234
- expect(topTools[0].tokens).toBe(3000);
235
- });
236
-
237
- it('should handle zero calls gracefully', async () => {
238
- const ctx = createMockContext({
239
- tokenUsage: {
240
- callCount: 0,
241
- totalTokens: 0,
242
- byTool: {},
243
- byModel: {},
244
- currentModel: null,
245
- },
246
- });
247
-
248
- const result = await getTokenUsage({}, ctx);
249
- const session = (result.result as { session: { calls: number; tokens: number; avg_per_call: number } }).session;
250
-
251
- expect(session.calls).toBe(0);
252
- expect(session.tokens).toBe(0);
253
- expect(session.avg_per_call).toBe(0);
254
- });
255
-
256
- it('should limit top_tools to 5', async () => {
257
- const ctx = createMockContext({
258
- tokenUsage: {
259
- callCount: 20,
260
- totalTokens: 10000,
261
- byTool: {
262
- tool_1: { calls: 1, tokens: 100 },
263
- tool_2: { calls: 2, tokens: 200 },
264
- tool_3: { calls: 3, tokens: 300 },
265
- tool_4: { calls: 4, tokens: 400 },
266
- tool_5: { calls: 5, tokens: 500 },
267
- tool_6: { calls: 6, tokens: 600 },
268
- tool_7: { calls: 7, tokens: 700 },
269
- },
270
- byModel: {},
271
- currentModel: null,
272
- },
273
- });
274
-
275
- const result = await getTokenUsage({}, ctx);
276
- const topTools = (result.result as { top_tools: Array<{ tool: string }> }).top_tools;
277
-
278
- expect(topTools.length).toBe(5);
279
- });
280
- });
281
-
282
- // ============================================================================
283
- // endWorkSession Tests
284
- // ============================================================================
285
-
286
- describe('endWorkSession', () => {
287
- beforeEach(() => vi.clearAllMocks());
288
-
289
- it('should handle no active session gracefully', async () => {
290
- const ctx = createMockContext({ sessionId: null });
291
-
292
- const result = await endWorkSession({}, ctx);
293
-
294
- expect(result.result).toMatchObject({
295
- success: true,
296
- message: 'No active session to end',
297
- });
298
- });
299
-
300
- it('should use provided session_id over current session', async () => {
301
- const ctx = createMockContext();
302
- mockApiClient.syncSession.mockResolvedValue({ ok: true });
303
- mockApiClient.endSession.mockResolvedValue({
304
- ok: true,
305
- data: {
306
- session_summary: {
307
- agent_name: 'Wave',
308
- tasks_completed_this_session: 3,
309
- tasks_awaiting_validation: 1,
310
- tasks_released: 0,
311
- },
312
- },
313
- });
314
-
315
- const result = await endWorkSession({ session_id: 'other-session-456' }, ctx);
316
-
317
- expect(result.result).toHaveProperty('ended_session_id', 'other-session-456');
318
- expect(mockApiClient.endSession).toHaveBeenCalledWith('other-session-456');
319
- });
320
-
321
- it('should call updateSession to clear current session', async () => {
322
- const ctx = createMockContext();
323
- mockApiClient.syncSession.mockResolvedValue({ ok: true });
324
- mockApiClient.endSession.mockResolvedValue({
325
- ok: true,
326
- data: {
327
- session_summary: {
328
- agent_name: 'Wave',
329
- tasks_completed_this_session: 0,
330
- tasks_awaiting_validation: 0,
331
- tasks_released: 0,
332
- },
333
- },
334
- });
335
-
336
- await endWorkSession({}, ctx);
337
-
338
- expect(ctx.updateSession).toHaveBeenCalledWith({ currentSessionId: null });
339
- });
340
-
341
- it('should return session summary', async () => {
342
- const ctx = createMockContext();
343
- mockApiClient.syncSession.mockResolvedValue({ ok: true });
344
- mockApiClient.endSession.mockResolvedValue({
345
- ok: true,
346
- data: {
347
- session_summary: {
348
- agent_name: 'Wave',
349
- tasks_completed_this_session: 2,
350
- tasks_awaiting_validation: 1,
351
- tasks_released: 0,
352
- },
353
- },
354
- });
355
-
356
- const result = await endWorkSession({}, ctx);
357
-
358
- expect(result.result).toHaveProperty('session_summary');
359
- const summary = (result.result as { session_summary: { agent_name: string; token_usage: unknown } }).session_summary;
360
- expect(summary.agent_name).toBe('Wave');
361
- expect(summary).toHaveProperty('token_usage');
362
- });
363
-
364
- it('should not call updateSession when ending a different session', async () => {
365
- const ctx = createMockContext({ sessionId: 'session-123' });
366
- mockApiClient.syncSession.mockResolvedValue({ ok: true });
367
- mockApiClient.endSession.mockResolvedValue({
368
- ok: true,
369
- data: {
370
- session_summary: {
371
- agent_name: 'Wave',
372
- tasks_completed_this_session: 0,
373
- tasks_awaiting_validation: 0,
374
- tasks_released: 0,
375
- },
376
- },
377
- });
378
-
379
- await endWorkSession({ session_id: 'different-session' }, ctx);
380
-
381
- // Should NOT clear the current session since we're ending a different one
382
- expect(ctx.updateSession).not.toHaveBeenCalledWith({ currentSessionId: null });
383
- });
384
- });
385
-
386
- // ============================================================================
387
- // startWorkSession Tests
388
- // ============================================================================
389
-
390
- describe('startWorkSession', () => {
391
- beforeEach(() => {
392
- vi.clearAllMocks();
393
- });
394
-
395
- it('should return error when project_id and git_url are both missing', async () => {
396
- const ctx = createMockContext({ sessionId: null });
397
-
398
- const result = await startWorkSession({}, ctx);
399
-
400
- expect(result.result).toMatchObject({
401
- error: 'Please provide project_id or git_url to start a session',
402
- });
403
- });
404
-
405
- it('should return project_not_found when no project matches', async () => {
406
- const ctx = createMockContext({ sessionId: null });
407
- mockApiClient.startSession.mockResolvedValue({
408
- ok: true,
409
- data: {
410
- session_started: false,
411
- project_not_found: true,
412
- message: 'No project found',
413
- suggestion: {
414
- action: 'create_project',
415
- example: 'create_project(name: "repo")',
416
- note: 'After creating the project, call start_work_session again.',
417
- },
418
- },
419
- });
420
-
421
- const result = await startWorkSession({ git_url: 'https://github.com/test/repo' }, ctx);
422
-
423
- expect(result.result).toMatchObject({
424
- session_started: false,
425
- project_not_found: true,
426
- });
427
- expect(result.result).toHaveProperty('suggestion');
428
- });
429
-
430
- it('should reuse existing persona when session already has one', async () => {
431
- const ctx = createMockContext({ sessionId: null });
432
- mockApiClient.startSession.mockResolvedValue({
433
- ok: true,
434
- data: {
435
- session_started: true,
436
- session_id: 'existing-session-123',
437
- persona: 'Pixel',
438
- role: 'developer',
439
- project: { id: 'project-123', name: 'Test Project' },
440
- },
441
- });
442
-
443
- const result = await startWorkSession({ project_id: 'project-123' }, ctx);
444
-
445
- expect(result.result).toMatchObject({
446
- session_started: true,
447
- persona: 'Pixel',
448
- });
449
- });
450
-
451
- it('should call updateSession with session ID and persona', async () => {
452
- const ctx = createMockContext({ sessionId: null });
453
- mockApiClient.startSession.mockResolvedValue({
454
- ok: true,
455
- data: {
456
- session_started: true,
457
- session_id: 'new-session-123',
458
- persona: 'Wave',
459
- role: 'developer',
460
- project: { id: 'project-123', name: 'Test Project' },
461
- },
462
- });
463
-
464
- await startWorkSession({ project_id: 'project-123' }, ctx);
465
-
466
- expect(ctx.updateSession).toHaveBeenCalledWith(
467
- expect.objectContaining({
468
- currentSessionId: 'new-session-123',
469
- currentPersona: 'Wave',
470
- })
471
- );
472
- });
473
-
474
- it('should return lite mode response by default', async () => {
475
- const ctx = createMockContext({ sessionId: null });
476
- mockApiClient.startSession.mockResolvedValue({
477
- ok: true,
478
- data: {
479
- session_started: true,
480
- session_id: 'new-session-123',
481
- persona: 'Wave',
482
- role: 'developer',
483
- project: { id: 'project-123', name: 'Test Project' },
484
- directive: 'ACTION_REQUIRED: Start working immediately.',
485
- },
486
- });
487
-
488
- const result = await startWorkSession({ project_id: 'project-123' }, ctx);
489
-
490
- expect(result.result).toMatchObject({
491
- session_started: true,
492
- });
493
- expect(result.result).toHaveProperty('project');
494
- expect(result.result).toHaveProperty('directive');
495
- });
496
-
497
- it('should return error when API call fails', async () => {
498
- const ctx = createMockContext({ sessionId: null });
499
- mockApiClient.startSession.mockResolvedValue({
500
- ok: false,
501
- error: 'Internal server error',
502
- });
503
-
504
- const result = await startWorkSession({ project_id: 'project-123' }, ctx);
505
-
506
- expect(result.result).toMatchObject({
507
- error: 'Internal server error',
508
- });
509
- });
510
-
511
- it('should include next_task when available', async () => {
512
- const ctx = createMockContext({ sessionId: null });
513
- mockApiClient.startSession.mockResolvedValue({
514
- ok: true,
515
- data: {
516
- session_started: true,
517
- session_id: 'new-session-123',
518
- persona: 'Wave',
519
- role: 'developer',
520
- project: { id: 'project-123', name: 'Test Project' },
521
- next_task: { id: 'task-1', title: 'Fix bug', priority: 1 },
522
- },
523
- });
524
-
525
- const result = await startWorkSession({ project_id: 'project-123' }, ctx);
526
-
527
- expect(result.result).toHaveProperty('next_task');
528
- expect((result.result as { next_task: { id: string } }).next_task.id).toBe('task-1');
529
- });
530
-
531
- it('should include pending_requests when available in full mode', async () => {
532
- const ctx = createMockContext({ sessionId: null });
533
- const mockRequests = [
534
- { id: 'req-1', request_type: 'question', message: 'What is the status?', created_at: '2026-01-14T10:00:00Z' },
535
- { id: 'req-2', request_type: 'instruction', message: 'Please prioritize task X', created_at: '2026-01-14T11:00:00Z' },
536
- ];
537
- mockApiClient.startSession.mockResolvedValue({
538
- ok: true,
539
- data: {
540
- session_started: true,
541
- session_id: 'new-session-123',
542
- persona: 'Wave',
543
- role: 'developer',
544
- project: { id: 'project-123', name: 'Test Project' },
545
- pending_requests: mockRequests,
546
- },
547
- });
548
-
549
- const result = await startWorkSession({ project_id: 'project-123', mode: 'full' }, ctx);
550
-
551
- expect(result.result).toHaveProperty('pending_requests');
552
- expect(result.result).toHaveProperty('pending_requests_count', 2);
553
- const pendingRequests = (result.result as { pending_requests: typeof mockRequests }).pending_requests;
554
- expect(pendingRequests.length).toBe(2);
555
- expect(pendingRequests[0].request_type).toBe('question');
556
- });
557
-
558
- it('should not include pending_requests when empty', async () => {
559
- const ctx = createMockContext({ sessionId: null });
560
- mockApiClient.startSession.mockResolvedValue({
561
- ok: true,
562
- data: {
563
- session_started: true,
564
- session_id: 'new-session-123',
565
- persona: 'Wave',
566
- role: 'developer',
567
- project: { id: 'project-123', name: 'Test Project' },
568
- pending_requests: [],
569
- },
570
- });
571
-
572
- const result = await startWorkSession({ project_id: 'project-123', mode: 'full' }, ctx);
573
-
574
- expect(result.result).not.toHaveProperty('pending_requests');
575
- expect(result.result).not.toHaveProperty('pending_requests_count');
576
- });
577
-
578
- it('should surface awaiting_validation tasks when present', async () => {
579
- const ctx = createMockContext({ sessionId: null });
580
- const mockValidationTasks = [
581
- { id: 'task-1', title: 'Implement login' },
582
- { id: 'task-2', title: 'Add tests' },
583
- ];
584
- mockApiClient.startSession.mockResolvedValue({
585
- ok: true,
586
- data: {
587
- session_started: true,
588
- session_id: 'new-session-123',
589
- persona: 'Wave',
590
- role: 'developer',
591
- project: { id: 'project-123', name: 'Test Project' },
592
- awaiting_validation: mockValidationTasks,
593
- validation_count: 2,
594
- validation_priority: 'VALIDATE FIRST: 2 task(s) need review before starting new work.',
595
- directive: 'VALIDATE FIRST: 2 task(s) need review before starting new work. Call claim_validation(task_id) to start reviewing.',
596
- },
597
- });
598
-
599
- const result = await startWorkSession({ project_id: 'project-123' }, ctx);
600
-
601
- expect(result.result).toHaveProperty('awaiting_validation');
602
- expect(result.result).toHaveProperty('validation_count', 2);
603
- expect(result.result).toHaveProperty('validation_priority');
604
- const awaitingValidation = (result.result as { awaiting_validation: typeof mockValidationTasks }).awaiting_validation;
605
- expect(awaitingValidation.length).toBe(2);
606
- expect(awaitingValidation[0].id).toBe('task-1');
607
- });
608
-
609
- it('should include next_action when validation tasks are present', async () => {
610
- const ctx = createMockContext({ sessionId: null });
611
- mockApiClient.startSession.mockResolvedValue({
612
- ok: true,
613
- data: {
614
- session_started: true,
615
- session_id: 'new-session-123',
616
- persona: 'Wave',
617
- role: 'developer',
618
- project: { id: 'project-123', name: 'Test Project' },
619
- awaiting_validation: [{ id: 'task-abc', title: 'Fix bug' }],
620
- validation_count: 1,
621
- next_action: 'claim_validation(task_id: "task-abc")',
622
- },
623
- });
624
-
625
- const result = await startWorkSession({ project_id: 'project-123' }, ctx);
626
-
627
- expect(result.result).toHaveProperty('next_action');
628
- expect((result.result as { next_action: string }).next_action).toContain('task-abc');
629
- });
630
- });
631
-
632
- // ============================================================================
633
- // reportTokenUsage Tests
634
- // ============================================================================
635
-
636
- describe('reportTokenUsage', () => {
637
- beforeEach(() => vi.clearAllMocks());
638
-
639
- it('should report token usage successfully with session', async () => {
640
- const ctx = createMockContext();
641
- mockApiClient.reportTokenUsage.mockResolvedValue({
642
- ok: true,
643
- data: {
644
- success: true,
645
- reported: {
646
- session_id: 'session-123',
647
- model: 'sonnet',
648
- input_tokens: 1000,
649
- output_tokens: 500,
650
- total_tokens: 1500,
651
- estimated_cost_usd: 0.0105,
652
- },
653
- task_attributed: true,
654
- task_id: 'task-123',
655
- },
656
- });
657
-
658
- const result = await reportTokenUsage(
659
- { input_tokens: 1000, output_tokens: 500, model: 'sonnet' },
660
- ctx
661
- );
662
-
663
- expect(result.result).toMatchObject({
664
- success: true,
665
- task_attributed: true,
666
- task_id: 'task-123',
667
- });
668
- expect(result.result).toHaveProperty('reported');
669
- expect(mockApiClient.reportTokenUsage).toHaveBeenCalledWith('session-123', {
670
- input_tokens: 1000,
671
- output_tokens: 500,
672
- model: 'sonnet',
673
- });
674
- });
675
-
676
- it('should default to sonnet model when not specified', async () => {
677
- const ctx = createMockContext();
678
- mockApiClient.reportTokenUsage.mockResolvedValue({
679
- ok: true,
680
- data: {
681
- success: true,
682
- reported: {
683
- session_id: 'session-123',
684
- model: 'sonnet',
685
- input_tokens: 1000,
686
- output_tokens: 500,
687
- total_tokens: 1500,
688
- estimated_cost_usd: 0.0105,
689
- },
690
- task_attributed: false,
691
- },
692
- });
693
-
694
- await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
695
-
696
- expect(mockApiClient.reportTokenUsage).toHaveBeenCalledWith('session-123', {
697
- input_tokens: 1000,
698
- output_tokens: 500,
699
- model: 'sonnet',
700
- });
701
- });
702
-
703
- it('should use session currentModel if available', async () => {
704
- const ctx = createMockContext({
705
- tokenUsage: {
706
- callCount: 0,
707
- totalTokens: 0,
708
- byTool: {},
709
- byModel: {},
710
- currentModel: 'opus',
711
- },
712
- });
713
- mockApiClient.reportTokenUsage.mockResolvedValue({
714
- ok: true,
715
- data: {
716
- success: true,
717
- reported: {
718
- session_id: 'session-123',
719
- model: 'opus',
720
- input_tokens: 1000,
721
- output_tokens: 500,
722
- total_tokens: 1500,
723
- estimated_cost_usd: 0.0525,
724
- },
725
- task_attributed: false,
726
- },
727
- });
728
-
729
- await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
730
-
731
- expect(mockApiClient.reportTokenUsage).toHaveBeenCalledWith('session-123', {
732
- input_tokens: 1000,
733
- output_tokens: 500,
734
- model: 'opus',
735
- });
736
- });
737
-
738
- it('should return error for negative token counts', async () => {
739
- const ctx = createMockContext();
740
-
741
- const result = await reportTokenUsage({ input_tokens: -100, output_tokens: 500 }, ctx);
742
-
743
- expect(result.result).toMatchObject({
744
- error: 'Token counts must be non-negative',
745
- });
746
- expect(mockApiClient.reportTokenUsage).not.toHaveBeenCalled();
747
- });
748
-
749
- it('should handle local-only reporting when no session', async () => {
750
- const ctx = createMockContext({ sessionId: null });
751
-
752
- const result = await reportTokenUsage(
753
- { input_tokens: 1000, output_tokens: 500, model: 'haiku' },
754
- ctx
755
- );
756
-
757
- expect(result.result).toMatchObject({
758
- success: true,
759
- });
760
- expect(result.result).toHaveProperty('reported');
761
- const reported = (result.result as { reported: { model: string } }).reported;
762
- expect(reported.model).toBe('haiku');
763
- expect(result.result).toHaveProperty('note');
764
- expect(mockApiClient.reportTokenUsage).not.toHaveBeenCalled();
765
- });
766
-
767
- it('should update local token tracking', async () => {
768
- const ctx = createMockContext({
769
- tokenUsage: {
770
- callCount: 5,
771
- totalTokens: 2500,
772
- byTool: {},
773
- byModel: { sonnet: { input: 1000, output: 500 } },
774
- currentModel: null,
775
- },
776
- });
777
- mockApiClient.reportTokenUsage.mockResolvedValue({
778
- ok: true,
779
- data: {
780
- success: true,
781
- reported: {
782
- session_id: 'session-123',
783
- model: 'sonnet',
784
- input_tokens: 1000,
785
- output_tokens: 500,
786
- total_tokens: 1500,
787
- estimated_cost_usd: 0.0105,
788
- },
789
- task_attributed: false,
790
- },
791
- });
792
-
793
- await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
794
-
795
- expect(ctx.updateSession).toHaveBeenCalledWith(
796
- expect.objectContaining({
797
- tokenUsage: expect.objectContaining({
798
- callCount: 6,
799
- totalTokens: 4000,
800
- byModel: { sonnet: { input: 2000, output: 1000 } },
801
- }),
802
- })
803
- );
804
- });
805
-
806
- it('should handle backend failure gracefully', async () => {
807
- const ctx = createMockContext();
808
- mockApiClient.reportTokenUsage.mockResolvedValue({
809
- ok: false,
810
- error: 'Server error',
811
- });
812
-
813
- const result = await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
814
-
815
- // Should still succeed with local calculation
816
- expect(result.result).toMatchObject({
817
- success: true,
818
- });
819
- expect(result.result).toHaveProperty('warning');
820
- });
821
-
822
- it('should indicate when task attribution succeeds', async () => {
823
- const ctx = createMockContext();
824
- mockApiClient.reportTokenUsage.mockResolvedValue({
825
- ok: true,
826
- data: {
827
- success: true,
828
- reported: {
829
- session_id: 'session-123',
830
- model: 'sonnet',
831
- input_tokens: 1000,
832
- output_tokens: 500,
833
- total_tokens: 1500,
834
- estimated_cost_usd: 0.0105,
835
- },
836
- task_attributed: true,
837
- task_id: 'task-abc123',
838
- },
839
- });
840
-
841
- const result = await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
842
-
843
- expect(result.result).toMatchObject({
844
- task_attributed: true,
845
- task_id: 'task-abc123',
846
- });
847
- expect((result.result as { note: string }).note).toContain('attributed to current task');
848
- });
849
-
850
- it('should indicate when no task to attribute to', async () => {
851
- const ctx = createMockContext();
852
- mockApiClient.reportTokenUsage.mockResolvedValue({
853
- ok: true,
854
- data: {
855
- success: true,
856
- reported: {
857
- session_id: 'session-123',
858
- model: 'sonnet',
859
- input_tokens: 1000,
860
- output_tokens: 500,
861
- total_tokens: 1500,
862
- estimated_cost_usd: 0.0105,
863
- },
864
- task_attributed: false,
865
- },
866
- });
867
-
868
- const result = await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
869
-
870
- expect(result.result).toMatchObject({
871
- task_attributed: false,
872
- });
873
- expect((result.result as { note: string }).note).toContain('No active task');
874
- });
875
- });
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import {
3
+ startWorkSession,
4
+ heartbeat,
5
+ endWorkSession,
6
+ getHelp,
7
+ getTokenUsage,
8
+ reportTokenUsage,
9
+ } from './session.js';
10
+ import { createMockContext } from './__test-utils__.js';
11
+ import { mockApiClient } from './__test-setup__.js';
12
+
13
+ // ============================================================================
14
+ // heartbeat Tests
15
+ // ============================================================================
16
+
17
+ describe('heartbeat', () => {
18
+ beforeEach(() => vi.clearAllMocks());
19
+
20
+ it('should record heartbeat successfully', async () => {
21
+ const ctx = createMockContext();
22
+ mockApiClient.heartbeat.mockResolvedValue({
23
+ ok: true,
24
+ data: { timestamp: '2026-01-14T10:00:00Z' },
25
+ });
26
+ mockApiClient.syncSession.mockResolvedValue({ ok: true });
27
+
28
+ const result = await heartbeat({}, ctx);
29
+
30
+ expect(result.result).toMatchObject({
31
+ success: true,
32
+ session_id: 'session-123',
33
+ });
34
+ expect(result.result).toHaveProperty('timestamp');
35
+ expect(mockApiClient.heartbeat).toHaveBeenCalledWith('session-123', expect.objectContaining({ current_worktree_path: undefined }));
36
+ });
37
+
38
+ it('should use provided session_id over current session', async () => {
39
+ const ctx = createMockContext();
40
+ mockApiClient.heartbeat.mockResolvedValue({
41
+ ok: true,
42
+ data: { timestamp: '2026-01-14T10:00:00Z' },
43
+ });
44
+ mockApiClient.syncSession.mockResolvedValue({ ok: true });
45
+
46
+ const result = await heartbeat({ session_id: 'other-session-456' }, ctx);
47
+
48
+ expect(result.result).toMatchObject({
49
+ success: true,
50
+ session_id: 'other-session-456',
51
+ });
52
+ expect(mockApiClient.heartbeat).toHaveBeenCalledWith('other-session-456', expect.objectContaining({ current_worktree_path: undefined }));
53
+ });
54
+
55
+ it('should pass worktree_path to API', async () => {
56
+ const ctx = createMockContext();
57
+ mockApiClient.heartbeat.mockResolvedValue({
58
+ ok: true,
59
+ data: { timestamp: '2026-01-14T10:00:00Z' },
60
+ });
61
+ mockApiClient.syncSession.mockResolvedValue({ ok: true });
62
+
63
+ await heartbeat({ current_worktree_path: '../project-task-abc123' }, ctx);
64
+
65
+ expect(mockApiClient.heartbeat).toHaveBeenCalledWith('session-123', expect.objectContaining({ current_worktree_path: '../project-task-abc123' }));
66
+ });
67
+
68
+ it('should return error when no active session', async () => {
69
+ const ctx = createMockContext({ sessionId: null });
70
+
71
+ const result = await heartbeat({}, ctx);
72
+
73
+ expect(result.result).toMatchObject({
74
+ error: 'No active session. Call start_work_session first.',
75
+ });
76
+ });
77
+
78
+ it('should sync session with token usage', async () => {
79
+ const ctx = createMockContext({
80
+ tokenUsage: {
81
+ callCount: 10,
82
+ totalTokens: 5000,
83
+ byTool: {
84
+ get_task: { calls: 3, tokens: 1500 },
85
+ update_task: { calls: 4, tokens: 2000 },
86
+ complete_task: { calls: 3, tokens: 1500 },
87
+ },
88
+ byModel: {},
89
+ currentModel: null,
90
+ },
91
+ });
92
+ mockApiClient.heartbeat.mockResolvedValue({
93
+ ok: true,
94
+ data: { timestamp: '2026-01-14T10:00:00Z' },
95
+ });
96
+ mockApiClient.syncSession.mockResolvedValue({ ok: true });
97
+
98
+ await heartbeat({}, ctx);
99
+
100
+ expect(mockApiClient.syncSession).toHaveBeenCalledWith(
101
+ 'session-123',
102
+ expect.objectContaining({
103
+ total_tokens: 5000,
104
+ })
105
+ );
106
+ });
107
+ });
108
+
109
+ // ============================================================================
110
+ // getHelp Tests
111
+ // ============================================================================
112
+
113
+ describe('getHelp', () => {
114
+ beforeEach(() => vi.clearAllMocks());
115
+
116
+ it('should return help content for valid topic', async () => {
117
+ const ctx = createMockContext();
118
+ mockApiClient.getHelpTopic.mockResolvedValue({
119
+ ok: true,
120
+ data: { slug: 'tasks', title: 'Task Workflow', content: '# Task Workflow\nTest content' },
121
+ });
122
+
123
+ const result = await getHelp({ topic: 'tasks' }, ctx);
124
+
125
+ expect(result.result).toHaveProperty('topic', 'tasks');
126
+ expect(result.result).toHaveProperty('content');
127
+ });
128
+
129
+ it('should return getting_started help', async () => {
130
+ const ctx = createMockContext();
131
+ mockApiClient.getHelpTopic.mockResolvedValue({
132
+ ok: true,
133
+ data: { slug: 'getting_started', title: 'Getting Started', content: '# Getting Started\nTest content' },
134
+ });
135
+
136
+ const result = await getHelp({ topic: 'getting_started' }, ctx);
137
+
138
+ expect(result.result).toHaveProperty('topic', 'getting_started');
139
+ expect(result.result).toHaveProperty('content');
140
+ });
141
+
142
+ it('should return error for unknown topic', async () => {
143
+ const ctx = createMockContext();
144
+ mockApiClient.getHelpTopic.mockResolvedValue({ ok: true, data: null });
145
+ mockApiClient.getHelpTopics.mockResolvedValue({
146
+ ok: true,
147
+ data: [{ slug: 'tasks', title: 'Tasks' }, { slug: 'getting_started', title: 'Getting Started' }],
148
+ });
149
+
150
+ const result = await getHelp({ topic: 'unknown_topic' }, ctx);
151
+
152
+ expect(result.result).toMatchObject({
153
+ error: 'Unknown topic: unknown_topic',
154
+ });
155
+ expect(result.result).toHaveProperty('available');
156
+ });
157
+
158
+ it('should list available topics for unknown topic', async () => {
159
+ const ctx = createMockContext();
160
+ mockApiClient.getHelpTopic.mockResolvedValue({ ok: true, data: null });
161
+ mockApiClient.getHelpTopics.mockResolvedValue({
162
+ ok: true,
163
+ data: [
164
+ { slug: 'tasks', title: 'Tasks' },
165
+ { slug: 'getting_started', title: 'Getting Started' },
166
+ { slug: 'validation', title: 'Validation' },
167
+ ],
168
+ });
169
+
170
+ const result = await getHelp({ topic: 'nonexistent' }, ctx);
171
+
172
+ const available = (result.result as { available: string[] }).available;
173
+ expect(Array.isArray(available)).toBe(true);
174
+ expect(available.length).toBeGreaterThan(0);
175
+ });
176
+ });
177
+
178
+ // ============================================================================
179
+ // getTokenUsage Tests
180
+ // ============================================================================
181
+
182
+ describe('getTokenUsage', () => {
183
+ beforeEach(() => vi.clearAllMocks());
184
+
185
+ it('should return token usage stats', async () => {
186
+ const ctx = createMockContext();
187
+
188
+ const result = await getTokenUsage({}, ctx);
189
+
190
+ expect(result.result).toHaveProperty('session');
191
+ expect(result.result).toHaveProperty('top_tools');
192
+ expect(result.result).toHaveProperty('note');
193
+ });
194
+
195
+ it('should return correct session stats', async () => {
196
+ const ctx = createMockContext({
197
+ tokenUsage: {
198
+ callCount: 10,
199
+ totalTokens: 5000,
200
+ byTool: {},
201
+ byModel: {},
202
+ currentModel: null,
203
+ },
204
+ });
205
+
206
+ const result = await getTokenUsage({}, ctx);
207
+ const session = (result.result as { session: { calls: number; tokens: number; avg_per_call: number } }).session;
208
+
209
+ expect(session.calls).toBe(10);
210
+ expect(session.tokens).toBe(5000);
211
+ expect(session.avg_per_call).toBe(500);
212
+ });
213
+
214
+ it('should return top tools sorted by tokens', async () => {
215
+ const ctx = createMockContext({
216
+ tokenUsage: {
217
+ callCount: 10,
218
+ totalTokens: 5000,
219
+ byTool: {
220
+ tool_a: { calls: 2, tokens: 1000 },
221
+ tool_b: { calls: 5, tokens: 3000 },
222
+ tool_c: { calls: 3, tokens: 1000 },
223
+ },
224
+ byModel: {},
225
+ currentModel: null,
226
+ },
227
+ });
228
+
229
+ const result = await getTokenUsage({}, ctx);
230
+ const topTools = (result.result as { top_tools: Array<{ tool: string; tokens: number }> }).top_tools;
231
+
232
+ // Should be sorted by tokens descending
233
+ expect(topTools[0].tool).toBe('tool_b');
234
+ expect(topTools[0].tokens).toBe(3000);
235
+ });
236
+
237
+ it('should handle zero calls gracefully', async () => {
238
+ const ctx = createMockContext({
239
+ tokenUsage: {
240
+ callCount: 0,
241
+ totalTokens: 0,
242
+ byTool: {},
243
+ byModel: {},
244
+ currentModel: null,
245
+ },
246
+ });
247
+
248
+ const result = await getTokenUsage({}, ctx);
249
+ const session = (result.result as { session: { calls: number; tokens: number; avg_per_call: number } }).session;
250
+
251
+ expect(session.calls).toBe(0);
252
+ expect(session.tokens).toBe(0);
253
+ expect(session.avg_per_call).toBe(0);
254
+ });
255
+
256
+ it('should limit top_tools to 5', async () => {
257
+ const ctx = createMockContext({
258
+ tokenUsage: {
259
+ callCount: 20,
260
+ totalTokens: 10000,
261
+ byTool: {
262
+ tool_1: { calls: 1, tokens: 100 },
263
+ tool_2: { calls: 2, tokens: 200 },
264
+ tool_3: { calls: 3, tokens: 300 },
265
+ tool_4: { calls: 4, tokens: 400 },
266
+ tool_5: { calls: 5, tokens: 500 },
267
+ tool_6: { calls: 6, tokens: 600 },
268
+ tool_7: { calls: 7, tokens: 700 },
269
+ },
270
+ byModel: {},
271
+ currentModel: null,
272
+ },
273
+ });
274
+
275
+ const result = await getTokenUsage({}, ctx);
276
+ const topTools = (result.result as { top_tools: Array<{ tool: string }> }).top_tools;
277
+
278
+ expect(topTools.length).toBe(5);
279
+ });
280
+ });
281
+
282
+ // ============================================================================
283
+ // endWorkSession Tests
284
+ // ============================================================================
285
+
286
+ describe('endWorkSession', () => {
287
+ beforeEach(() => vi.clearAllMocks());
288
+
289
+ it('should handle no active session gracefully', async () => {
290
+ const ctx = createMockContext({ sessionId: null });
291
+
292
+ const result = await endWorkSession({}, ctx);
293
+
294
+ expect(result.result).toMatchObject({
295
+ success: true,
296
+ message: 'No active session to end',
297
+ });
298
+ });
299
+
300
+ it('should use provided session_id over current session', async () => {
301
+ const ctx = createMockContext();
302
+ mockApiClient.syncSession.mockResolvedValue({ ok: true });
303
+ mockApiClient.endSession.mockResolvedValue({
304
+ ok: true,
305
+ data: {
306
+ session_summary: {
307
+ agent_name: 'Wave',
308
+ tasks_completed_this_session: 3,
309
+ tasks_awaiting_validation: 1,
310
+ tasks_released: 0,
311
+ },
312
+ },
313
+ });
314
+
315
+ const result = await endWorkSession({ session_id: 'other-session-456' }, ctx);
316
+
317
+ expect(result.result).toHaveProperty('ended_session_id', 'other-session-456');
318
+ expect(mockApiClient.endSession).toHaveBeenCalledWith('other-session-456');
319
+ });
320
+
321
+ it('should call updateSession to clear current session', async () => {
322
+ const ctx = createMockContext();
323
+ mockApiClient.syncSession.mockResolvedValue({ ok: true });
324
+ mockApiClient.endSession.mockResolvedValue({
325
+ ok: true,
326
+ data: {
327
+ session_summary: {
328
+ agent_name: 'Wave',
329
+ tasks_completed_this_session: 0,
330
+ tasks_awaiting_validation: 0,
331
+ tasks_released: 0,
332
+ },
333
+ },
334
+ });
335
+
336
+ await endWorkSession({}, ctx);
337
+
338
+ expect(ctx.updateSession).toHaveBeenCalledWith({ currentSessionId: null });
339
+ });
340
+
341
+ it('should return session summary', async () => {
342
+ const ctx = createMockContext();
343
+ mockApiClient.syncSession.mockResolvedValue({ ok: true });
344
+ mockApiClient.endSession.mockResolvedValue({
345
+ ok: true,
346
+ data: {
347
+ session_summary: {
348
+ agent_name: 'Wave',
349
+ tasks_completed_this_session: 2,
350
+ tasks_awaiting_validation: 1,
351
+ tasks_released: 0,
352
+ },
353
+ },
354
+ });
355
+
356
+ const result = await endWorkSession({}, ctx);
357
+
358
+ expect(result.result).toHaveProperty('session_summary');
359
+ const summary = (result.result as { session_summary: { agent_name: string; token_usage: unknown } }).session_summary;
360
+ expect(summary.agent_name).toBe('Wave');
361
+ expect(summary).toHaveProperty('token_usage');
362
+ });
363
+
364
+ it('should not call updateSession when ending a different session', async () => {
365
+ const ctx = createMockContext({ sessionId: 'session-123' });
366
+ mockApiClient.syncSession.mockResolvedValue({ ok: true });
367
+ mockApiClient.endSession.mockResolvedValue({
368
+ ok: true,
369
+ data: {
370
+ session_summary: {
371
+ agent_name: 'Wave',
372
+ tasks_completed_this_session: 0,
373
+ tasks_awaiting_validation: 0,
374
+ tasks_released: 0,
375
+ },
376
+ },
377
+ });
378
+
379
+ await endWorkSession({ session_id: 'different-session' }, ctx);
380
+
381
+ // Should NOT clear the current session since we're ending a different one
382
+ expect(ctx.updateSession).not.toHaveBeenCalledWith({ currentSessionId: null });
383
+ });
384
+ });
385
+
386
+ // ============================================================================
387
+ // startWorkSession Tests
388
+ // ============================================================================
389
+
390
+ describe('startWorkSession', () => {
391
+ beforeEach(() => {
392
+ vi.clearAllMocks();
393
+ });
394
+
395
+ it('should return error when project_id and git_url are both missing', async () => {
396
+ const ctx = createMockContext({ sessionId: null });
397
+
398
+ const result = await startWorkSession({}, ctx);
399
+
400
+ expect(result.result).toMatchObject({
401
+ error: 'Please provide project_id or git_url to start a session',
402
+ });
403
+ });
404
+
405
+ it('should return project_not_found when no project matches', async () => {
406
+ const ctx = createMockContext({ sessionId: null });
407
+ mockApiClient.startSession.mockResolvedValue({
408
+ ok: true,
409
+ data: {
410
+ session_started: false,
411
+ project_not_found: true,
412
+ message: 'No project found',
413
+ suggestion: {
414
+ action: 'create_project',
415
+ example: 'create_project(name: "repo")',
416
+ note: 'After creating the project, call start_work_session again.',
417
+ },
418
+ },
419
+ });
420
+
421
+ const result = await startWorkSession({ git_url: 'https://github.com/test/repo' }, ctx);
422
+
423
+ expect(result.result).toMatchObject({
424
+ session_started: false,
425
+ project_not_found: true,
426
+ });
427
+ expect(result.result).toHaveProperty('suggestion');
428
+ });
429
+
430
+ it('should reuse existing persona when session already has one', async () => {
431
+ const ctx = createMockContext({ sessionId: null });
432
+ mockApiClient.startSession.mockResolvedValue({
433
+ ok: true,
434
+ data: {
435
+ session_started: true,
436
+ session_id: 'existing-session-123',
437
+ persona: 'Pixel',
438
+ role: 'developer',
439
+ project: { id: 'project-123', name: 'Test Project' },
440
+ },
441
+ });
442
+
443
+ const result = await startWorkSession({ project_id: 'project-123' }, ctx);
444
+
445
+ expect(result.result).toMatchObject({
446
+ session_started: true,
447
+ persona: 'Pixel',
448
+ });
449
+ });
450
+
451
+ it('should call updateSession with session ID and persona', async () => {
452
+ const ctx = createMockContext({ sessionId: null });
453
+ mockApiClient.startSession.mockResolvedValue({
454
+ ok: true,
455
+ data: {
456
+ session_started: true,
457
+ session_id: 'new-session-123',
458
+ persona: 'Wave',
459
+ role: 'developer',
460
+ project: { id: 'project-123', name: 'Test Project' },
461
+ },
462
+ });
463
+
464
+ await startWorkSession({ project_id: 'project-123' }, ctx);
465
+
466
+ expect(ctx.updateSession).toHaveBeenCalledWith(
467
+ expect.objectContaining({
468
+ currentSessionId: 'new-session-123',
469
+ currentPersona: 'Wave',
470
+ })
471
+ );
472
+ });
473
+
474
+ it('should return lite mode response by default', async () => {
475
+ const ctx = createMockContext({ sessionId: null });
476
+ mockApiClient.startSession.mockResolvedValue({
477
+ ok: true,
478
+ data: {
479
+ session_started: true,
480
+ session_id: 'new-session-123',
481
+ persona: 'Wave',
482
+ role: 'developer',
483
+ project: { id: 'project-123', name: 'Test Project' },
484
+ directive: 'ACTION_REQUIRED: Start working immediately.',
485
+ },
486
+ });
487
+
488
+ const result = await startWorkSession({ project_id: 'project-123' }, ctx);
489
+
490
+ expect(result.result).toMatchObject({
491
+ session_started: true,
492
+ });
493
+ expect(result.result).toHaveProperty('project');
494
+ expect(result.result).toHaveProperty('directive');
495
+ });
496
+
497
+ it('should return error when API call fails', async () => {
498
+ const ctx = createMockContext({ sessionId: null });
499
+ mockApiClient.startSession.mockResolvedValue({
500
+ ok: false,
501
+ error: 'Internal server error',
502
+ });
503
+
504
+ const result = await startWorkSession({ project_id: 'project-123' }, ctx);
505
+
506
+ expect(result.result).toMatchObject({
507
+ error: 'Internal server error',
508
+ });
509
+ });
510
+
511
+ it('should include next_task when available', async () => {
512
+ const ctx = createMockContext({ sessionId: null });
513
+ mockApiClient.startSession.mockResolvedValue({
514
+ ok: true,
515
+ data: {
516
+ session_started: true,
517
+ session_id: 'new-session-123',
518
+ persona: 'Wave',
519
+ role: 'developer',
520
+ project: { id: 'project-123', name: 'Test Project' },
521
+ next_task: { id: 'task-1', title: 'Fix bug', priority: 1 },
522
+ },
523
+ });
524
+
525
+ const result = await startWorkSession({ project_id: 'project-123' }, ctx);
526
+
527
+ expect(result.result).toHaveProperty('next_task');
528
+ expect((result.result as { next_task: { id: string } }).next_task.id).toBe('task-1');
529
+ });
530
+
531
+ it('should include pending_requests when available in full mode', async () => {
532
+ const ctx = createMockContext({ sessionId: null });
533
+ const mockRequests = [
534
+ { id: 'req-1', request_type: 'question', message: 'What is the status?', created_at: '2026-01-14T10:00:00Z' },
535
+ { id: 'req-2', request_type: 'instruction', message: 'Please prioritize task X', created_at: '2026-01-14T11:00:00Z' },
536
+ ];
537
+ mockApiClient.startSession.mockResolvedValue({
538
+ ok: true,
539
+ data: {
540
+ session_started: true,
541
+ session_id: 'new-session-123',
542
+ persona: 'Wave',
543
+ role: 'developer',
544
+ project: { id: 'project-123', name: 'Test Project' },
545
+ pending_requests: mockRequests,
546
+ },
547
+ });
548
+
549
+ const result = await startWorkSession({ project_id: 'project-123', mode: 'full' }, ctx);
550
+
551
+ expect(result.result).toHaveProperty('pending_requests');
552
+ expect(result.result).toHaveProperty('pending_requests_count', 2);
553
+ const pendingRequests = (result.result as { pending_requests: typeof mockRequests }).pending_requests;
554
+ expect(pendingRequests.length).toBe(2);
555
+ expect(pendingRequests[0].request_type).toBe('question');
556
+ });
557
+
558
+ it('should not include pending_requests when empty', async () => {
559
+ const ctx = createMockContext({ sessionId: null });
560
+ mockApiClient.startSession.mockResolvedValue({
561
+ ok: true,
562
+ data: {
563
+ session_started: true,
564
+ session_id: 'new-session-123',
565
+ persona: 'Wave',
566
+ role: 'developer',
567
+ project: { id: 'project-123', name: 'Test Project' },
568
+ pending_requests: [],
569
+ },
570
+ });
571
+
572
+ const result = await startWorkSession({ project_id: 'project-123', mode: 'full' }, ctx);
573
+
574
+ expect(result.result).not.toHaveProperty('pending_requests');
575
+ expect(result.result).not.toHaveProperty('pending_requests_count');
576
+ });
577
+
578
+ it('should surface awaiting_validation tasks when present', async () => {
579
+ const ctx = createMockContext({ sessionId: null });
580
+ const mockValidationTasks = [
581
+ { id: 'task-1', title: 'Implement login' },
582
+ { id: 'task-2', title: 'Add tests' },
583
+ ];
584
+ mockApiClient.startSession.mockResolvedValue({
585
+ ok: true,
586
+ data: {
587
+ session_started: true,
588
+ session_id: 'new-session-123',
589
+ persona: 'Wave',
590
+ role: 'developer',
591
+ project: { id: 'project-123', name: 'Test Project' },
592
+ awaiting_validation: mockValidationTasks,
593
+ validation_count: 2,
594
+ validation_priority: 'VALIDATE FIRST: 2 task(s) need review before starting new work.',
595
+ directive: 'VALIDATE FIRST: 2 task(s) need review before starting new work. Call claim_validation(task_id) to start reviewing.',
596
+ },
597
+ });
598
+
599
+ const result = await startWorkSession({ project_id: 'project-123' }, ctx);
600
+
601
+ expect(result.result).toHaveProperty('awaiting_validation');
602
+ expect(result.result).toHaveProperty('validation_count', 2);
603
+ expect(result.result).toHaveProperty('validation_priority');
604
+ const awaitingValidation = (result.result as { awaiting_validation: typeof mockValidationTasks }).awaiting_validation;
605
+ expect(awaitingValidation.length).toBe(2);
606
+ expect(awaitingValidation[0].id).toBe('task-1');
607
+ });
608
+
609
+ it('should include next_action when validation tasks are present', async () => {
610
+ const ctx = createMockContext({ sessionId: null });
611
+ mockApiClient.startSession.mockResolvedValue({
612
+ ok: true,
613
+ data: {
614
+ session_started: true,
615
+ session_id: 'new-session-123',
616
+ persona: 'Wave',
617
+ role: 'developer',
618
+ project: { id: 'project-123', name: 'Test Project' },
619
+ awaiting_validation: [{ id: 'task-abc', title: 'Fix bug' }],
620
+ validation_count: 1,
621
+ next_action: 'claim_validation(task_id: "task-abc")',
622
+ },
623
+ });
624
+
625
+ const result = await startWorkSession({ project_id: 'project-123' }, ctx);
626
+
627
+ expect(result.result).toHaveProperty('next_action');
628
+ expect((result.result as { next_action: string }).next_action).toContain('task-abc');
629
+ });
630
+ });
631
+
632
+ // ============================================================================
633
+ // reportTokenUsage Tests
634
+ // ============================================================================
635
+
636
+ describe('reportTokenUsage', () => {
637
+ beforeEach(() => vi.clearAllMocks());
638
+
639
+ it('should report token usage successfully with session', async () => {
640
+ const ctx = createMockContext();
641
+ mockApiClient.reportTokenUsage.mockResolvedValue({
642
+ ok: true,
643
+ data: {
644
+ success: true,
645
+ reported: {
646
+ session_id: 'session-123',
647
+ model: 'sonnet',
648
+ input_tokens: 1000,
649
+ output_tokens: 500,
650
+ total_tokens: 1500,
651
+ estimated_cost_usd: 0.0105,
652
+ },
653
+ task_attributed: true,
654
+ task_id: 'task-123',
655
+ },
656
+ });
657
+
658
+ const result = await reportTokenUsage(
659
+ { input_tokens: 1000, output_tokens: 500, model: 'sonnet' },
660
+ ctx
661
+ );
662
+
663
+ expect(result.result).toMatchObject({
664
+ success: true,
665
+ task_attributed: true,
666
+ task_id: 'task-123',
667
+ });
668
+ expect(result.result).toHaveProperty('reported');
669
+ expect(mockApiClient.reportTokenUsage).toHaveBeenCalledWith('session-123', {
670
+ input_tokens: 1000,
671
+ output_tokens: 500,
672
+ model: 'sonnet',
673
+ });
674
+ });
675
+
676
+ it('should default to sonnet model when not specified', async () => {
677
+ const ctx = createMockContext();
678
+ mockApiClient.reportTokenUsage.mockResolvedValue({
679
+ ok: true,
680
+ data: {
681
+ success: true,
682
+ reported: {
683
+ session_id: 'session-123',
684
+ model: 'sonnet',
685
+ input_tokens: 1000,
686
+ output_tokens: 500,
687
+ total_tokens: 1500,
688
+ estimated_cost_usd: 0.0105,
689
+ },
690
+ task_attributed: false,
691
+ },
692
+ });
693
+
694
+ await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
695
+
696
+ expect(mockApiClient.reportTokenUsage).toHaveBeenCalledWith('session-123', {
697
+ input_tokens: 1000,
698
+ output_tokens: 500,
699
+ model: 'sonnet',
700
+ });
701
+ });
702
+
703
+ it('should use session currentModel if available', async () => {
704
+ const ctx = createMockContext({
705
+ tokenUsage: {
706
+ callCount: 0,
707
+ totalTokens: 0,
708
+ byTool: {},
709
+ byModel: {},
710
+ currentModel: 'opus',
711
+ },
712
+ });
713
+ mockApiClient.reportTokenUsage.mockResolvedValue({
714
+ ok: true,
715
+ data: {
716
+ success: true,
717
+ reported: {
718
+ session_id: 'session-123',
719
+ model: 'opus',
720
+ input_tokens: 1000,
721
+ output_tokens: 500,
722
+ total_tokens: 1500,
723
+ estimated_cost_usd: 0.0525,
724
+ },
725
+ task_attributed: false,
726
+ },
727
+ });
728
+
729
+ await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
730
+
731
+ expect(mockApiClient.reportTokenUsage).toHaveBeenCalledWith('session-123', {
732
+ input_tokens: 1000,
733
+ output_tokens: 500,
734
+ model: 'opus',
735
+ });
736
+ });
737
+
738
+ it('should return error for negative token counts', async () => {
739
+ const ctx = createMockContext();
740
+
741
+ const result = await reportTokenUsage({ input_tokens: -100, output_tokens: 500 }, ctx);
742
+
743
+ expect(result.result).toMatchObject({
744
+ error: 'Token counts must be non-negative',
745
+ });
746
+ expect(mockApiClient.reportTokenUsage).not.toHaveBeenCalled();
747
+ });
748
+
749
+ it('should handle local-only reporting when no session', async () => {
750
+ const ctx = createMockContext({ sessionId: null });
751
+
752
+ const result = await reportTokenUsage(
753
+ { input_tokens: 1000, output_tokens: 500, model: 'haiku' },
754
+ ctx
755
+ );
756
+
757
+ expect(result.result).toMatchObject({
758
+ success: true,
759
+ });
760
+ expect(result.result).toHaveProperty('reported');
761
+ const reported = (result.result as { reported: { model: string } }).reported;
762
+ expect(reported.model).toBe('haiku');
763
+ expect(result.result).toHaveProperty('note');
764
+ expect(mockApiClient.reportTokenUsage).not.toHaveBeenCalled();
765
+ });
766
+
767
+ it('should update local token tracking', async () => {
768
+ const ctx = createMockContext({
769
+ tokenUsage: {
770
+ callCount: 5,
771
+ totalTokens: 2500,
772
+ byTool: {},
773
+ byModel: { sonnet: { input: 1000, output: 500 } },
774
+ currentModel: null,
775
+ },
776
+ });
777
+ mockApiClient.reportTokenUsage.mockResolvedValue({
778
+ ok: true,
779
+ data: {
780
+ success: true,
781
+ reported: {
782
+ session_id: 'session-123',
783
+ model: 'sonnet',
784
+ input_tokens: 1000,
785
+ output_tokens: 500,
786
+ total_tokens: 1500,
787
+ estimated_cost_usd: 0.0105,
788
+ },
789
+ task_attributed: false,
790
+ },
791
+ });
792
+
793
+ await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
794
+
795
+ expect(ctx.updateSession).toHaveBeenCalledWith(
796
+ expect.objectContaining({
797
+ tokenUsage: expect.objectContaining({
798
+ callCount: 6,
799
+ totalTokens: 4000,
800
+ byModel: { sonnet: { input: 2000, output: 1000 } },
801
+ }),
802
+ })
803
+ );
804
+ });
805
+
806
+ it('should handle backend failure gracefully', async () => {
807
+ const ctx = createMockContext();
808
+ mockApiClient.reportTokenUsage.mockResolvedValue({
809
+ ok: false,
810
+ error: 'Server error',
811
+ });
812
+
813
+ const result = await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
814
+
815
+ // Should still succeed with local calculation
816
+ expect(result.result).toMatchObject({
817
+ success: true,
818
+ });
819
+ expect(result.result).toHaveProperty('warning');
820
+ });
821
+
822
+ it('should indicate when task attribution succeeds', async () => {
823
+ const ctx = createMockContext();
824
+ mockApiClient.reportTokenUsage.mockResolvedValue({
825
+ ok: true,
826
+ data: {
827
+ success: true,
828
+ reported: {
829
+ session_id: 'session-123',
830
+ model: 'sonnet',
831
+ input_tokens: 1000,
832
+ output_tokens: 500,
833
+ total_tokens: 1500,
834
+ estimated_cost_usd: 0.0105,
835
+ },
836
+ task_attributed: true,
837
+ task_id: 'task-abc123',
838
+ },
839
+ });
840
+
841
+ const result = await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
842
+
843
+ expect(result.result).toMatchObject({
844
+ task_attributed: true,
845
+ task_id: 'task-abc123',
846
+ });
847
+ expect((result.result as { note: string }).note).toContain('attributed to current task');
848
+ });
849
+
850
+ it('should indicate when no task to attribute to', async () => {
851
+ const ctx = createMockContext();
852
+ mockApiClient.reportTokenUsage.mockResolvedValue({
853
+ ok: true,
854
+ data: {
855
+ success: true,
856
+ reported: {
857
+ session_id: 'session-123',
858
+ model: 'sonnet',
859
+ input_tokens: 1000,
860
+ output_tokens: 500,
861
+ total_tokens: 1500,
862
+ estimated_cost_usd: 0.0105,
863
+ },
864
+ task_attributed: false,
865
+ },
866
+ });
867
+
868
+ const result = await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
869
+
870
+ expect(result.result).toMatchObject({
871
+ task_attributed: false,
872
+ });
873
+ expect((result.result as { note: string }).note).toContain('No active task');
874
+ });
875
+ });