@vibescope/mcp-server 0.4.5 → 0.4.7

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 (176) hide show
  1. package/CHANGELOG.md +84 -84
  2. package/README.md +194 -194
  3. package/dist/api-client/project.d.ts +1 -0
  4. package/dist/api-client.d.ts +4 -1
  5. package/dist/api-client.js +24 -7
  6. package/dist/cli-init.js +25 -24
  7. package/dist/cli.js +26 -26
  8. package/dist/handlers/chat.d.ts +2 -0
  9. package/dist/handlers/chat.js +25 -0
  10. package/dist/handlers/discovery.js +12 -0
  11. package/dist/handlers/project.js +4 -2
  12. package/dist/handlers/tool-docs.js +1203 -1137
  13. package/dist/handlers/version.js +1 -1
  14. package/dist/index.js +159 -87
  15. package/dist/setup.js +13 -7
  16. package/dist/templates/agent-guidelines.d.ts +1 -1
  17. package/dist/templates/agent-guidelines.js +205 -187
  18. package/dist/templates/help-content.js +1621 -1621
  19. package/dist/tools/bodies-of-work.js +6 -6
  20. package/dist/tools/chat.d.ts +1 -0
  21. package/dist/tools/chat.js +24 -0
  22. package/dist/tools/cloud-agents.js +22 -22
  23. package/dist/tools/features.d.ts +13 -0
  24. package/dist/tools/features.js +151 -0
  25. package/dist/tools/index.d.ts +3 -1
  26. package/dist/tools/index.js +4 -1
  27. package/dist/tools/milestones.js +2 -2
  28. package/dist/tools/project.js +4 -0
  29. package/dist/tools/requests.js +1 -1
  30. package/dist/tools/session.js +11 -11
  31. package/dist/tools/sprints.js +9 -9
  32. package/dist/tools/tasks.js +35 -35
  33. package/dist/tools/worktrees.js +14 -14
  34. package/dist/tools.d.ts +2 -0
  35. package/dist/tools.js +3602 -0
  36. package/dist/utils.js +11 -11
  37. package/dist/version.d.ts +9 -3
  38. package/dist/version.js +56 -8
  39. package/docs/TOOLS.md +2663 -2559
  40. package/package.json +53 -53
  41. package/scripts/generate-docs.ts +212 -212
  42. package/scripts/version-bump.ts +203 -203
  43. package/src/api-client/blockers.ts +86 -86
  44. package/src/api-client/bodies-of-work.ts +194 -194
  45. package/src/api-client/chat.ts +50 -50
  46. package/src/api-client/connectors.ts +152 -152
  47. package/src/api-client/cost.ts +185 -185
  48. package/src/api-client/decisions.ts +87 -87
  49. package/src/api-client/deployment.ts +313 -313
  50. package/src/api-client/discovery.ts +81 -81
  51. package/src/api-client/fallback.ts +52 -52
  52. package/src/api-client/file-checkouts.ts +115 -115
  53. package/src/api-client/findings.ts +100 -100
  54. package/src/api-client/git-issues.ts +88 -88
  55. package/src/api-client/ideas.ts +112 -112
  56. package/src/api-client/index.ts +592 -592
  57. package/src/api-client/milestones.ts +83 -83
  58. package/src/api-client/organizations.ts +185 -185
  59. package/src/api-client/progress.ts +94 -94
  60. package/src/api-client/project.ts +180 -179
  61. package/src/api-client/requests.ts +54 -54
  62. package/src/api-client/session.ts +220 -220
  63. package/src/api-client/sprints.ts +227 -227
  64. package/src/api-client/subtasks.ts +57 -57
  65. package/src/api-client/tasks.ts +450 -450
  66. package/src/api-client/types.ts +32 -32
  67. package/src/api-client/validation.ts +60 -60
  68. package/src/api-client/worktrees.ts +53 -53
  69. package/src/api-client.test.ts +847 -847
  70. package/src/api-client.ts +2723 -2706
  71. package/src/cli-init.ts +558 -557
  72. package/src/cli.test.ts +284 -284
  73. package/src/cli.ts +204 -204
  74. package/src/handlers/__test-setup__.ts +240 -240
  75. package/src/handlers/__test-utils__.ts +89 -89
  76. package/src/handlers/blockers.test.ts +468 -468
  77. package/src/handlers/blockers.ts +172 -172
  78. package/src/handlers/bodies-of-work.test.ts +704 -704
  79. package/src/handlers/bodies-of-work.ts +526 -526
  80. package/src/handlers/chat.test.ts +185 -185
  81. package/src/handlers/chat.ts +101 -69
  82. package/src/handlers/cloud-agents.test.ts +438 -438
  83. package/src/handlers/cloud-agents.ts +156 -156
  84. package/src/handlers/connectors.test.ts +834 -834
  85. package/src/handlers/connectors.ts +229 -229
  86. package/src/handlers/cost.test.ts +462 -462
  87. package/src/handlers/cost.ts +285 -285
  88. package/src/handlers/decisions.test.ts +382 -382
  89. package/src/handlers/decisions.ts +153 -153
  90. package/src/handlers/deployment.test.ts +551 -551
  91. package/src/handlers/deployment.ts +570 -570
  92. package/src/handlers/discovery.test.ts +206 -206
  93. package/src/handlers/discovery.ts +427 -415
  94. package/src/handlers/fallback.test.ts +537 -537
  95. package/src/handlers/fallback.ts +194 -194
  96. package/src/handlers/file-checkouts.test.ts +750 -750
  97. package/src/handlers/file-checkouts.ts +185 -185
  98. package/src/handlers/findings.test.ts +633 -633
  99. package/src/handlers/findings.ts +239 -239
  100. package/src/handlers/git-issues.test.ts +631 -631
  101. package/src/handlers/git-issues.ts +136 -136
  102. package/src/handlers/ideas.test.ts +644 -644
  103. package/src/handlers/ideas.ts +207 -207
  104. package/src/handlers/index.ts +93 -93
  105. package/src/handlers/milestones.test.ts +475 -475
  106. package/src/handlers/milestones.ts +180 -180
  107. package/src/handlers/organizations.test.ts +826 -826
  108. package/src/handlers/organizations.ts +315 -315
  109. package/src/handlers/progress.test.ts +269 -269
  110. package/src/handlers/progress.ts +77 -77
  111. package/src/handlers/project.test.ts +546 -546
  112. package/src/handlers/project.ts +242 -239
  113. package/src/handlers/requests.test.ts +303 -303
  114. package/src/handlers/requests.ts +99 -99
  115. package/src/handlers/roles.test.ts +305 -305
  116. package/src/handlers/roles.ts +219 -219
  117. package/src/handlers/session.test.ts +998 -998
  118. package/src/handlers/session.ts +1105 -1105
  119. package/src/handlers/sprints.test.ts +732 -732
  120. package/src/handlers/sprints.ts +537 -537
  121. package/src/handlers/tasks.test.ts +931 -931
  122. package/src/handlers/tasks.ts +1133 -1133
  123. package/src/handlers/tool-categories.test.ts +66 -66
  124. package/src/handlers/tool-docs.test.ts +511 -511
  125. package/src/handlers/tool-docs.ts +1571 -1499
  126. package/src/handlers/types.test.ts +259 -259
  127. package/src/handlers/types.ts +176 -176
  128. package/src/handlers/validation.test.ts +582 -582
  129. package/src/handlers/validation.ts +164 -164
  130. package/src/handlers/version.ts +63 -63
  131. package/src/index.test.ts +674 -674
  132. package/src/index.ts +884 -807
  133. package/src/setup.test.ts +243 -233
  134. package/src/setup.ts +410 -404
  135. package/src/templates/agent-guidelines.ts +233 -215
  136. package/src/templates/help-content.ts +1751 -1751
  137. package/src/token-tracking.test.ts +463 -463
  138. package/src/token-tracking.ts +167 -167
  139. package/src/tools/blockers.ts +122 -122
  140. package/src/tools/bodies-of-work.ts +283 -283
  141. package/src/tools/chat.ts +72 -46
  142. package/src/tools/cloud-agents.ts +101 -101
  143. package/src/tools/connectors.ts +191 -191
  144. package/src/tools/cost.ts +111 -111
  145. package/src/tools/decisions.ts +111 -111
  146. package/src/tools/deployment.ts +455 -455
  147. package/src/tools/discovery.ts +76 -76
  148. package/src/tools/fallback.ts +111 -111
  149. package/src/tools/features.ts +154 -0
  150. package/src/tools/file-checkouts.ts +145 -145
  151. package/src/tools/findings.ts +101 -101
  152. package/src/tools/git-issues.ts +130 -130
  153. package/src/tools/ideas.ts +162 -162
  154. package/src/tools/index.ts +141 -137
  155. package/src/tools/milestones.ts +118 -118
  156. package/src/tools/organizations.ts +224 -224
  157. package/src/tools/progress.ts +73 -73
  158. package/src/tools/project.ts +206 -202
  159. package/src/tools/requests.ts +68 -68
  160. package/src/tools/roles.ts +112 -112
  161. package/src/tools/session.ts +181 -181
  162. package/src/tools/sprints.ts +298 -298
  163. package/src/tools/tasks.ts +550 -550
  164. package/src/tools/tools.test.ts +222 -222
  165. package/src/tools/types.ts +9 -9
  166. package/src/tools/validation.ts +75 -75
  167. package/src/tools/version.ts +34 -34
  168. package/src/tools/worktrees.ts +66 -66
  169. package/src/tools.test.ts +416 -416
  170. package/src/utils.test.ts +1014 -1014
  171. package/src/utils.ts +586 -586
  172. package/src/validators.test.ts +223 -223
  173. package/src/validators.ts +249 -249
  174. package/src/version.ts +162 -109
  175. package/tsconfig.json +16 -16
  176. package/vitest.config.ts +14 -14
