@vibescope/mcp-server 0.0.1

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 (170) hide show
  1. package/README.md +98 -0
  2. package/dist/cli.d.ts +34 -0
  3. package/dist/cli.js +356 -0
  4. package/dist/cli.test.d.ts +1 -0
  5. package/dist/cli.test.js +367 -0
  6. package/dist/handlers/__test-utils__.d.ts +72 -0
  7. package/dist/handlers/__test-utils__.js +176 -0
  8. package/dist/handlers/blockers.d.ts +18 -0
  9. package/dist/handlers/blockers.js +81 -0
  10. package/dist/handlers/bodies-of-work.d.ts +34 -0
  11. package/dist/handlers/bodies-of-work.js +614 -0
  12. package/dist/handlers/checkouts.d.ts +37 -0
  13. package/dist/handlers/checkouts.js +377 -0
  14. package/dist/handlers/cost.d.ts +39 -0
  15. package/dist/handlers/cost.js +247 -0
  16. package/dist/handlers/decisions.d.ts +16 -0
  17. package/dist/handlers/decisions.js +64 -0
  18. package/dist/handlers/deployment.d.ts +36 -0
  19. package/dist/handlers/deployment.js +1062 -0
  20. package/dist/handlers/discovery.d.ts +14 -0
  21. package/dist/handlers/discovery.js +870 -0
  22. package/dist/handlers/fallback.d.ts +18 -0
  23. package/dist/handlers/fallback.js +216 -0
  24. package/dist/handlers/findings.d.ts +18 -0
  25. package/dist/handlers/findings.js +110 -0
  26. package/dist/handlers/git-issues.d.ts +22 -0
  27. package/dist/handlers/git-issues.js +247 -0
  28. package/dist/handlers/ideas.d.ts +19 -0
  29. package/dist/handlers/ideas.js +188 -0
  30. package/dist/handlers/index.d.ts +29 -0
  31. package/dist/handlers/index.js +65 -0
  32. package/dist/handlers/knowledge-query.d.ts +22 -0
  33. package/dist/handlers/knowledge-query.js +253 -0
  34. package/dist/handlers/knowledge.d.ts +12 -0
  35. package/dist/handlers/knowledge.js +108 -0
  36. package/dist/handlers/milestones.d.ts +20 -0
  37. package/dist/handlers/milestones.js +179 -0
  38. package/dist/handlers/organizations.d.ts +36 -0
  39. package/dist/handlers/organizations.js +428 -0
  40. package/dist/handlers/progress.d.ts +14 -0
  41. package/dist/handlers/progress.js +149 -0
  42. package/dist/handlers/project.d.ts +20 -0
  43. package/dist/handlers/project.js +278 -0
  44. package/dist/handlers/requests.d.ts +16 -0
  45. package/dist/handlers/requests.js +131 -0
  46. package/dist/handlers/roles.d.ts +30 -0
  47. package/dist/handlers/roles.js +281 -0
  48. package/dist/handlers/session.d.ts +20 -0
  49. package/dist/handlers/session.js +791 -0
  50. package/dist/handlers/tasks.d.ts +52 -0
  51. package/dist/handlers/tasks.js +1111 -0
  52. package/dist/handlers/tasks.test.d.ts +1 -0
  53. package/dist/handlers/tasks.test.js +431 -0
  54. package/dist/handlers/types.d.ts +94 -0
  55. package/dist/handlers/types.js +1 -0
  56. package/dist/handlers/validation.d.ts +16 -0
  57. package/dist/handlers/validation.js +188 -0
  58. package/dist/index.d.ts +2 -0
  59. package/dist/index.js +2707 -0
  60. package/dist/knowledge.d.ts +6 -0
  61. package/dist/knowledge.js +121 -0
  62. package/dist/tools.d.ts +2 -0
  63. package/dist/tools.js +2498 -0
  64. package/dist/utils.d.ts +149 -0
  65. package/dist/utils.js +317 -0
  66. package/dist/utils.test.d.ts +1 -0
  67. package/dist/utils.test.js +532 -0
  68. package/dist/validators.d.ts +35 -0
  69. package/dist/validators.js +111 -0
  70. package/dist/validators.test.d.ts +1 -0
  71. package/dist/validators.test.js +176 -0
  72. package/package.json +44 -0
  73. package/src/cli.test.ts +442 -0
  74. package/src/cli.ts +439 -0
  75. package/src/handlers/__test-utils__.ts +217 -0
  76. package/src/handlers/blockers.test.ts +390 -0
  77. package/src/handlers/blockers.ts +110 -0
  78. package/src/handlers/bodies-of-work.test.ts +1276 -0
  79. package/src/handlers/bodies-of-work.ts +783 -0
  80. package/src/handlers/cost.test.ts +436 -0
  81. package/src/handlers/cost.ts +322 -0
  82. package/src/handlers/decisions.test.ts +401 -0
  83. package/src/handlers/decisions.ts +86 -0
  84. package/src/handlers/deployment.test.ts +516 -0
  85. package/src/handlers/deployment.ts +1289 -0
  86. package/src/handlers/discovery.test.ts +254 -0
  87. package/src/handlers/discovery.ts +969 -0
  88. package/src/handlers/fallback.test.ts +687 -0
  89. package/src/handlers/fallback.ts +260 -0
  90. package/src/handlers/findings.test.ts +565 -0
  91. package/src/handlers/findings.ts +153 -0
  92. package/src/handlers/ideas.test.ts +753 -0
  93. package/src/handlers/ideas.ts +247 -0
  94. package/src/handlers/index.ts +69 -0
  95. package/src/handlers/milestones.test.ts +584 -0
  96. package/src/handlers/milestones.ts +217 -0
  97. package/src/handlers/organizations.test.ts +997 -0
  98. package/src/handlers/organizations.ts +550 -0
  99. package/src/handlers/progress.test.ts +369 -0
  100. package/src/handlers/progress.ts +188 -0
  101. package/src/handlers/project.test.ts +562 -0
  102. package/src/handlers/project.ts +352 -0
  103. package/src/handlers/requests.test.ts +531 -0
  104. package/src/handlers/requests.ts +150 -0
  105. package/src/handlers/session.test.ts +459 -0
  106. package/src/handlers/session.ts +912 -0
  107. package/src/handlers/tasks.test.ts +602 -0
  108. package/src/handlers/tasks.ts +1393 -0
  109. package/src/handlers/types.ts +88 -0
  110. package/src/handlers/validation.test.ts +880 -0
  111. package/src/handlers/validation.ts +223 -0
  112. package/src/index.ts +3205 -0
  113. package/src/knowledge.ts +132 -0
  114. package/src/tmpclaude-0078-cwd +1 -0
  115. package/src/tmpclaude-0ee1-cwd +1 -0
  116. package/src/tmpclaude-2dd5-cwd +1 -0
  117. package/src/tmpclaude-344c-cwd +1 -0
  118. package/src/tmpclaude-3860-cwd +1 -0
  119. package/src/tmpclaude-4b63-cwd +1 -0
  120. package/src/tmpclaude-5c73-cwd +1 -0
  121. package/src/tmpclaude-5ee3-cwd +1 -0
  122. package/src/tmpclaude-6795-cwd +1 -0
  123. package/src/tmpclaude-709e-cwd +1 -0
  124. package/src/tmpclaude-9839-cwd +1 -0
  125. package/src/tmpclaude-d829-cwd +1 -0
  126. package/src/tmpclaude-e072-cwd +1 -0
  127. package/src/tmpclaude-f6ee-cwd +1 -0
  128. package/src/utils.test.ts +681 -0
  129. package/src/utils.ts +375 -0
  130. package/src/validators.test.ts +223 -0
  131. package/src/validators.ts +122 -0
  132. package/tmpclaude-0439-cwd +1 -0
  133. package/tmpclaude-132f-cwd +1 -0
  134. package/tmpclaude-15bb-cwd +1 -0
  135. package/tmpclaude-165a-cwd +1 -0
  136. package/tmpclaude-1ba9-cwd +1 -0
  137. package/tmpclaude-21a3-cwd +1 -0
  138. package/tmpclaude-2a38-cwd +1 -0
  139. package/tmpclaude-2adf-cwd +1 -0
  140. package/tmpclaude-2f56-cwd +1 -0
  141. package/tmpclaude-3626-cwd +1 -0
  142. package/tmpclaude-3727-cwd +1 -0
  143. package/tmpclaude-40bc-cwd +1 -0
  144. package/tmpclaude-436f-cwd +1 -0
  145. package/tmpclaude-4783-cwd +1 -0
  146. package/tmpclaude-4b6d-cwd +1 -0
  147. package/tmpclaude-4ba4-cwd +1 -0
  148. package/tmpclaude-51e6-cwd +1 -0
  149. package/tmpclaude-5ecf-cwd +1 -0
  150. package/tmpclaude-6f97-cwd +1 -0
  151. package/tmpclaude-7fb2-cwd +1 -0
  152. package/tmpclaude-825c-cwd +1 -0
  153. package/tmpclaude-8baf-cwd +1 -0
  154. package/tmpclaude-8d9f-cwd +1 -0
  155. package/tmpclaude-975c-cwd +1 -0
  156. package/tmpclaude-9983-cwd +1 -0
  157. package/tmpclaude-a045-cwd +1 -0
  158. package/tmpclaude-ac4a-cwd +1 -0
  159. package/tmpclaude-b593-cwd +1 -0
  160. package/tmpclaude-b891-cwd +1 -0
  161. package/tmpclaude-c032-cwd +1 -0
  162. package/tmpclaude-cf43-cwd +1 -0
  163. package/tmpclaude-d040-cwd +1 -0
  164. package/tmpclaude-dcdd-cwd +1 -0
  165. package/tmpclaude-dcee-cwd +1 -0
  166. package/tmpclaude-e16b-cwd +1 -0
  167. package/tmpclaude-ecd2-cwd +1 -0
  168. package/tmpclaude-f48d-cwd +1 -0
  169. package/tsconfig.json +16 -0
  170. package/vitest.config.ts +13 -0