@@ -1,998 +1,998 @@
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
- // Git URL normalization messaging tests
632
- it('should include git_url_normalized when URL is normalized (SSH format)', async () => {
633
- const ctx = createMockContext({ sessionId: null });
634
- mockApiClient.startSession.mockResolvedValue({
635
- ok: true,
636
- data: {
637
- session_started: true,
638
- session_id: 'new-session-123',
639
- persona: 'Wave',
640
- role: 'developer',
641
- project: { id: 'project-123', name: 'Test Project', git_url: 'https://github.com/owner/repo' },
642
- },
643
- });
644
-
645
- const result = await startWorkSession({ git_url: 'git@github.com:owner/repo.git' }, ctx);
646
-
647
- expect(result.result).toHaveProperty('git_url_normalized');
648
- const normalized = (result.result as { git_url_normalized: { original: string; normalized: string; message: string } }).git_url_normalized;
649
- expect(normalized.original).toBe('git@github.com:owner/repo.git');
650
- expect(normalized.normalized).toBe('https://github.com/owner/repo');
651
- expect(normalized.message).toContain('normalized');
652
- });
653
-
654
- it('should include git_url_normalized when URL has .git suffix', async () => {
655
- const ctx = createMockContext({ sessionId: null });
656
- mockApiClient.startSession.mockResolvedValue({
657
- ok: true,
658
- data: {
659
- session_started: true,
660
- session_id: 'new-session-123',
661
- persona: 'Wave',
662
- role: 'developer',
663
- project: { id: 'project-123', name: 'Test Project' },
664
- },
665
- });
666
-
667
- const result = await startWorkSession({ git_url: 'https://github.com/owner/repo.git' }, ctx);
668
-
669
- expect(result.result).toHaveProperty('git_url_normalized');
670
- const normalized = (result.result as { git_url_normalized: { original: string; normalized: string } }).git_url_normalized;
671
- expect(normalized.original).toBe('https://github.com/owner/repo.git');
672
- expect(normalized.normalized).toBe('https://github.com/owner/repo');
673
- });
674
-
675
- it('should include git_url_normalized when URL has different casing', async () => {
676
- const ctx = createMockContext({ sessionId: null });
677
- mockApiClient.startSession.mockResolvedValue({
678
- ok: true,
679
- data: {
680
- session_started: true,
681
- session_id: 'new-session-123',
682
- persona: 'Wave',
683
- role: 'developer',
684
- project: { id: 'project-123', name: 'Test Project' },
685
- },
686
- });
687
-
688
- const result = await startWorkSession({ git_url: 'https://GitHub.COM/OWNER/Repo' }, ctx);
689
-
690
- expect(result.result).toHaveProperty('git_url_normalized');
691
- const normalized = (result.result as { git_url_normalized: { original: string; normalized: string } }).git_url_normalized;
692
- expect(normalized.original).toBe('https://GitHub.COM/OWNER/Repo');
693
- expect(normalized.normalized).toBe('https://github.com/owner/repo');
694
- });
695
-
696
- it('should NOT include git_url_normalized when URL is already normalized', async () => {
697
- const ctx = createMockContext({ sessionId: null });
698
- mockApiClient.startSession.mockResolvedValue({
699
- ok: true,
700
- data: {
701
- session_started: true,
702
- session_id: 'new-session-123',
703
- persona: 'Wave',
704
- role: 'developer',
705
- project: { id: 'project-123', name: 'Test Project' },
706
- },
707
- });
708
-
709
- const result = await startWorkSession({ git_url: 'https://github.com/owner/repo' }, ctx);
710
-
711
- expect(result.result).not.toHaveProperty('git_url_normalized');
712
- });
713
-
714
- it('should NOT include git_url_normalized when using project_id instead of git_url', async () => {
715
- const ctx = createMockContext({ sessionId: null });
716
- mockApiClient.startSession.mockResolvedValue({
717
- ok: true,
718
- data: {
719
- session_started: true,
720
- session_id: 'new-session-123',
721
- persona: 'Wave',
722
- role: 'developer',
723
- project: { id: 'project-123', name: 'Test Project' },
724
- },
725
- });
726
-
727
- const result = await startWorkSession({ project_id: 'project-123' }, ctx);
728
-
729
- expect(result.result).not.toHaveProperty('git_url_normalized');
730
- });
731
-
732
- it('should include examples in git_url_normalized response', async () => {
733
- const ctx = createMockContext({ sessionId: null });
734
- mockApiClient.startSession.mockResolvedValue({
735
- ok: true,
736
- data: {
737
- session_started: true,
738
- session_id: 'new-session-123',
739
- persona: 'Wave',
740
- role: 'developer',
741
- project: { id: 'project-123', name: 'Test Project' },
742
- },
743
- });
744
-
745
- const result = await startWorkSession({ git_url: 'git@github.com:owner/repo' }, ctx);
746
-
747
- expect(result.result).toHaveProperty('git_url_normalized');
748
- const normalized = (result.result as { git_url_normalized: { examples: string[] } }).git_url_normalized;
749
- expect(normalized.examples).toBeDefined();
750
- expect(Array.isArray(normalized.examples)).toBe(true);
751
- expect(normalized.examples.length).toBeGreaterThan(0);
752
- });
753
- });
754
-
755
- // ============================================================================
756
- // reportTokenUsage Tests
757
- // ============================================================================
758
-
759
- describe('reportTokenUsage', () => {
760
- beforeEach(() => vi.clearAllMocks());
761
-
762
- it('should report token usage successfully with session', async () => {
763
- const ctx = createMockContext();
764
- mockApiClient.reportTokenUsage.mockResolvedValue({
765
- ok: true,
766
- data: {
767
- success: true,
768
- reported: {
769
- session_id: 'session-123',
770
- model: 'sonnet',
771
- input_tokens: 1000,
772
- output_tokens: 500,
773
- total_tokens: 1500,
774
- estimated_cost_usd: 0.0105,
775
- },
776
- task_attributed: true,
777
- task_id: 'task-123',
778
- },
779
- });
780
-
781
- const result = await reportTokenUsage(
782
- { input_tokens: 1000, output_tokens: 500, model: 'sonnet' },
783
- ctx
784
- );
785
-
786
- expect(result.result).toMatchObject({
787
- success: true,
788
- task_attributed: true,
789
- task_id: 'task-123',
790
- });
791
- expect(result.result).toHaveProperty('reported');
792
- expect(mockApiClient.reportTokenUsage).toHaveBeenCalledWith('session-123', {
793
- input_tokens: 1000,
794
- output_tokens: 500,
795
- model: 'sonnet',
796
- });
797
- });
798
-
799
- it('should default to sonnet model when not specified', async () => {
800
- const ctx = createMockContext();
801
- mockApiClient.reportTokenUsage.mockResolvedValue({
802
- ok: true,
803
- data: {
804
- success: true,
805
- reported: {
806
- session_id: 'session-123',
807
- model: 'sonnet',
808
- input_tokens: 1000,
809
- output_tokens: 500,
810
- total_tokens: 1500,
811
- estimated_cost_usd: 0.0105,
812
- },
813
- task_attributed: false,
814
- },
815
- });
816
-
817
- await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
818
-
819
- expect(mockApiClient.reportTokenUsage).toHaveBeenCalledWith('session-123', {
820
- input_tokens: 1000,
821
- output_tokens: 500,
822
- model: 'sonnet',
823
- });
824
- });
825
-
826
- it('should use session currentModel if available', async () => {
827
- const ctx = createMockContext({
828
- tokenUsage: {
829
- callCount: 0,
830
- totalTokens: 0,
831
- byTool: {},
832
- byModel: {},
833
- currentModel: 'opus',
834
- },
835
- });
836
- mockApiClient.reportTokenUsage.mockResolvedValue({
837
- ok: true,
838
- data: {
839
- success: true,
840
- reported: {
841
- session_id: 'session-123',
842
- model: 'opus',
843
- input_tokens: 1000,
844
- output_tokens: 500,
845
- total_tokens: 1500,
846
- estimated_cost_usd: 0.0525,
847
- },
848
- task_attributed: false,
849
- },
850
- });
851
-
852
- await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
853
-
854
- expect(mockApiClient.reportTokenUsage).toHaveBeenCalledWith('session-123', {
855
- input_tokens: 1000,
856
- output_tokens: 500,
857
- model: 'opus',
858
- });
859
- });
860
-
861
- it('should return error for negative token counts', async () => {
862
- const ctx = createMockContext();
863
-
864
- const result = await reportTokenUsage({ input_tokens: -100, output_tokens: 500 }, ctx);
865
-
866
- expect(result.result).toMatchObject({
867
- error: 'Token counts must be non-negative',
868
- });
869
- expect(mockApiClient.reportTokenUsage).not.toHaveBeenCalled();
870
- });
871
-
872
- it('should handle local-only reporting when no session', async () => {
873
- const ctx = createMockContext({ sessionId: null });
874
-
875
- const result = await reportTokenUsage(
876
- { input_tokens: 1000, output_tokens: 500, model: 'haiku' },
877
- ctx
878
- );
879
-
880
- expect(result.result).toMatchObject({
881
- success: true,
882
- });
883
- expect(result.result).toHaveProperty('reported');
884
- const reported = (result.result as { reported: { model: string } }).reported;
885
- expect(reported.model).toBe('haiku');
886
- expect(result.result).toHaveProperty('note');
887
- expect(mockApiClient.reportTokenUsage).not.toHaveBeenCalled();
888
- });
889
-
890
- it('should update local token tracking', async () => {
891
- const ctx = createMockContext({
892
- tokenUsage: {
893
- callCount: 5,
894
- totalTokens: 2500,
895
- byTool: {},
896
- byModel: { sonnet: { input: 1000, output: 500 } },
897
- currentModel: null,
898
- },
899
- });
900
- mockApiClient.reportTokenUsage.mockResolvedValue({
901
- ok: true,
902
- data: {
903
- success: true,
904
- reported: {
905
- session_id: 'session-123',
906
- model: 'sonnet',
907
- input_tokens: 1000,
908
- output_tokens: 500,
909
- total_tokens: 1500,
910
- estimated_cost_usd: 0.0105,
911
- },
912
- task_attributed: false,
913
- },
914
- });
915
-
916
- await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
917
-
918
- expect(ctx.updateSession).toHaveBeenCalledWith(
919
- expect.objectContaining({
920
- tokenUsage: expect.objectContaining({
921
- callCount: 6,
922
- totalTokens: 4000,
923
- byModel: { sonnet: { input: 2000, output: 1000 } },
924
- }),
925
- })
926
- );
927
- });
928
-
929
- it('should handle backend failure gracefully', async () => {
930
- const ctx = createMockContext();
931
- mockApiClient.reportTokenUsage.mockResolvedValue({
932
- ok: false,
933
- error: 'Server error',
934
- });
935
-
936
- const result = await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
937
-
938
- // Should still succeed with local calculation
939
- expect(result.result).toMatchObject({
940
- success: true,
941
- });
942
- expect(result.result).toHaveProperty('warning');
943
- });
944
-
945
- it('should indicate when task attribution succeeds', async () => {
946
- const ctx = createMockContext();
947
- mockApiClient.reportTokenUsage.mockResolvedValue({
948
- ok: true,
949
- data: {
950
- success: true,
951
- reported: {
952
- session_id: 'session-123',
953
- model: 'sonnet',
954
- input_tokens: 1000,
955
- output_tokens: 500,
956
- total_tokens: 1500,
957
- estimated_cost_usd: 0.0105,
958
- },
959
- task_attributed: true,
960
- task_id: 'task-abc123',
961
- },
962
- });
963
-
964
- const result = await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
965
-
966
- expect(result.result).toMatchObject({
967
- task_attributed: true,
968
- task_id: 'task-abc123',
969
- });
970
- expect((result.result as { note: string }).note).toContain('attributed to current task');
971
- });
972
-
973
- it('should indicate when no task to attribute to', async () => {
974
- const ctx = createMockContext();
975
- mockApiClient.reportTokenUsage.mockResolvedValue({
976
- ok: true,
977
- data: {
978
- success: true,
979
- reported: {
980
- session_id: 'session-123',
981
- model: 'sonnet',
982
- input_tokens: 1000,
983
- output_tokens: 500,
984
- total_tokens: 1500,
985
- estimated_cost_usd: 0.0105,
986
- },
987
- task_attributed: false,
988
- },
989
- });
990
-
991
- const result = await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
992
-
993
- expect(result.result).toMatchObject({
994
- task_attributed: false,
995
- });
996
- expect((result.result as { note: string }).note).toContain('No active task');
997
- });
998
- });
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
+ // Git URL normalization messaging tests
632
+ it('should include git_url_normalized when URL is normalized (SSH format)', async () => {
633
+ const ctx = createMockContext({ sessionId: null });
634
+ mockApiClient.startSession.mockResolvedValue({
635
+ ok: true,
636
+ data: {
637
+ session_started: true,
638
+ session_id: 'new-session-123',
639
+ persona: 'Wave',
640
+ role: 'developer',
641
+ project: { id: 'project-123', name: 'Test Project', git_url: 'https://github.com/owner/repo' },
642
+ },
643
+ });
644
+
645
+ const result = await startWorkSession({ git_url: 'git@github.com:owner/repo.git' }, ctx);
646
+
647
+ expect(result.result).toHaveProperty('git_url_normalized');
648
+ const normalized = (result.result as { git_url_normalized: { original: string; normalized: string; message: string } }).git_url_normalized;
649
+ expect(normalized.original).toBe('git@github.com:owner/repo.git');
650
+ expect(normalized.normalized).toBe('https://github.com/owner/repo');
651
+ expect(normalized.message).toContain('normalized');
652
+ });
653
+
654
+ it('should include git_url_normalized when URL has .git suffix', async () => {
655
+ const ctx = createMockContext({ sessionId: null });
656
+ mockApiClient.startSession.mockResolvedValue({
657
+ ok: true,
658
+ data: {
659
+ session_started: true,
660
+ session_id: 'new-session-123',
661
+ persona: 'Wave',
662
+ role: 'developer',
663
+ project: { id: 'project-123', name: 'Test Project' },
664
+ },
665
+ });
666
+
667
+ const result = await startWorkSession({ git_url: 'https://github.com/owner/repo.git' }, ctx);
668
+
669
+ expect(result.result).toHaveProperty('git_url_normalized');
670
+ const normalized = (result.result as { git_url_normalized: { original: string; normalized: string } }).git_url_normalized;
671
+ expect(normalized.original).toBe('https://github.com/owner/repo.git');
672
+ expect(normalized.normalized).toBe('https://github.com/owner/repo');
673
+ });
674
+
675
+ it('should include git_url_normalized when URL has different casing', async () => {
676
+ const ctx = createMockContext({ sessionId: null });
677
+ mockApiClient.startSession.mockResolvedValue({
678
+ ok: true,
679
+ data: {
680
+ session_started: true,
681
+ session_id: 'new-session-123',
682
+ persona: 'Wave',
683
+ role: 'developer',
684
+ project: { id: 'project-123', name: 'Test Project' },
685
+ },
686
+ });
687
+
688
+ const result = await startWorkSession({ git_url: 'https://GitHub.COM/OWNER/Repo' }, ctx);
689
+
690
+ expect(result.result).toHaveProperty('git_url_normalized');
691
+ const normalized = (result.result as { git_url_normalized: { original: string; normalized: string } }).git_url_normalized;
692
+ expect(normalized.original).toBe('https://GitHub.COM/OWNER/Repo');
693
+ expect(normalized.normalized).toBe('https://github.com/owner/repo');
694
+ });
695
+
696
+ it('should NOT include git_url_normalized when URL is already normalized', async () => {
697
+ const ctx = createMockContext({ sessionId: null });
698
+ mockApiClient.startSession.mockResolvedValue({
699
+ ok: true,
700
+ data: {
701
+ session_started: true,
702
+ session_id: 'new-session-123',
703
+ persona: 'Wave',
704
+ role: 'developer',
705
+ project: { id: 'project-123', name: 'Test Project' },
706
+ },
707
+ });
708
+
709
+ const result = await startWorkSession({ git_url: 'https://github.com/owner/repo' }, ctx);
710
+
711
+ expect(result.result).not.toHaveProperty('git_url_normalized');
712
+ });
713
+
714
+ it('should NOT include git_url_normalized when using project_id instead of git_url', async () => {
715
+ const ctx = createMockContext({ sessionId: null });
716
+ mockApiClient.startSession.mockResolvedValue({
717
+ ok: true,
718
+ data: {
719
+ session_started: true,
720
+ session_id: 'new-session-123',
721
+ persona: 'Wave',
722
+ role: 'developer',
723
+ project: { id: 'project-123', name: 'Test Project' },
724
+ },
725
+ });
726
+
727
+ const result = await startWorkSession({ project_id: 'project-123' }, ctx);
728
+
729
+ expect(result.result).not.toHaveProperty('git_url_normalized');
730
+ });
731
+
732
+ it('should include examples in git_url_normalized response', async () => {
733
+ const ctx = createMockContext({ sessionId: null });
734
+ mockApiClient.startSession.mockResolvedValue({
735
+ ok: true,
736
+ data: {
737
+ session_started: true,
738
+ session_id: 'new-session-123',
739
+ persona: 'Wave',
740
+ role: 'developer',
741
+ project: { id: 'project-123', name: 'Test Project' },
742
+ },
743
+ });
744
+
745
+ const result = await startWorkSession({ git_url: 'git@github.com:owner/repo' }, ctx);
746
+
747
+ expect(result.result).toHaveProperty('git_url_normalized');
748
+ const normalized = (result.result as { git_url_normalized: { examples: string[] } }).git_url_normalized;
749
+ expect(normalized.examples).toBeDefined();
750
+ expect(Array.isArray(normalized.examples)).toBe(true);
751
+ expect(normalized.examples.length).toBeGreaterThan(0);
752
+ });
753
+ });
754
+
755
+ // ============================================================================
756
+ // reportTokenUsage Tests
757
+ // ============================================================================
758
+
759
+ describe('reportTokenUsage', () => {
760
+ beforeEach(() => vi.clearAllMocks());
761
+
762
+ it('should report token usage successfully with session', async () => {
763
+ const ctx = createMockContext();
764
+ mockApiClient.reportTokenUsage.mockResolvedValue({
765
+ ok: true,
766
+ data: {
767
+ success: true,
768
+ reported: {
769
+ session_id: 'session-123',
770
+ model: 'sonnet',
771
+ input_tokens: 1000,
772
+ output_tokens: 500,
773
+ total_tokens: 1500,
774
+ estimated_cost_usd: 0.0105,
775
+ },
776
+ task_attributed: true,
777
+ task_id: 'task-123',
778
+ },
779
+ });
780
+
781
+ const result = await reportTokenUsage(
782
+ { input_tokens: 1000, output_tokens: 500, model: 'sonnet' },
783
+ ctx
784
+ );
785
+
786
+ expect(result.result).toMatchObject({
787
+ success: true,
788
+ task_attributed: true,
789
+ task_id: 'task-123',
790
+ });
791
+ expect(result.result).toHaveProperty('reported');
792
+ expect(mockApiClient.reportTokenUsage).toHaveBeenCalledWith('session-123', {
793
+ input_tokens: 1000,
794
+ output_tokens: 500,
795
+ model: 'sonnet',
796
+ });
797
+ });
798
+
799
+ it('should default to sonnet model when not specified', async () => {
800
+ const ctx = createMockContext();
801
+ mockApiClient.reportTokenUsage.mockResolvedValue({
802
+ ok: true,
803
+ data: {
804
+ success: true,
805
+ reported: {
806
+ session_id: 'session-123',
807
+ model: 'sonnet',
808
+ input_tokens: 1000,
809
+ output_tokens: 500,
810
+ total_tokens: 1500,
811
+ estimated_cost_usd: 0.0105,
812
+ },
813
+ task_attributed: false,
814
+ },
815
+ });
816
+
817
+ await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
818
+
819
+ expect(mockApiClient.reportTokenUsage).toHaveBeenCalledWith('session-123', {
820
+ input_tokens: 1000,
821
+ output_tokens: 500,
822
+ model: 'sonnet',
823
+ });
824
+ });
825
+
826
+ it('should use session currentModel if available', async () => {
827
+ const ctx = createMockContext({
828
+ tokenUsage: {
829
+ callCount: 0,
830
+ totalTokens: 0,
831
+ byTool: {},
832
+ byModel: {},
833
+ currentModel: 'opus',
834
+ },
835
+ });
836
+ mockApiClient.reportTokenUsage.mockResolvedValue({
837
+ ok: true,
838
+ data: {
839
+ success: true,
840
+ reported: {
841
+ session_id: 'session-123',
842
+ model: 'opus',
843
+ input_tokens: 1000,
844
+ output_tokens: 500,
845
+ total_tokens: 1500,
846
+ estimated_cost_usd: 0.0525,
847
+ },
848
+ task_attributed: false,
849
+ },
850
+ });
851
+
852
+ await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
853
+
854
+ expect(mockApiClient.reportTokenUsage).toHaveBeenCalledWith('session-123', {
855
+ input_tokens: 1000,
856
+ output_tokens: 500,
857
+ model: 'opus',
858
+ });
859
+ });
860
+
861
+ it('should return error for negative token counts', async () => {
862
+ const ctx = createMockContext();
863
+
864
+ const result = await reportTokenUsage({ input_tokens: -100, output_tokens: 500 }, ctx);
865
+
866
+ expect(result.result).toMatchObject({
867
+ error: 'Token counts must be non-negative',
868
+ });
869
+ expect(mockApiClient.reportTokenUsage).not.toHaveBeenCalled();
870
+ });
871
+
872
+ it('should handle local-only reporting when no session', async () => {
873
+ const ctx = createMockContext({ sessionId: null });
874
+
875
+ const result = await reportTokenUsage(
876
+ { input_tokens: 1000, output_tokens: 500, model: 'haiku' },
877
+ ctx
878
+ );
879
+
880
+ expect(result.result).toMatchObject({
881
+ success: true,
882
+ });
883
+ expect(result.result).toHaveProperty('reported');
884
+ const reported = (result.result as { reported: { model: string } }).reported;
885
+ expect(reported.model).toBe('haiku');
886
+ expect(result.result).toHaveProperty('note');
887
+ expect(mockApiClient.reportTokenUsage).not.toHaveBeenCalled();
888
+ });
889
+
890
+ it('should update local token tracking', async () => {
891
+ const ctx = createMockContext({
892
+ tokenUsage: {
893
+ callCount: 5,
894
+ totalTokens: 2500,
895
+ byTool: {},
896
+ byModel: { sonnet: { input: 1000, output: 500 } },
897
+ currentModel: null,
898
+ },
899
+ });
900
+ mockApiClient.reportTokenUsage.mockResolvedValue({
901
+ ok: true,
902
+ data: {
903
+ success: true,
904
+ reported: {
905
+ session_id: 'session-123',
906
+ model: 'sonnet',
907
+ input_tokens: 1000,
908
+ output_tokens: 500,
909
+ total_tokens: 1500,
910
+ estimated_cost_usd: 0.0105,
911
+ },
912
+ task_attributed: false,
913
+ },
914
+ });
915
+
916
+ await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
917
+
918
+ expect(ctx.updateSession).toHaveBeenCalledWith(
919
+ expect.objectContaining({
920
+ tokenUsage: expect.objectContaining({
921
+ callCount: 6,
922
+ totalTokens: 4000,
923
+ byModel: { sonnet: { input: 2000, output: 1000 } },
924
+ }),
925
+ })
926
+ );
927
+ });
928
+
929
+ it('should handle backend failure gracefully', async () => {
930
+ const ctx = createMockContext();
931
+ mockApiClient.reportTokenUsage.mockResolvedValue({
932
+ ok: false,
933
+ error: 'Server error',
934
+ });
935
+
936
+ const result = await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
937
+
938
+ // Should still succeed with local calculation
939
+ expect(result.result).toMatchObject({
940
+ success: true,
941
+ });
942
+ expect(result.result).toHaveProperty('warning');
943
+ });
944
+
945
+ it('should indicate when task attribution succeeds', async () => {
946
+ const ctx = createMockContext();
947
+ mockApiClient.reportTokenUsage.mockResolvedValue({
948
+ ok: true,
949
+ data: {
950
+ success: true,
951
+ reported: {
952
+ session_id: 'session-123',
953
+ model: 'sonnet',
954
+ input_tokens: 1000,
955
+ output_tokens: 500,
956
+ total_tokens: 1500,
957
+ estimated_cost_usd: 0.0105,
958
+ },
959
+ task_attributed: true,
960
+ task_id: 'task-abc123',
961
+ },
962
+ });
963
+
964
+ const result = await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
965
+
966
+ expect(result.result).toMatchObject({
967
+ task_attributed: true,
968
+ task_id: 'task-abc123',
969
+ });
970
+ expect((result.result as { note: string }).note).toContain('attributed to current task');
971
+ });
972
+
973
+ it('should indicate when no task to attribute to', async () => {
974
+ const ctx = createMockContext();
975
+ mockApiClient.reportTokenUsage.mockResolvedValue({
976
+ ok: true,
977
+ data: {
978
+ success: true,
979
+ reported: {
980
+ session_id: 'session-123',
981
+ model: 'sonnet',
982
+ input_tokens: 1000,
983
+ output_tokens: 500,
984
+ total_tokens: 1500,
985
+ estimated_cost_usd: 0.0105,
986
+ },
987
+ task_attributed: false,
988
+ },
989
+ });
990
+
991
+ const result = await reportTokenUsage({ input_tokens: 1000, output_tokens: 500 }, ctx);
992
+
993
+ expect(result.result).toMatchObject({
994
+ task_attributed: false,
995
+ });
996
+ expect((result.result as { note: string }).note).toContain('No active task');
997
+ });
998
+ });