@@ -0,0 +1,1062 @@
1
+ /**
2
+ * Deployment Handlers
3
+ *
4
+ * Handles deployment coordination and requirements:
5
+ * - request_deployment
6
+ * - claim_deployment_validation
7
+ * - report_validation
8
+ * - check_deployment_status
9
+ * - start_deployment
10
+ * - complete_deployment
11
+ * - cancel_deployment
12
+ * - add_deployment_requirement
13
+ * - complete_deployment_requirement
14
+ * - get_deployment_requirements
15
+ */
16
+ import { ValidationError, validateRequired, validateUUID, validateEnvironment, } from '../validators.js';
17
+ export const requestDeployment = async (args, ctx) => {
18
+ const { project_id, environment = 'production', version_bump = 'patch', notes, git_ref } = args;
19
+ const { supabase, session } = ctx;
20
+ const currentSessionId = session.currentSessionId;
21
+ validateRequired(project_id, 'project_id');
22
+ validateUUID(project_id, 'project_id');
23
+ validateEnvironment(environment);
24
+ if (version_bump && !['patch', 'minor', 'major'].includes(version_bump)) {
25
+ throw new ValidationError('Invalid version_bump value', {
26
+ field: 'version_bump',
27
+ validValues: ['patch', 'minor', 'major'],
28
+ hint: 'Must be one of: patch, minor, major',
29
+ });
30
+ }
31
+ // Check for existing active deployment
32
+ const { data: existingDeployment } = await supabase
33
+ .from('deployments')
34
+ .select('id, status')
35
+ .eq('project_id', project_id)
36
+ .not('status', 'in', '("deployed","failed")')
37
+ .single();
38
+ if (existingDeployment) {
39
+ return {
40
+ result: {
41
+ success: false,
42
+ error: 'A deployment is already in progress',
43
+ existing_deployment_id: existingDeployment.id,
44
+ existing_status: existingDeployment.status,
45
+ hint: 'Wait for the current deployment to complete or cancel it first',
46
+ },
47
+ };
48
+ }
49
+ // Check for unvalidated completed tasks
50
+ const { data: unvalidatedTasks } = await supabase
51
+ .from('tasks')
52
+ .select('id, title, completed_at, completed_by_session_id')
53
+ .eq('project_id', project_id)
54
+ .eq('status', 'completed')
55
+ .is('validated_at', null)
56
+ .order('completed_at', { ascending: true });
57
+ if (unvalidatedTasks && unvalidatedTasks.length > 0) {
58
+ return {
59
+ result: {
60
+ success: false,
61
+ error: 'Cannot deploy: There are unvalidated completed tasks',
62
+ unvalidated_tasks: unvalidatedTasks.map(t => ({
63
+ id: t.id,
64
+ title: t.title,
65
+ completed_at: t.completed_at,
66
+ })),
67
+ unvalidated_count: unvalidatedTasks.length,
68
+ hint: 'All completed tasks must be validated before deployment. Use validate_task to review each task.',
69
+ action: `Call validate_task(task_id: "${unvalidatedTasks[0].id}", approved: true/false, validation_notes: "...")`,
70
+ },
71
+ };
72
+ }
73
+ // Get current version from project
74
+ const { data: project } = await supabase
75
+ .from('projects')
76
+ .select('current_version')
77
+ .eq('id', project_id)
78
+ .single();
79
+ const currentVersion = project?.current_version || '0.0.0';
80
+ // Create new deployment
81
+ const { data: deployment, error } = await supabase
82
+ .from('deployments')
83
+ .insert({
84
+ project_id,
85
+ environment,
86
+ version_bump,
87
+ notes,
88
+ git_ref,
89
+ requested_by: 'agent',
90
+ requesting_agent_session_id: currentSessionId,
91
+ })
92
+ .select()
93
+ .single();
94
+ if (error)
95
+ throw error;
96
+ // Auto-convert pending deployment requirements to tasks
97
+ const { data: pendingRequirements } = await supabase
98
+ .from('deployment_requirements')
99
+ .select('id, type, title, description, stage, blocking')
100
+ .eq('project_id', project_id)
101
+ .eq('status', 'pending')
102
+ .is('converted_task_id', null);
103
+ const convertedTasks = [];
104
+ if (pendingRequirements && pendingRequirements.length > 0) {
105
+ for (const req of pendingRequirements) {
106
+ const isDeployStage = req.stage === 'deployment';
107
+ const isBlocking = req.blocking ?? isDeployStage;
108
+ const titlePrefix = isBlocking
109
+ ? 'DEPLOY:'
110
+ : isDeployStage
111
+ ? 'DEPLOY:'
112
+ : req.stage === 'verification'
113
+ ? 'VERIFY:'
114
+ : 'PREP:';
115
+ // Create linked task
116
+ const { data: newTask } = await supabase
117
+ .from('tasks')
118
+ .insert({
119
+ project_id,
120
+ title: `${titlePrefix} ${req.title}`,
121
+ description: `[${req.type}] ${req.description || req.title}`,
122
+ priority: 1,
123
+ status: 'pending',
124
+ blocking: isBlocking,
125
+ created_by: 'agent',
126
+ created_by_session_id: currentSessionId,
127
+ })
128
+ .select('id')
129
+ .single();
130
+ if (newTask) {
131
+ // Link task to requirement WITHOUT changing status
132
+ // This keeps the requirement visible in the deployment steps list (permanent)
133
+ await supabase
134
+ .from('deployment_requirements')
135
+ .update({
136
+ converted_task_id: newTask.id,
137
+ })
138
+ .eq('id', req.id);
139
+ convertedTasks.push({
140
+ task_id: newTask.id,
141
+ requirement_id: req.id,
142
+ title: `${titlePrefix} ${req.title}`,
143
+ });
144
+ }
145
+ }
146
+ }
147
+ // Log progress
148
+ const convertedMsg = convertedTasks.length > 0
149
+ ? ` (${convertedTasks.length} requirements converted to tasks)`
150
+ : '';
151
+ await supabase.from('progress_logs').insert({
152
+ project_id,
153
+ summary: `Deployment requested for ${environment} (${version_bump} bump from ${currentVersion})${convertedMsg}`,
154
+ details: notes || undefined,
155
+ created_by: 'agent',
156
+ created_by_session_id: currentSessionId,
157
+ });
158
+ return {
159
+ result: {
160
+ success: true,
161
+ deployment_id: deployment.id,
162
+ status: deployment.status,
163
+ environment: deployment.environment,
164
+ version_bump,
165
+ current_version: currentVersion,
166
+ converted_requirements: convertedTasks.length,
167
+ converted_tasks: convertedTasks.length > 0 ? convertedTasks : undefined,
168
+ message: convertedTasks.length > 0
169
+ ? `Deployment created. ${convertedTasks.length} requirements converted to tasks. Run build/tests then call claim_deployment_validation.`
170
+ : 'Deployment created. Run build/tests then call claim_deployment_validation.',
171
+ },
172
+ };
173
+ };
174
+ export const claimDeploymentValidation = async (args, ctx) => {
175
+ const { project_id } = args;
176
+ const { supabase, session } = ctx;
177
+ const currentSessionId = session.currentSessionId;
178
+ validateRequired(project_id, 'project_id');
179
+ validateUUID(project_id, 'project_id');
180
+ // Find pending deployment
181
+ const { data: deployment, error: fetchError } = await supabase
182
+ .from('deployments')
183
+ .select('*')
184
+ .eq('project_id', project_id)
185
+ .eq('status', 'pending')
186
+ .single();
187
+ if (fetchError || !deployment) {
188
+ return {
189
+ result: {
190
+ success: false,
191
+ error: 'No pending deployment found',
192
+ hint: 'Use request_deployment to create a deployment first, or check_deployment_status to see current state',
193
+ },
194
+ };
195
+ }
196
+ // Claim validation
197
+ const { data: updated, error: updateError } = await supabase
198
+ .from('deployments')
199
+ .update({
200
+ status: 'validating',
201
+ validation_agent_session_id: currentSessionId,
202
+ validation_started_at: new Date().toISOString(),
203
+ })
204
+ .eq('id', deployment.id)
205
+ .eq('status', 'pending')
206
+ .select()
207
+ .single();
208
+ if (updateError || !updated) {
209
+ return {
210
+ result: {
211
+ success: false,
212
+ error: 'Failed to claim validation - deployment may have been claimed by another agent',
213
+ },
214
+ };
215
+ }
216
+ return {
217
+ result: {
218
+ success: true,
219
+ deployment_id: deployment.id,
220
+ status: 'validating',
221
+ message: 'Validation claimed. Run build and tests, then call report_validation with results.',
222
+ },
223
+ };
224
+ };
225
+ export const reportValidation = async (args, ctx) => {
226
+ const { project_id, build_passed, tests_passed, error_message } = args;
227
+ const { supabase, session } = ctx;
228
+ const currentSessionId = session.currentSessionId;
229
+ validateRequired(project_id, 'project_id');
230
+ validateUUID(project_id, 'project_id');
231
+ if (build_passed === undefined) {
232
+ throw new ValidationError('build_passed is required', {
233
+ field: 'build_passed',
234
+ hint: 'Set to true if the build succeeded, false otherwise',
235
+ });
236
+ }
237
+ // Find validating deployment
238
+ const { data: deployment, error: fetchError } = await supabase
239
+ .from('deployments')
240
+ .select('id')
241
+ .eq('project_id', project_id)
242
+ .eq('status', 'validating')
243
+ .single();
244
+ if (fetchError || !deployment) {
245
+ return {
246
+ result: {
247
+ success: false,
248
+ error: 'No deployment being validated. Use claim_deployment_validation first.',
249
+ },
250
+ };
251
+ }
252
+ const validationPassed = build_passed && (tests_passed !== false);
253
+ const newStatus = validationPassed ? 'ready' : 'failed';
254
+ const { error: updateError } = await supabase
255
+ .from('deployments')
256
+ .update({
257
+ status: newStatus,
258
+ build_passed,
259
+ tests_passed: tests_passed ?? null,
260
+ validation_completed_at: new Date().toISOString(),
261
+ validation_error: error_message || null,
262
+ })
263
+ .eq('id', deployment.id);
264
+ if (updateError)
265
+ throw updateError;
266
+ // Log result
267
+ await supabase.from('progress_logs').insert({
268
+ project_id,
269
+ summary: validationPassed
270
+ ? `Deployment validation passed - ready to deploy`
271
+ : `Deployment validation failed: ${error_message || 'build/tests failed'}`,
272
+ details: `Build: ${build_passed ? 'passed' : 'failed'}, Tests: ${tests_passed === undefined ? 'skipped' : tests_passed ? 'passed' : 'failed'}`,
273
+ created_by: 'agent',
274
+ created_by_session_id: currentSessionId,
275
+ });
276
+ // Auto-create task for failed validation
277
+ let createdTaskId = null;
278
+ if (!validationPassed) {
279
+ const failureType = !build_passed ? 'build' : 'test';
280
+ const { data: newTask } = await supabase
281
+ .from('tasks')
282
+ .insert({
283
+ project_id,
284
+ title: `Fix ${failureType} failure`,
285
+ description: error_message || `${failureType} failed during deployment validation`,
286
+ priority: 1,
287
+ status: 'pending',
288
+ created_by: 'agent',
289
+ created_by_session_id: currentSessionId,
290
+ estimated_minutes: 30,
291
+ })
292
+ .select('id')
293
+ .single();
294
+ createdTaskId = newTask?.id || null;
295
+ }
296
+ return {
297
+ result: {
298
+ success: true,
299
+ status: newStatus,
300
+ passed: validationPassed,
301
+ ...(createdTaskId && { fix_task_id: createdTaskId }),
302
+ },
303
+ };
304
+ };
305
+ export const checkDeploymentStatus = async (args, ctx) => {
306
+ const { project_id } = args;
307
+ const { supabase } = ctx;
308
+ validateRequired(project_id, 'project_id');
309
+ validateUUID(project_id, 'project_id');
310
+ // Get most recent deployment
311
+ const { data: deployment, error } = await supabase
312
+ .from('deployments')
313
+ .select('*')
314
+ .eq('project_id', project_id)
315
+ .order('created_at', { ascending: false })
316
+ .limit(1)
317
+ .single();
318
+ if (error || !deployment) {
319
+ return {
320
+ result: {
321
+ has_deployment: false,
322
+ message: 'No deployments found for this project',
323
+ },
324
+ };
325
+ }
326
+ // Auto-timeout stale deployments
327
+ const DEPLOYMENT_TIMEOUT_MS = {
328
+ pending: 30 * 60 * 1000,
329
+ validating: 15 * 60 * 1000,
330
+ ready: 30 * 60 * 1000,
331
+ deploying: 10 * 60 * 1000,
332
+ };
333
+ if (!['deployed', 'failed'].includes(deployment.status)) {
334
+ const timeout = DEPLOYMENT_TIMEOUT_MS[deployment.status];
335
+ if (timeout) {
336
+ const startTime = deployment.status === 'deploying'
337
+ ? deployment.deployment_started_at
338
+ : deployment.status === 'validating'
339
+ ? deployment.validation_started_at
340
+ : deployment.created_at;
341
+ if (startTime && Date.now() - new Date(startTime).getTime() > timeout) {
342
+ const timeoutError = `Timed out: deployment was stuck in '${deployment.status}' state for too long`;
343
+ await supabase
344
+ .from('deployments')
345
+ .update({
346
+ status: 'failed',
347
+ deployment_error: timeoutError,
348
+ deployment_completed_at: new Date().toISOString(),
349
+ })
350
+ .eq('id', deployment.id);
351
+ deployment.status = 'failed';
352
+ deployment.deployment_error = timeoutError;
353
+ }
354
+ }
355
+ }
356
+ return {
357
+ result: {
358
+ has_deployment: true,
359
+ deployment: {
360
+ id: deployment.id,
361
+ status: deployment.status,
362
+ environment: deployment.environment,
363
+ requested_by: deployment.requested_by,
364
+ build_passed: deployment.build_passed,
365
+ tests_passed: deployment.tests_passed,
366
+ validation_error: deployment.validation_error,
367
+ deployment_error: deployment.deployment_error,
368
+ deployment_summary: deployment.deployment_summary,
369
+ notes: deployment.notes,
370
+ git_ref: deployment.git_ref,
371
+ created_at: deployment.created_at,
372
+ validation_started_at: deployment.validation_started_at,
373
+ validation_completed_at: deployment.validation_completed_at,
374
+ deployment_started_at: deployment.deployment_started_at,
375
+ deployment_completed_at: deployment.deployment_completed_at,
376
+ },
377
+ },
378
+ };
379
+ };
380
+ export const startDeployment = async (args, ctx) => {
381
+ const { project_id } = args;
382
+ const { supabase, session } = ctx;
383
+ const currentSessionId = session.currentSessionId;
384
+ validateRequired(project_id, 'project_id');
385
+ validateUUID(project_id, 'project_id');
386
+ // Find ready deployment and project deployment instructions
387
+ const [deploymentResult, projectResult] = await Promise.all([
388
+ supabase
389
+ .from('deployments')
390
+ .select('id, environment')
391
+ .eq('project_id', project_id)
392
+ .eq('status', 'ready')
393
+ .single(),
394
+ supabase
395
+ .from('projects')
396
+ .select('deployment_instructions, git_main_branch')
397
+ .eq('id', project_id)
398
+ .single(),
399
+ ]);
400
+ if (deploymentResult.error || !deploymentResult.data) {
401
+ return {
402
+ result: {
403
+ success: false,
404
+ error: 'No deployment ready. Must pass validation first.',
405
+ },
406
+ };
407
+ }
408
+ const deployment = deploymentResult.data;
409
+ const project = projectResult.data;
410
+ const { error: updateError } = await supabase
411
+ .from('deployments')
412
+ .update({
413
+ status: 'deploying',
414
+ deployment_started_at: new Date().toISOString(),
415
+ })
416
+ .eq('id', deployment.id);
417
+ if (updateError)
418
+ throw updateError;
419
+ await supabase.from('progress_logs').insert({
420
+ project_id,
421
+ summary: `Deployment to ${deployment.environment} started`,
422
+ created_by: 'agent',
423
+ created_by_session_id: currentSessionId,
424
+ });
425
+ const result = {
426
+ success: true,
427
+ status: 'deploying',
428
+ env: deployment.environment,
429
+ };
430
+ if (project?.deployment_instructions) {
431
+ result.instructions = project.deployment_instructions;
432
+ }
433
+ else {
434
+ result.instructions = `No deployment instructions configured. Common steps:\n1. Push to ${project?.git_main_branch || 'main'} branch\n2. Or run your deploy command (e.g., fly deploy, vercel deploy)\n3. Call complete_deployment when done`;
435
+ }
436
+ return { result };
437
+ };
438
+ export const completeDeployment = async (args, ctx) => {
439
+ const { project_id, success, summary } = args;
440
+ const { supabase, session } = ctx;
441
+ const currentSessionId = session.currentSessionId;
442
+ validateRequired(project_id, 'project_id');
443
+ validateUUID(project_id, 'project_id');
444
+ if (success === undefined) {
445
+ throw new ValidationError('success is required', {
446
+ field: 'success',
447
+ hint: 'Set to true if deployment succeeded, false otherwise',
448
+ });
449
+ }
450
+ // Find deploying deployment
451
+ const { data: deployment, error: fetchError } = await supabase
452
+ .from('deployments')
453
+ .select('id, environment, version_bump')
454
+ .eq('project_id', project_id)
455
+ .eq('status', 'deploying')
456
+ .single();
457
+ if (fetchError || !deployment) {
458
+ return {
459
+ result: {
460
+ success: false,
461
+ error: 'No deployment in progress. Use start_deployment first.',
462
+ },
463
+ };
464
+ }
465
+ const newStatus = success ? 'deployed' : 'failed';
466
+ let newVersion = null;
467
+ // If successful, calculate and store new version
468
+ if (success) {
469
+ const { data: project } = await supabase
470
+ .from('projects')
471
+ .select('current_version')
472
+ .eq('id', project_id)
473
+ .single();
474
+ const currentVersion = project?.current_version || '0.0.0';
475
+ const versionBump = deployment.version_bump || 'patch';
476
+ const parts = currentVersion.split('.').map((p) => parseInt(p, 10) || 0);
477
+ let [major, minor, patch] = [parts[0] || 0, parts[1] || 0, parts[2] || 0];
478
+ switch (versionBump) {
479
+ case 'major':
480
+ major += 1;
481
+ minor = 0;
482
+ patch = 0;
483
+ break;
484
+ case 'minor':
485
+ minor += 1;
486
+ patch = 0;
487
+ break;
488
+ default: patch += 1;
489
+ }
490
+ newVersion = `${major}.${minor}.${patch}`;
491
+ await supabase
492
+ .from('projects')
493
+ .update({ current_version: newVersion })
494
+ .eq('id', project_id);
495
+ }
496
+ const { error: updateError } = await supabase
497
+ .from('deployments')
498
+ .update({
499
+ status: newStatus,
500
+ version: newVersion,
501
+ deployment_completed_at: new Date().toISOString(),
502
+ deployment_summary: summary || null,
503
+ })
504
+ .eq('id', deployment.id);
505
+ if (updateError)
506
+ throw updateError;
507
+ await supabase.from('progress_logs').insert({
508
+ project_id,
509
+ summary: success
510
+ ? `Deployed to ${deployment.environment}${newVersion ? ` v${newVersion}` : ''}`
511
+ : `Deployment failed`,
512
+ details: summary || undefined,
513
+ created_by: 'agent',
514
+ created_by_session_id: currentSessionId,
515
+ });
516
+ return {
517
+ result: {
518
+ success: true,
519
+ status: newStatus,
520
+ ...(newVersion && { version: newVersion }),
521
+ },
522
+ };
523
+ };
524
+ export const cancelDeployment = async (args, ctx) => {
525
+ const { project_id, reason } = args;
526
+ const { supabase, session } = ctx;
527
+ const currentSessionId = session.currentSessionId;
528
+ validateRequired(project_id, 'project_id');
529
+ validateUUID(project_id, 'project_id');
530
+ const { data: deployment, error: fetchError } = await supabase
531
+ .from('deployments')
532
+ .select('id')
533
+ .eq('project_id', project_id)
534
+ .not('status', 'in', '("deployed","failed")')
535
+ .single();
536
+ if (fetchError || !deployment) {
537
+ return { result: { success: false, error: 'No active deployment' } };
538
+ }
539
+ const { error: updateError } = await supabase
540
+ .from('deployments')
541
+ .update({
542
+ status: 'failed',
543
+ deployment_error: `Cancelled: ${reason || 'unspecified'}`,
544
+ deployment_completed_at: new Date().toISOString(),
545
+ })
546
+ .eq('id', deployment.id);
547
+ if (updateError)
548
+ throw updateError;
549
+ await supabase.from('progress_logs').insert({
550
+ project_id,
551
+ summary: `Deployment cancelled${reason ? `: ${reason}` : ''}`,
552
+ created_by: 'agent',
553
+ created_by_session_id: currentSessionId,
554
+ });
555
+ return { result: { success: true } };
556
+ };
557
+ export const addDeploymentRequirement = async (args, ctx) => {
558
+ const { project_id, type, title, description, file_path, stage = 'preparation', blocking = false } = args;
559
+ const { supabase, session } = ctx;
560
+ const currentSessionId = session.currentSessionId;
561
+ validateRequired(project_id, 'project_id');
562
+ validateUUID(project_id, 'project_id');
563
+ validateRequired(type, 'type');
564
+ validateRequired(title, 'title');
565
+ const validTypes = ['migration', 'env_var', 'config', 'manual', 'breaking_change', 'agent_task'];
566
+ if (!validTypes.includes(type)) {
567
+ throw new ValidationError(`type must be one of: ${validTypes.join(', ')}`);
568
+ }
569
+ const validStages = ['preparation', 'deployment', 'verification'];
570
+ if (!validStages.includes(stage)) {
571
+ throw new ValidationError(`stage must be one of: ${validStages.join(', ')}`);
572
+ }
573
+ const { data: requirement, error } = await supabase
574
+ .from('deployment_requirements')
575
+ .insert({
576
+ project_id,
577
+ type,
578
+ title,
579
+ description: description || null,
580
+ file_path: file_path || null,
581
+ stage,
582
+ blocking,
583
+ created_by_session_id: currentSessionId,
584
+ })
585
+ .select('id, type, title, stage, blocking')
586
+ .single();
587
+ if (error)
588
+ throw new Error(`Failed to add requirement: ${error.message}`);
589
+ const blockingText = blocking ? ' (BLOCKING)' : '';
590
+ await supabase.from('progress_logs').insert({
591
+ project_id,
592
+ summary: `Added ${stage} deployment requirement${blockingText}: ${title}`,
593
+ details: `Type: ${type}, Stage: ${stage}${blocking ? ', Blocking: true' : ''}${file_path ? `, File: ${file_path}` : ''}`,
594
+ created_by: 'agent',
595
+ created_by_session_id: currentSessionId,
596
+ });
597
+ const stageMessage = blocking
598
+ ? 'Will block all other work when converted to task.'
599
+ : stage === 'deployment'
600
+ ? 'Will run during deployment.'
601
+ : stage === 'verification'
602
+ ? 'Will run after deployment for verification.'
603
+ : 'Will run during preparation phase.';
604
+ return {
605
+ result: {
606
+ success: true,
607
+ requirement_id: requirement.id,
608
+ stage: requirement.stage,
609
+ message: `Added ${type} requirement. ${stageMessage}`,
610
+ },
611
+ };
612
+ };
613
+ export const completeDeploymentRequirement = async (args, ctx) => {
614
+ const { requirement_id } = args;
615
+ const { supabase, session } = ctx;
616
+ const currentSessionId = session.currentSessionId;
617
+ validateRequired(requirement_id, 'requirement_id');
618
+ validateUUID(requirement_id, 'requirement_id');
619
+ const { data: requirement, error: fetchError } = await supabase
620
+ .from('deployment_requirements')
621
+ .select('id, title, status')
622
+ .eq('id', requirement_id)
623
+ .single();
624
+ if (fetchError || !requirement) {
625
+ throw new Error('Requirement not found');
626
+ }
627
+ if (requirement.status !== 'pending') {
628
+ return {
629
+ result: {
630
+ success: false,
631
+ error: `Requirement is already ${requirement.status}`,
632
+ },
633
+ };
634
+ }
635
+ const { error: updateError } = await supabase
636
+ .from('deployment_requirements')
637
+ .update({
638
+ status: 'completed',
639
+ completed_at: new Date().toISOString(),
640
+ completed_by: currentSessionId || 'agent',
641
+ })
642
+ .eq('id', requirement_id);
643
+ if (updateError)
644
+ throw updateError;
645
+ return {
646
+ result: {
647
+ success: true,
648
+ requirement_id,
649
+ title: requirement.title,
650
+ },
651
+ };
652
+ };
653
+ export const getDeploymentRequirements = async (args, ctx) => {
654
+ const { project_id, status = 'pending', stage } = args;
655
+ const { supabase } = ctx;
656
+ validateRequired(project_id, 'project_id');
657
+ validateUUID(project_id, 'project_id');
658
+ let query = supabase
659
+ .from('deployment_requirements')
660
+ .select('id, type, title, description, file_path, status, stage, blocking, created_at, completed_at')
661
+ .eq('project_id', project_id)
662
+ .order('stage', { ascending: true })
663
+ .order('created_at', { ascending: false });
664
+ if (status !== 'all') {
665
+ query = query.eq('status', status);
666
+ }
667
+ if (stage && stage !== 'all') {
668
+ query = query.eq('stage', stage);
669
+ }
670
+ const { data: requirements, error } = await query;
671
+ if (error)
672
+ throw new Error(`Failed to fetch requirements: ${error.message}`);
673
+ const preparationPending = requirements?.filter(r => r.status === 'pending' && r.stage === 'preparation').length || 0;
674
+ const deploymentPending = requirements?.filter(r => r.status === 'pending' && r.stage === 'deployment').length || 0;
675
+ return {
676
+ result: {
677
+ requirements: requirements || [],
678
+ preparation_pending: preparationPending,
679
+ deployment_pending: deploymentPending,
680
+ deployment_blocked: preparationPending > 0 || deploymentPending > 0,
681
+ },
682
+ };
683
+ };
684
+ // ============================================================================
685
+ // Scheduled Deployments
686
+ // ============================================================================
687
+ export const scheduleDeployment = async (args, ctx) => {
688
+ const { project_id, environment = 'production', version_bump = 'patch', schedule_type = 'once', scheduled_at, auto_trigger = true, notes, git_ref, } = args;
689
+ const { supabase, session } = ctx;
690
+ const currentSessionId = session.currentSessionId;
691
+ validateRequired(project_id, 'project_id');
692
+ validateUUID(project_id, 'project_id');
693
+ validateRequired(scheduled_at, 'scheduled_at');
694
+ validateEnvironment(environment);
695
+ if (!['patch', 'minor', 'major'].includes(version_bump)) {
696
+ throw new ValidationError('Invalid version_bump value', {
697
+ field: 'version_bump',
698
+ validValues: ['patch', 'minor', 'major'],
699
+ });
700
+ }
701
+ if (!['once', 'daily', 'weekly', 'monthly'].includes(schedule_type)) {
702
+ throw new ValidationError('Invalid schedule_type value', {
703
+ field: 'schedule_type',
704
+ validValues: ['once', 'daily', 'weekly', 'monthly'],
705
+ });
706
+ }
707
+ // Parse and validate scheduled_at
708
+ const scheduledDate = new Date(scheduled_at);
709
+ if (isNaN(scheduledDate.getTime())) {
710
+ throw new ValidationError('Invalid scheduled_at date format', {
711
+ field: 'scheduled_at',
712
+ hint: 'Use ISO 8601 format, e.g., 2025-01-15T14:00:00Z',
713
+ });
714
+ }
715
+ if (scheduledDate.getTime() <= Date.now()) {
716
+ throw new ValidationError('scheduled_at must be in the future', {
717
+ field: 'scheduled_at',
718
+ });
719
+ }
720
+ // Create scheduled deployment
721
+ const { data: schedule, error } = await supabase
722
+ .from('scheduled_deployments')
723
+ .insert({
724
+ project_id,
725
+ environment,
726
+ version_bump,
727
+ schedule_type,
728
+ scheduled_at: scheduledDate.toISOString(),
729
+ auto_trigger,
730
+ notes: notes || null,
731
+ git_ref: git_ref || null,
732
+ created_by: 'agent',
733
+ created_by_session_id: currentSessionId,
734
+ })
735
+ .select('id, scheduled_at, schedule_type')
736
+ .single();
737
+ if (error)
738
+ throw new Error(`Failed to create schedule: ${error.message}`);
739
+ // Log progress
740
+ await supabase.from('progress_logs').insert({
741
+ project_id,
742
+ summary: `Scheduled ${schedule_type} deployment to ${environment} for ${scheduledDate.toISOString()}`,
743
+ details: `Auto-trigger: ${auto_trigger}, Version bump: ${version_bump}`,
744
+ created_by: 'agent',
745
+ created_by_session_id: currentSessionId,
746
+ });
747
+ return {
748
+ result: {
749
+ success: true,
750
+ schedule_id: schedule.id,
751
+ scheduled_at: schedule.scheduled_at,
752
+ schedule_type: schedule.schedule_type,
753
+ auto_trigger,
754
+ message: auto_trigger
755
+ ? 'Deployment scheduled. Will trigger automatically when time arrives.'
756
+ : 'Deployment scheduled. Manual trigger required from dashboard.',
757
+ },
758
+ };
759
+ };
760
+ export const getScheduledDeployments = async (args, ctx) => {
761
+ const { project_id, include_disabled = false } = args;
762
+ const { supabase } = ctx;
763
+ validateRequired(project_id, 'project_id');
764
+ validateUUID(project_id, 'project_id');
765
+ let query = supabase
766
+ .from('scheduled_deployments')
767
+ .select('*')
768
+ .eq('project_id', project_id)
769
+ .order('scheduled_at', { ascending: true });
770
+ if (!include_disabled) {
771
+ query = query.eq('enabled', true);
772
+ }
773
+ const { data: schedules, error } = await query;
774
+ if (error)
775
+ throw new Error(`Failed to fetch schedules: ${error.message}`);
776
+ const now = new Date();
777
+ const schedulesWithStatus = (schedules || []).map(s => ({
778
+ ...s,
779
+ is_due: s.enabled && new Date(s.scheduled_at) <= now,
780
+ }));
781
+ const dueCount = schedulesWithStatus.filter(s => s.is_due && s.auto_trigger).length;
782
+ return {
783
+ result: {
784
+ schedules: schedulesWithStatus,
785
+ count: schedulesWithStatus.length,
786
+ due_count: dueCount,
787
+ ...(dueCount > 0 && {
788
+ hint: 'There are due schedules. Call trigger_scheduled_deployment to execute.',
789
+ }),
790
+ },
791
+ };
792
+ };
793
+ export const updateScheduledDeployment = async (args, ctx) => {
794
+ const { schedule_id, environment, version_bump, schedule_type, scheduled_at, auto_trigger, enabled, notes, git_ref, } = args;
795
+ const { supabase } = ctx;
796
+ validateRequired(schedule_id, 'schedule_id');
797
+ validateUUID(schedule_id, 'schedule_id');
798
+ const updates = {};
799
+ if (environment !== undefined) {
800
+ validateEnvironment(environment);
801
+ updates.environment = environment;
802
+ }
803
+ if (version_bump !== undefined) {
804
+ if (!['patch', 'minor', 'major'].includes(version_bump)) {
805
+ throw new ValidationError('Invalid version_bump value');
806
+ }
807
+ updates.version_bump = version_bump;
808
+ }
809
+ if (schedule_type !== undefined) {
810
+ if (!['once', 'daily', 'weekly', 'monthly'].includes(schedule_type)) {
811
+ throw new ValidationError('Invalid schedule_type value');
812
+ }
813
+ updates.schedule_type = schedule_type;
814
+ }
815
+ if (scheduled_at !== undefined) {
816
+ const scheduledDate = new Date(scheduled_at);
817
+ if (isNaN(scheduledDate.getTime())) {
818
+ throw new ValidationError('Invalid scheduled_at date format');
819
+ }
820
+ updates.scheduled_at = scheduledDate.toISOString();
821
+ }
822
+ if (auto_trigger !== undefined)
823
+ updates.auto_trigger = auto_trigger;
824
+ if (enabled !== undefined)
825
+ updates.enabled = enabled;
826
+ if (notes !== undefined)
827
+ updates.notes = notes;
828
+ if (git_ref !== undefined)
829
+ updates.git_ref = git_ref;
830
+ if (Object.keys(updates).length === 0) {
831
+ return { result: { success: false, error: 'No updates provided' } };
832
+ }
833
+ const { error } = await supabase
834
+ .from('scheduled_deployments')
835
+ .update(updates)
836
+ .eq('id', schedule_id);
837
+ if (error)
838
+ throw new Error(`Failed to update schedule: ${error.message}`);
839
+ return { result: { success: true, schedule_id } };
840
+ };
841
+ export const deleteScheduledDeployment = async (args, ctx) => {
842
+ const { schedule_id } = args;
843
+ const { supabase } = ctx;
844
+ validateRequired(schedule_id, 'schedule_id');
845
+ validateUUID(schedule_id, 'schedule_id');
846
+ const { error } = await supabase
847
+ .from('scheduled_deployments')
848
+ .delete()
849
+ .eq('id', schedule_id);
850
+ if (error)
851
+ throw new Error(`Failed to delete schedule: ${error.message}`);
852
+ return { result: { success: true } };
853
+ };
854
+ export const triggerScheduledDeployment = async (args, ctx) => {
855
+ const { schedule_id } = args;
856
+ const { supabase, session } = ctx;
857
+ const currentSessionId = session.currentSessionId;
858
+ validateRequired(schedule_id, 'schedule_id');
859
+ validateUUID(schedule_id, 'schedule_id');
860
+ // Get the schedule
861
+ const { data: schedule, error: fetchError } = await supabase
862
+ .from('scheduled_deployments')
863
+ .select('*')
864
+ .eq('id', schedule_id)
865
+ .single();
866
+ if (fetchError || !schedule) {
867
+ return { result: { success: false, error: 'Schedule not found' } };
868
+ }
869
+ if (!schedule.enabled) {
870
+ return { result: { success: false, error: 'Schedule is disabled' } };
871
+ }
872
+ // Check for existing active deployment
873
+ const { data: existingDeployment } = await supabase
874
+ .from('deployments')
875
+ .select('id, status')
876
+ .eq('project_id', schedule.project_id)
877
+ .not('status', 'in', '("deployed","failed")')
878
+ .single();
879
+ if (existingDeployment) {
880
+ return {
881
+ result: {
882
+ success: false,
883
+ error: 'A deployment is already in progress',
884
+ existing_deployment_id: existingDeployment.id,
885
+ hint: 'Wait for current deployment to complete or cancel it first',
886
+ },
887
+ };
888
+ }
889
+ // Create the deployment (similar to request_deployment)
890
+ const { data: deployment, error: deployError } = await supabase
891
+ .from('deployments')
892
+ .insert({
893
+ project_id: schedule.project_id,
894
+ environment: schedule.environment,
895
+ version_bump: schedule.version_bump,
896
+ notes: schedule.notes,
897
+ git_ref: schedule.git_ref,
898
+ requested_by: 'agent',
899
+ requesting_agent_session_id: currentSessionId,
900
+ })
901
+ .select('id, status')
902
+ .single();
903
+ if (deployError)
904
+ throw new Error(`Failed to create deployment: ${deployError.message}`);
905
+ // Auto-convert pending deployment requirements to tasks
906
+ const { data: pendingRequirements } = await supabase
907
+ .from('deployment_requirements')
908
+ .select('id, type, title, description, stage, blocking')
909
+ .eq('project_id', schedule.project_id)
910
+ .eq('status', 'pending')
911
+ .is('converted_task_id', null);
912
+ const convertedTasks = [];
913
+ if (pendingRequirements && pendingRequirements.length > 0) {
914
+ for (const req of pendingRequirements) {
915
+ const isDeployStage = req.stage === 'deployment';
916
+ const isBlocking = req.blocking ?? isDeployStage;
917
+ const titlePrefix = isBlocking
918
+ ? 'DEPLOY:'
919
+ : isDeployStage
920
+ ? 'DEPLOY:'
921
+ : req.stage === 'verification'
922
+ ? 'VERIFY:'
923
+ : 'PREP:';
924
+ // Create linked task
925
+ const { data: newTask } = await supabase
926
+ .from('tasks')
927
+ .insert({
928
+ project_id: schedule.project_id,
929
+ title: `${titlePrefix} ${req.title}`,
930
+ description: `[${req.type}] ${req.description || req.title}`,
931
+ priority: 1,
932
+ status: 'pending',
933
+ blocking: isBlocking,
934
+ created_by: 'agent',
935
+ created_by_session_id: currentSessionId,
936
+ })
937
+ .select('id')
938
+ .single();
939
+ if (newTask) {
940
+ // Link task to requirement WITHOUT changing status
941
+ // This keeps the requirement visible in the deployment steps list (permanent)
942
+ await supabase
943
+ .from('deployment_requirements')
944
+ .update({
945
+ converted_task_id: newTask.id,
946
+ })
947
+ .eq('id', req.id);
948
+ convertedTasks.push({
949
+ task_id: newTask.id,
950
+ requirement_id: req.id,
951
+ title: `${titlePrefix} ${req.title}`,
952
+ });
953
+ }
954
+ }
955
+ }
956
+ // Update the schedule
957
+ const scheduleUpdates = {
958
+ last_triggered_at: new Date().toISOString(),
959
+ last_deployment_id: deployment.id,
960
+ trigger_count: schedule.trigger_count + 1,
961
+ };
962
+ // For recurring schedules, calculate next run time
963
+ if (schedule.schedule_type !== 'once') {
964
+ const currentScheduledAt = new Date(schedule.scheduled_at);
965
+ let nextScheduledAt;
966
+ switch (schedule.schedule_type) {
967
+ case 'daily':
968
+ nextScheduledAt = new Date(currentScheduledAt.getTime() + 24 * 60 * 60 * 1000);
969
+ break;
970
+ case 'weekly':
971
+ nextScheduledAt = new Date(currentScheduledAt.getTime() + 7 * 24 * 60 * 60 * 1000);
972
+ break;
973
+ case 'monthly':
974
+ nextScheduledAt = new Date(currentScheduledAt.getTime() + 30 * 24 * 60 * 60 * 1000);
975
+ break;
976
+ default:
977
+ nextScheduledAt = currentScheduledAt;
978
+ }
979
+ scheduleUpdates.scheduled_at = nextScheduledAt.toISOString();
980
+ }
981
+ else {
982
+ // One-time schedule, disable it
983
+ scheduleUpdates.enabled = false;
984
+ }
985
+ await supabase
986
+ .from('scheduled_deployments')
987
+ .update(scheduleUpdates)
988
+ .eq('id', schedule_id);
989
+ // Log progress
990
+ const convertedMsg = convertedTasks.length > 0
991
+ ? `, ${convertedTasks.length} requirements converted to tasks`
992
+ : '';
993
+ await supabase.from('progress_logs').insert({
994
+ project_id: schedule.project_id,
995
+ summary: `Triggered scheduled deployment to ${schedule.environment}${convertedMsg}`,
996
+ details: `Schedule: ${schedule.schedule_type}, Trigger #${schedule.trigger_count + 1}`,
997
+ created_by: 'agent',
998
+ created_by_session_id: currentSessionId,
999
+ });
1000
+ return {
1001
+ result: {
1002
+ success: true,
1003
+ deployment_id: deployment.id,
1004
+ schedule_id,
1005
+ schedule_type: schedule.schedule_type,
1006
+ next_scheduled_at: schedule.schedule_type !== 'once' ? scheduleUpdates.scheduled_at : null,
1007
+ converted_requirements: convertedTasks.length,
1008
+ converted_tasks: convertedTasks.length > 0 ? convertedTasks : undefined,
1009
+ message: convertedTasks.length > 0
1010
+ ? `Deployment created from schedule. ${convertedTasks.length} requirements converted to tasks. Run validation then deploy.`
1011
+ : 'Deployment created from schedule. Run validation then deploy.',
1012
+ },
1013
+ };
1014
+ };
1015
+ export const checkDueDeployments = async (args, ctx) => {
1016
+ const { project_id } = args;
1017
+ const { supabase } = ctx;
1018
+ validateRequired(project_id, 'project_id');
1019
+ validateUUID(project_id, 'project_id');
1020
+ // Find schedules that are due (enabled, auto_trigger, and scheduled_at <= now)
1021
+ const { data: dueSchedules, error } = await supabase
1022
+ .from('scheduled_deployments')
1023
+ .select('id, environment, version_bump, schedule_type, scheduled_at')
1024
+ .eq('project_id', project_id)
1025
+ .eq('enabled', true)
1026
+ .eq('auto_trigger', true)
1027
+ .lte('scheduled_at', new Date().toISOString())
1028
+ .order('scheduled_at', { ascending: true });
1029
+ if (error)
1030
+ throw new Error(`Failed to check schedules: ${error.message}`);
1031
+ return {
1032
+ result: {
1033
+ due_schedules: dueSchedules || [],
1034
+ count: dueSchedules?.length || 0,
1035
+ ...(dueSchedules && dueSchedules.length > 0 && {
1036
+ hint: `Call trigger_scheduled_deployment(schedule_id: "${dueSchedules[0].id}") to trigger the first due deployment`,
1037
+ }),
1038
+ },
1039
+ };
1040
+ };
1041
+ /**
1042
+ * Deployment handlers registry
1043
+ */
1044
+ export const deploymentHandlers = {
1045
+ request_deployment: requestDeployment,
1046
+ claim_deployment_validation: claimDeploymentValidation,
1047
+ report_validation: reportValidation,
1048
+ check_deployment_status: checkDeploymentStatus,
1049
+ start_deployment: startDeployment,
1050
+ complete_deployment: completeDeployment,
1051
+ cancel_deployment: cancelDeployment,
1052
+ add_deployment_requirement: addDeploymentRequirement,
1053
+ complete_deployment_requirement: completeDeploymentRequirement,
1054
+ get_deployment_requirements: getDeploymentRequirements,
1055
+ // Scheduled deployments
1056
+ schedule_deployment: scheduleDeployment,
1057
+ get_scheduled_deployments: getScheduledDeployments,
1058
+ update_scheduled_deployment: updateScheduledDeployment,
1059
+ delete_scheduled_deployment: deleteScheduledDeployment,
1060
+ trigger_scheduled_deployment: triggerScheduledDeployment,
1061
+ check_due_deployments: checkDueDeployments,
1062
+ };