@synth-deploy/server 0.1.0 → 1.1.0

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 (96) hide show
  1. package/dist/agent/envoy-client.d.ts +62 -7
  2. package/dist/agent/envoy-client.d.ts.map +1 -1
  3. package/dist/agent/envoy-client.js +56 -6
  4. package/dist/agent/envoy-client.js.map +1 -1
  5. package/dist/agent/stale-deployment-detector.js +1 -1
  6. package/dist/agent/stale-deployment-detector.js.map +1 -1
  7. package/dist/agent/synth-agent.d.ts +7 -5
  8. package/dist/agent/synth-agent.d.ts.map +1 -1
  9. package/dist/agent/synth-agent.js +42 -39
  10. package/dist/agent/synth-agent.js.map +1 -1
  11. package/dist/alert-webhooks/alert-parsers.d.ts +21 -0
  12. package/dist/alert-webhooks/alert-parsers.d.ts.map +1 -0
  13. package/dist/alert-webhooks/alert-parsers.js +184 -0
  14. package/dist/alert-webhooks/alert-parsers.js.map +1 -0
  15. package/dist/api/agent.d.ts +0 -6
  16. package/dist/api/agent.d.ts.map +1 -1
  17. package/dist/api/agent.js +6 -459
  18. package/dist/api/agent.js.map +1 -1
  19. package/dist/api/alert-webhooks.d.ts +13 -0
  20. package/dist/api/alert-webhooks.d.ts.map +1 -0
  21. package/dist/api/alert-webhooks.js +279 -0
  22. package/dist/api/alert-webhooks.js.map +1 -0
  23. package/dist/api/envoy-reports.js +2 -2
  24. package/dist/api/envoy-reports.js.map +1 -1
  25. package/dist/api/envoys.js +1 -1
  26. package/dist/api/envoys.js.map +1 -1
  27. package/dist/api/fleet.d.ts.map +1 -1
  28. package/dist/api/fleet.js +14 -15
  29. package/dist/api/fleet.js.map +1 -1
  30. package/dist/api/graph.js +3 -3
  31. package/dist/api/graph.js.map +1 -1
  32. package/dist/api/operations.d.ts +7 -0
  33. package/dist/api/operations.d.ts.map +1 -0
  34. package/dist/api/operations.js +1883 -0
  35. package/dist/api/operations.js.map +1 -0
  36. package/dist/api/partitions.js +1 -1
  37. package/dist/api/partitions.js.map +1 -1
  38. package/dist/api/schemas.d.ts +194 -10
  39. package/dist/api/schemas.d.ts.map +1 -1
  40. package/dist/api/schemas.js +38 -5
  41. package/dist/api/schemas.js.map +1 -1
  42. package/dist/api/system.d.ts.map +1 -1
  43. package/dist/api/system.js +22 -21
  44. package/dist/api/system.js.map +1 -1
  45. package/dist/artifact-analyzer.js +2 -2
  46. package/dist/artifact-analyzer.js.map +1 -1
  47. package/dist/fleet/fleet-executor.js +1 -1
  48. package/dist/fleet/fleet-executor.js.map +1 -1
  49. package/dist/graph/graph-executor.js +2 -2
  50. package/dist/graph/graph-executor.js.map +1 -1
  51. package/dist/index.js +44 -40
  52. package/dist/index.js.map +1 -1
  53. package/dist/mcp/resources.js +3 -3
  54. package/dist/mcp/resources.js.map +1 -1
  55. package/dist/mcp/tools.d.ts.map +1 -1
  56. package/dist/mcp/tools.js +2 -9
  57. package/dist/mcp/tools.js.map +1 -1
  58. package/dist/middleware/auth.js +1 -1
  59. package/dist/middleware/auth.js.map +1 -1
  60. package/package.json +1 -1
  61. package/src/agent/envoy-client.ts +107 -15
  62. package/src/agent/stale-deployment-detector.ts +1 -1
  63. package/src/agent/synth-agent.ts +59 -45
  64. package/src/alert-webhooks/alert-parsers.ts +291 -0
  65. package/src/api/agent.ts +9 -528
  66. package/src/api/alert-webhooks.ts +354 -0
  67. package/src/api/envoy-reports.ts +2 -2
  68. package/src/api/envoys.ts +1 -1
  69. package/src/api/fleet.ts +14 -15
  70. package/src/api/graph.ts +3 -3
  71. package/src/api/operations.ts +2240 -0
  72. package/src/api/partitions.ts +1 -1
  73. package/src/api/schemas.ts +43 -7
  74. package/src/api/system.ts +23 -21
  75. package/src/artifact-analyzer.ts +2 -2
  76. package/src/fleet/fleet-executor.ts +1 -1
  77. package/src/graph/graph-executor.ts +2 -2
  78. package/src/index.ts +46 -40
  79. package/src/mcp/resources.ts +3 -3
  80. package/src/mcp/tools.ts +5 -9
  81. package/src/middleware/auth.ts +1 -1
  82. package/tests/agent-mode.test.ts +5 -376
  83. package/tests/api-handlers.test.ts +27 -27
  84. package/tests/composite-operations.test.ts +557 -0
  85. package/tests/decision-diary.test.ts +62 -63
  86. package/tests/diary-reader.test.ts +14 -18
  87. package/tests/mcp-tools.test.ts +1 -1
  88. package/tests/orchestration.test.ts +34 -30
  89. package/tests/partition-isolation.test.ts +4 -9
  90. package/tests/rbac-enforcement.test.ts +8 -8
  91. package/tests/ui-journey.test.ts +9 -9
  92. package/dist/api/deployments.d.ts +0 -11
  93. package/dist/api/deployments.d.ts.map +0 -1
  94. package/dist/api/deployments.js +0 -1098
  95. package/dist/api/deployments.js.map +0 -1
  96. package/src/api/deployments.ts +0 -1347
@@ -1,1098 +0,0 @@
1
- import { generatePostmortem, generatePostmortemAsync } from "@synth-deploy/core";
2
- import { requirePermission } from "../middleware/permissions.js";
3
- import { CreateDeploymentSchema, ApproveDeploymentSchema, RejectDeploymentSchema, ModifyDeploymentPlanSchema, SubmitPlanSchema, DeploymentListQuerySchema, DebriefQuerySchema, ProgressEventSchema, ReplanDeploymentSchema, } from "./schemas.js";
4
- import { EnvoyClient } from "../agent/envoy-client.js";
5
- /**
6
- * REST API routes for deployments. These are the traditional (non-MCP) interface
7
- * for the web UI and integrations.
8
- */
9
- export function registerDeploymentRoutes(app, deployments, debrief, partitions, environments, artifactStore, settings, telemetry, progressStore, envoyClient, envoyRegistry, llm) {
10
- // Create a deployment (plan phase)
11
- app.post("/api/deployments", { preHandler: [requirePermission("deployment.create")] }, async (request, reply) => {
12
- const parsed = CreateDeploymentSchema.safeParse(request.body);
13
- if (!parsed.success) {
14
- return reply.status(400).send({ error: parsed.error.message });
15
- }
16
- const { artifactId, environmentId, partitionId, envoyId, version } = parsed.data;
17
- // Validate artifact exists
18
- const artifact = artifactStore.get(artifactId);
19
- if (!artifact) {
20
- return reply.status(404).send({ error: `Artifact not found: ${artifactId}` });
21
- }
22
- // Validate environment exists (optional when targeting a partition or envoy)
23
- const environment = environmentId ? environments.get(environmentId) : undefined;
24
- if (environmentId && !environment) {
25
- return reply.status(404).send({ error: `Environment not found: ${environmentId}` });
26
- }
27
- // Validate partition if provided
28
- const partition = partitionId ? partitions.get(partitionId) : undefined;
29
- if (partitionId && !partition) {
30
- return reply.status(404).send({ error: `Partition not found: ${partitionId}` });
31
- }
32
- // Validate envoy if provided
33
- const targetEnvoy = envoyId ? envoyRegistry?.get(envoyId) : undefined;
34
- if (envoyId && !targetEnvoy) {
35
- return reply.status(404).send({ error: `Envoy not found: ${envoyId}` });
36
- }
37
- // Resolve variables — partition vars are base, environment vars take precedence if present
38
- const envVars = environment ? environment.variables : {};
39
- const partitionVars = partition?.variables ?? {};
40
- const resolved = { ...partitionVars, ...envVars };
41
- const deployment = {
42
- id: crypto.randomUUID(),
43
- artifactId,
44
- environmentId,
45
- partitionId,
46
- envoyId: targetEnvoy?.id,
47
- version: version ?? "",
48
- status: "pending",
49
- variables: resolved,
50
- debriefEntryIds: [],
51
- createdAt: new Date(),
52
- };
53
- deployments.save(deployment);
54
- telemetry.record({ actor: (request.user?.email) ?? "anonymous", action: "deployment.created", target: { type: "deployment", id: deployment.id }, details: { artifactId, environmentId, partitionId, envoyId } });
55
- // Dispatch planning to the appropriate envoy asynchronously.
56
- // The envoy reasons about the deployment (read-only) and POSTs back a plan,
57
- // which transitions the deployment to awaiting_approval.
58
- if (envoyRegistry) {
59
- // Find the target envoy: explicit envoyId > environment-assigned > first available
60
- const planningEnvoy = targetEnvoy
61
- ?? (environment ? envoyRegistry.findForEnvironment(environment.name) : undefined)
62
- ?? envoyRegistry.list()[0];
63
- if (planningEnvoy) {
64
- const planningClient = new EnvoyClient(planningEnvoy.url);
65
- const environmentForPlanning = environment
66
- ? { id: environment.id, name: environment.name, variables: environment.variables }
67
- : { id: `direct:${planningEnvoy.id}`, name: planningEnvoy.name, variables: {} };
68
- planningClient.requestPlan({
69
- deploymentId: deployment.id,
70
- artifact: {
71
- id: artifact.id,
72
- name: artifact.name,
73
- type: artifact.type,
74
- analysis: {
75
- summary: artifact.analysis.summary,
76
- dependencies: artifact.analysis.dependencies,
77
- configurationExpectations: artifact.analysis.configurationExpectations,
78
- deploymentIntent: artifact.analysis.deploymentIntent,
79
- confidence: artifact.analysis.confidence,
80
- },
81
- },
82
- environment: environmentForPlanning,
83
- partition: partition
84
- ? { id: partition.id, name: partition.name, variables: partition.variables }
85
- : undefined,
86
- version: deployment.version,
87
- resolvedVariables: resolved,
88
- }).then((result) => {
89
- const dep = deployments.get(deployment.id);
90
- if (!dep || dep.status !== "pending")
91
- return;
92
- dep.plan = result.plan;
93
- dep.rollbackPlan = result.rollbackPlan;
94
- dep.envoyId = planningEnvoy.id;
95
- if (result.blocked) {
96
- // Unrecoverable precondition failures — block execution, do not present for approval
97
- dep.status = "failed";
98
- dep.failureReason = result.blockReason ?? "Plan blocked due to unrecoverable precondition failures";
99
- deployments.save(dep);
100
- debrief.record({
101
- partitionId: dep.partitionId ?? null,
102
- deploymentId: dep.id,
103
- agent: "envoy",
104
- decisionType: "plan-generation",
105
- decision: `Deployment plan blocked — infrastructure prerequisites not met`,
106
- reasoning: result.blockReason ?? result.plan.reasoning,
107
- context: { stepCount: result.plan.steps.length, envoyId: planningEnvoy.id, blocked: true },
108
- });
109
- }
110
- else {
111
- // Plan is valid — transition to awaiting_approval
112
- dep.status = "awaiting_approval";
113
- dep.recommendation = computeRecommendation(dep, deployments, result.assessmentSummary);
114
- deployments.save(dep);
115
- debrief.record({
116
- partitionId: dep.partitionId ?? null,
117
- deploymentId: dep.id,
118
- agent: "envoy",
119
- decisionType: "plan-generation",
120
- decision: `Deployment plan generated with ${result.plan.steps.length} steps`,
121
- reasoning: result.plan.reasoning,
122
- context: { stepCount: result.plan.steps.length, envoyId: planningEnvoy.id, delta: result.delta },
123
- });
124
- }
125
- }).catch((err) => {
126
- // Planning failed — mark deployment failed so UI doesn't wait forever
127
- const dep = deployments.get(deployment.id);
128
- if (!dep || dep.status !== "pending")
129
- return;
130
- dep.status = "failed";
131
- dep.failureReason = err instanceof Error ? err.message : "Planning failed";
132
- deployments.save(dep);
133
- debrief.record({
134
- partitionId: dep.partitionId ?? null,
135
- deploymentId: dep.id,
136
- agent: "server",
137
- decisionType: "deployment-failure",
138
- decision: "Envoy planning failed",
139
- reasoning: dep.failureReason,
140
- context: { error: dep.failureReason, envoyId: planningEnvoy.id },
141
- });
142
- });
143
- }
144
- }
145
- return reply.status(201).send({ deployment });
146
- });
147
- // Get deployment by ID
148
- app.get("/api/deployments/:id", { preHandler: [requirePermission("deployment.view")] }, async (request, reply) => {
149
- const deployment = deployments.get(request.params.id);
150
- if (!deployment) {
151
- return reply.status(404).send({ error: "Deployment not found" });
152
- }
153
- return {
154
- deployment,
155
- debrief: debrief.getByDeployment(deployment.id),
156
- };
157
- });
158
- // What's New — compare deployed artifact version against catalog latest
159
- app.get("/api/deployments/:id/whats-new", { preHandler: [requirePermission("deployment.view")] }, async (request, reply) => {
160
- const deployment = deployments.get(request.params.id);
161
- if (!deployment) {
162
- return reply.status(404).send({ error: "Deployment not found" });
163
- }
164
- const versions = artifactStore.getVersions(deployment.artifactId);
165
- const sorted = versions.slice().sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
166
- const latest = sorted[0] ?? null;
167
- const deployedVersion = deployment.version;
168
- const latestVersion = latest?.version ?? null;
169
- const isLatest = latestVersion === null || latestVersion === deployedVersion;
170
- return {
171
- deployedVersion,
172
- latestVersion,
173
- isLatest,
174
- latestCreatedAt: latest?.createdAt ? new Date(latest.createdAt).toISOString() : null,
175
- };
176
- });
177
- // List deployments (optionally filtered by partition, artifact, or envoy)
178
- app.get("/api/deployments", { preHandler: [requirePermission("deployment.view")] }, async (request) => {
179
- const qParsed = DeploymentListQuerySchema.safeParse(request.query);
180
- const { partitionId, artifactId, envoyId } = qParsed.success ? qParsed.data : {};
181
- let list;
182
- if (partitionId) {
183
- list = deployments.getByPartition(partitionId);
184
- }
185
- else if (artifactId) {
186
- list = deployments.getByArtifact(artifactId);
187
- }
188
- else {
189
- list = deployments.list();
190
- }
191
- if (envoyId) {
192
- list = list.filter((d) => d.envoyId === envoyId);
193
- }
194
- return { deployments: list };
195
- });
196
- // Submit a plan from envoy — transitions deployment to awaiting_approval
197
- app.post("/api/deployments/:id/plan", { preHandler: [requirePermission("deployment.create")] }, async (request, reply) => {
198
- const deployment = deployments.get(request.params.id);
199
- if (!deployment) {
200
- return reply.status(404).send({ error: "Deployment not found" });
201
- }
202
- const parsed = SubmitPlanSchema.safeParse(request.body);
203
- if (!parsed.success) {
204
- return reply.status(400).send({ error: "Invalid plan submission", details: parsed.error.format() });
205
- }
206
- if (deployment.status !== "pending" && deployment.status !== "planning") {
207
- return reply.status(409).send({ error: `Cannot submit plan for deployment in "${deployment.status}" status` });
208
- }
209
- deployment.plan = parsed.data.plan;
210
- deployment.rollbackPlan = parsed.data.rollbackPlan;
211
- deployment.status = "awaiting_approval";
212
- // Generate recommendation from enrichment context
213
- deployment.recommendation = computeRecommendation(deployment, deployments);
214
- deployments.save(deployment);
215
- debrief.record({
216
- partitionId: deployment.partitionId ?? null,
217
- deploymentId: deployment.id,
218
- agent: "envoy",
219
- decisionType: "plan-generation",
220
- decision: `Deployment plan submitted with ${parsed.data.plan.steps.length} steps`,
221
- reasoning: parsed.data.plan.reasoning,
222
- context: { stepCount: parsed.data.plan.steps.length },
223
- });
224
- return reply.status(200).send({ deployment });
225
- });
226
- // Approve a deployment plan
227
- app.post("/api/deployments/:id/approve", { preHandler: [requirePermission("deployment.approve")] }, async (request, reply) => {
228
- const deployment = deployments.get(request.params.id);
229
- if (!deployment) {
230
- return reply.status(404).send({ error: "Deployment not found" });
231
- }
232
- const parsed = ApproveDeploymentSchema.safeParse(request.body);
233
- if (!parsed.success) {
234
- return reply.status(400).send({ error: parsed.error.message });
235
- }
236
- if (deployment.status !== "awaiting_approval") {
237
- return reply.status(409).send({ error: `Cannot approve deployment in "${deployment.status}" status — must be "awaiting_approval"` });
238
- }
239
- // Transition deployment status
240
- deployment.approvedBy = parsed.data.approvedBy;
241
- deployment.approvedAt = new Date();
242
- deployment.status = "approved";
243
- deployments.save(deployment);
244
- const actor = (request.user?.email) ?? parsed.data.approvedBy;
245
- // Record approval in debrief
246
- debrief.record({
247
- partitionId: deployment.partitionId ?? null,
248
- deploymentId: deployment.id,
249
- agent: "server",
250
- decisionType: "system",
251
- decision: `Deployment approved by ${actor}`,
252
- reasoning: parsed.data.modifications
253
- ? `Approved with modifications: ${parsed.data.modifications}`
254
- : "Approved without modifications",
255
- context: { approvedBy: actor },
256
- actor: request.user?.email,
257
- });
258
- telemetry.record({ actor, action: "deployment.approved", target: { type: "deployment", id: deployment.id }, details: { modifications: parsed.data.modifications } });
259
- telemetry.record({
260
- actor,
261
- action: parsed.data.modifications ? "agent.recommendation.overridden" : "agent.recommendation.followed",
262
- target: { type: "deployment", id: deployment.id },
263
- details: parsed.data.modifications
264
- ? { modifications: parsed.data.modifications }
265
- : { planStepCount: deployment.plan?.steps.length ?? 0 },
266
- });
267
- // Dispatch approved plan to envoy for execution
268
- if (envoyClient && deployment.plan && deployment.rollbackPlan) {
269
- const artifact = artifactStore.get(deployment.artifactId);
270
- const serverPort = process.env.PORT ?? "9410";
271
- const serverUrl = process.env.SYNTH_SERVER_URL ?? `http://localhost:${serverPort}`;
272
- const progressCallbackUrl = `${serverUrl}/api/deployments/${deployment.id}/progress`;
273
- const callbackToken = envoyRegistry?.list().find(r => r.url === envoyClient.url)?.token;
274
- deployment.status = "running";
275
- deployments.save(deployment);
276
- // Fire-and-forget: execution runs async, progress comes via callback
277
- envoyClient.executeApprovedPlan({
278
- deploymentId: deployment.id,
279
- plan: deployment.plan,
280
- rollbackPlan: deployment.rollbackPlan,
281
- artifactType: artifact?.type ?? "unknown",
282
- artifactName: artifact?.name ?? "unknown",
283
- environmentId: deployment.environmentId ?? "",
284
- progressCallbackUrl,
285
- callbackToken,
286
- }).catch((err) => {
287
- // Execution dispatch failed — record failure
288
- deployment.status = "failed";
289
- deployment.failureReason = err instanceof Error ? err.message : "Execution dispatch failed";
290
- deployments.save(deployment);
291
- debrief.record({
292
- partitionId: deployment.partitionId ?? null,
293
- deploymentId: deployment.id,
294
- agent: "server",
295
- decisionType: "deployment-failure",
296
- decision: "Failed to dispatch approved plan to envoy",
297
- reasoning: deployment.failureReason,
298
- context: { error: deployment.failureReason },
299
- });
300
- });
301
- }
302
- return { deployment, approved: true };
303
- });
304
- // Reject a deployment plan
305
- app.post("/api/deployments/:id/reject", { preHandler: [requirePermission("deployment.reject")] }, async (request, reply) => {
306
- const deployment = deployments.get(request.params.id);
307
- if (!deployment) {
308
- return reply.status(404).send({ error: "Deployment not found" });
309
- }
310
- const parsed = RejectDeploymentSchema.safeParse(request.body);
311
- if (!parsed.success) {
312
- return reply.status(400).send({ error: parsed.error.message });
313
- }
314
- if (deployment.status !== "awaiting_approval") {
315
- return reply.status(409).send({ error: `Cannot reject deployment in "${deployment.status}" status — must be "awaiting_approval"` });
316
- }
317
- // Transition deployment status and store rejection reason
318
- deployment.status = "rejected";
319
- deployment.rejectionReason = parsed.data.reason;
320
- deployments.save(deployment);
321
- const actor = (request.user?.email) ?? "anonymous";
322
- // Record rejection in debrief
323
- debrief.record({
324
- partitionId: deployment.partitionId ?? null,
325
- deploymentId: deployment.id,
326
- agent: "server",
327
- decisionType: "system",
328
- decision: "Deployment plan rejected",
329
- reasoning: parsed.data.reason,
330
- context: { reason: parsed.data.reason },
331
- actor: request.user?.email,
332
- });
333
- telemetry.record({ actor, action: "deployment.rejected", target: { type: "deployment", id: deployment.id }, details: { reason: parsed.data.reason } });
334
- return { deployment, rejected: true };
335
- });
336
- // Modify a deployment plan (user edits steps before approval)
337
- app.post("/api/deployments/:id/modify", { preHandler: [requirePermission("deployment.approve")] }, async (request, reply) => {
338
- const deployment = deployments.get(request.params.id);
339
- if (!deployment) {
340
- return reply.status(404).send({ error: "Deployment not found" });
341
- }
342
- const parsed = ModifyDeploymentPlanSchema.safeParse(request.body);
343
- if (!parsed.success) {
344
- return reply.status(400).send({ error: parsed.error.message });
345
- }
346
- if (deployment.status !== "awaiting_approval") {
347
- return reply.status(409).send({ error: `Cannot modify deployment in "${deployment.status}" status — must be "awaiting_approval"` });
348
- }
349
- if (!deployment.plan) {
350
- return reply.status(409).send({ error: "Deployment has no plan to modify" });
351
- }
352
- // Validate modified plan with envoy if available
353
- if (envoyClient) {
354
- try {
355
- const validation = await envoyClient.validatePlan(parsed.data.steps);
356
- if (!validation.valid) {
357
- return reply.status(422).send({
358
- error: "Modified plan failed envoy validation",
359
- violations: validation.violations,
360
- });
361
- }
362
- }
363
- catch {
364
- // Envoy unreachable — proceed without validation but note it
365
- }
366
- }
367
- // Build structured diff: what changed between old and new steps
368
- const oldSteps = deployment.plan.steps;
369
- const newSteps = parsed.data.steps;
370
- const diffLines = [];
371
- const maxLen = Math.max(oldSteps.length, newSteps.length);
372
- for (let i = 0; i < maxLen; i++) {
373
- const old = oldSteps[i];
374
- const cur = newSteps[i];
375
- if (!old) {
376
- diffLines.push(`+ Step ${i + 1} (added): ${cur.action} ${cur.target} — ${cur.description}`);
377
- }
378
- else if (!cur) {
379
- diffLines.push(`- Step ${i + 1} (removed): ${old.action} ${old.target} — ${old.description}`);
380
- }
381
- else if (old.action !== cur.action || old.target !== cur.target || old.description !== cur.description) {
382
- diffLines.push(`~ Step ${i + 1} (changed): ${old.action} ${old.target} → ${cur.action} ${cur.target}`);
383
- if (old.description !== cur.description) {
384
- diffLines.push(` was: ${old.description}`);
385
- diffLines.push(` now: ${cur.description}`);
386
- }
387
- }
388
- }
389
- const diffFromPreviousPlan = diffLines.length > 0
390
- ? diffLines.join("\n")
391
- : "Steps reordered or metadata changed (actions and targets unchanged)";
392
- // Apply modifications
393
- deployment.plan = {
394
- ...deployment.plan,
395
- steps: parsed.data.steps,
396
- diffFromPreviousPlan,
397
- };
398
- deployments.save(deployment);
399
- const actor = (request.user?.email) ?? "anonymous";
400
- // Record modification in debrief
401
- debrief.record({
402
- partitionId: deployment.partitionId ?? null,
403
- deploymentId: deployment.id,
404
- agent: "server",
405
- decisionType: "plan-modification",
406
- decision: `Deployment plan modified by ${actor}`,
407
- reasoning: parsed.data.reason,
408
- context: {
409
- modifiedBy: actor,
410
- stepCount: parsed.data.steps.length,
411
- reason: parsed.data.reason,
412
- },
413
- actor: request.user?.email,
414
- });
415
- telemetry.record({
416
- actor,
417
- action: "deployment.modified",
418
- target: { type: "deployment", id: deployment.id },
419
- details: { reason: parsed.data.reason, stepCount: parsed.data.steps.length },
420
- });
421
- telemetry.record({
422
- actor,
423
- action: "agent.recommendation.overridden",
424
- target: { type: "deployment", id: deployment.id },
425
- details: { reason: parsed.data.reason, stepCount: parsed.data.steps.length, diff: diffFromPreviousPlan },
426
- });
427
- return { deployment, modified: true };
428
- });
429
- // Replan a deployment with user feedback — triggers a new LLM planning pass
430
- app.post("/api/deployments/:id/replan", { preHandler: [requirePermission("deployment.approve")] }, async (request, reply) => {
431
- const deploymentId = request.params.id;
432
- const deployment = deployments.get(deploymentId);
433
- if (!deployment) {
434
- return reply.status(404).send({ error: "Deployment not found" });
435
- }
436
- if (deployment.status !== "awaiting_approval") {
437
- return reply.status(409).send({ error: `Cannot replan deployment in "${deployment.status}" status — must be "awaiting_approval"` });
438
- }
439
- const parsed = ReplanDeploymentSchema.safeParse(request.body);
440
- if (!parsed.success) {
441
- return reply.status(400).send({ error: parsed.error.message });
442
- }
443
- const artifact = artifactStore.get(deployment.artifactId);
444
- if (!artifact) {
445
- return reply.status(404).send({ error: `Artifact not found: ${deployment.artifactId}` });
446
- }
447
- const environment = deployment.environmentId ? environments.get(deployment.environmentId) : undefined;
448
- const partition = deployment.partitionId ? partitions.get(deployment.partitionId) : undefined;
449
- const planningEnvoy = deployment.envoyId ? envoyRegistry?.get(deployment.envoyId) : envoyRegistry?.list()[0];
450
- if (!planningEnvoy) {
451
- return reply.status(422).send({ error: "No envoy available for replanning" });
452
- }
453
- // Validate feedback with LLM before triggering expensive replan
454
- const planningClientForValidation = new EnvoyClient(planningEnvoy.url);
455
- try {
456
- const validation = await planningClientForValidation.validateRefinementFeedback({
457
- feedback: parsed.data.feedback,
458
- currentPlanSteps: (deployment.plan?.steps ?? []).map((s) => ({
459
- description: s.description,
460
- action: s.action,
461
- target: s.target,
462
- })),
463
- artifactName: artifact?.name ?? "unknown",
464
- environmentName: environment?.name ?? "unknown",
465
- });
466
- if (validation.mode === "rejection") {
467
- return reply.status(422).send({ error: validation.message, mode: "rejection" });
468
- }
469
- if (validation.mode === "response") {
470
- return reply.status(200).send({ mode: "response", message: validation.message });
471
- }
472
- // mode === "replan" — fall through to full replan
473
- }
474
- catch {
475
- // Validation call failed — proceed with replan rather than blocking the user
476
- }
477
- deployment.status = "planning";
478
- deployments.save(deployment);
479
- const planningClient = new EnvoyClient(planningEnvoy.url);
480
- const environmentForPlanning = environment
481
- ? { id: environment.id, name: environment.name, variables: environment.variables }
482
- : { id: `direct:${planningEnvoy.id}`, name: planningEnvoy.name, variables: {} };
483
- let result;
484
- try {
485
- result = await planningClient.requestPlan({
486
- deploymentId,
487
- artifact: {
488
- id: artifact.id,
489
- name: artifact.name,
490
- type: artifact.type,
491
- analysis: {
492
- summary: artifact.analysis.summary,
493
- dependencies: artifact.analysis.dependencies,
494
- configurationExpectations: artifact.analysis.configurationExpectations,
495
- deploymentIntent: artifact.analysis.deploymentIntent,
496
- confidence: artifact.analysis.confidence,
497
- },
498
- },
499
- environment: environmentForPlanning,
500
- partition: partition
501
- ? { id: partition.id, name: partition.name, variables: partition.variables }
502
- : undefined,
503
- version: deployment.version,
504
- resolvedVariables: deployment.variables,
505
- refinementFeedback: parsed.data.feedback,
506
- });
507
- }
508
- catch (err) {
509
- const dep = deployments.get(deploymentId);
510
- if (dep) {
511
- dep.status = "awaiting_approval";
512
- deployments.save(dep);
513
- }
514
- return reply.status(500).send({ error: err instanceof Error ? err.message : "Replanning failed" });
515
- }
516
- const dep = deployments.get(deploymentId);
517
- if (!dep) {
518
- return reply.status(404).send({ error: "Deployment not found after replanning" });
519
- }
520
- dep.plan = result.plan;
521
- dep.rollbackPlan = result.rollbackPlan;
522
- dep.recommendation = computeRecommendation(dep, deployments, result.assessmentSummary);
523
- dep.status = "awaiting_approval";
524
- deployments.save(dep);
525
- debrief.record({
526
- partitionId: dep.partitionId ?? null,
527
- deploymentId: dep.id,
528
- agent: "envoy",
529
- decisionType: "plan-generation",
530
- decision: `Plan regenerated with user feedback (${result.plan.steps.length} steps)`,
531
- reasoning: result.plan.reasoning,
532
- context: { stepCount: result.plan.steps.length, envoyId: planningEnvoy.id, refinementFeedback: parsed.data.feedback },
533
- });
534
- return { deployment: dep, replanned: true };
535
- });
536
- // Get cross-system enrichment context for a deployment
537
- app.get("/api/deployments/:id/context", { preHandler: [requirePermission("deployment.view")] }, async (request, reply) => {
538
- const deployment = deployments.get(request.params.id);
539
- if (!deployment) {
540
- return reply.status(404).send({ error: "Deployment not found" });
541
- }
542
- const now = new Date();
543
- const twentyFourHoursAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
544
- // Count recent deployments to the same environment (only meaningful when environmentId is set)
545
- const recentDeploymentsToEnv = deployment.environmentId
546
- ? deployments.countByEnvironment(deployment.environmentId, twentyFourHoursAgo)
547
- : 0;
548
- // Check if the same artifact version was previously rolled back
549
- const previouslyRolledBack = deployment.version
550
- ? deployments.findByArtifactVersion(deployment.artifactId, deployment.version, "rolled_back").length > 0
551
- : false;
552
- // Check for other in-progress deployments to the same environment
553
- const conflictingDeployments = deployment.environmentId
554
- ? deployments.list()
555
- .filter((d) => d.environmentId === deployment.environmentId &&
556
- d.id !== deployment.id &&
557
- (d.status === "running" || d.status === "approved" || d.status === "awaiting_approval"))
558
- .map((d) => d.id)
559
- : [];
560
- // Find last deployment to the same environment
561
- const lastDeploy = deployment.environmentId
562
- ? deployments.findLatestByEnvironment(deployment.environmentId)
563
- : undefined;
564
- const lastDeploymentToEnv = lastDeploy && lastDeploy.id !== deployment.id
565
- ? {
566
- id: lastDeploy.id,
567
- status: lastDeploy.status,
568
- version: lastDeploy.version,
569
- completedAt: lastDeploy.completedAt,
570
- }
571
- : undefined;
572
- const enrichment = {
573
- recentDeploymentsToEnv,
574
- previouslyRolledBack,
575
- conflictingDeployments,
576
- lastDeploymentToEnv,
577
- };
578
- return {
579
- enrichment,
580
- recommendation: deployment.recommendation ?? computeRecommendation(deployment, deployments),
581
- };
582
- });
583
- // Request a post-hoc rollback plan — asks the envoy to reason about
584
- // what actually ran and produce a targeted rollback plan
585
- app.post("/api/deployments/:id/request-rollback-plan", { preHandler: [requirePermission("deployment.approve")] }, async (request, reply) => {
586
- const deployment = deployments.get(request.params.id);
587
- if (!deployment) {
588
- return reply.status(404).send({ error: "Deployment not found" });
589
- }
590
- const finishedStatuses = new Set(["succeeded", "failed", "rolled_back"]);
591
- if (!finishedStatuses.has(deployment.status)) {
592
- return reply.status(409).send({
593
- error: `Cannot request rollback plan for deployment in "${deployment.status}" status — deployment must be finished`,
594
- });
595
- }
596
- const artifact = artifactStore.get(deployment.artifactId);
597
- if (!artifact) {
598
- return reply.status(404).send({ error: "Artifact not found" });
599
- }
600
- // Determine which envoy to ask
601
- const targetEnvoy = deployment.envoyId
602
- ? envoyRegistry?.get(deployment.envoyId)
603
- : envoyRegistry?.list()[0];
604
- if (!targetEnvoy) {
605
- return reply.status(503).send({ error: "No envoy available to generate rollback plan" });
606
- }
607
- const environment = deployment.environmentId ? environments.get(deployment.environmentId) : undefined;
608
- // Build the list of completed steps from execution record (or plan as fallback)
609
- const completedSteps = deployment.executionRecord?.steps.map((s) => ({
610
- description: s.description,
611
- action: deployment.plan?.steps.find((p) => p.description === s.description)?.action ?? "unknown",
612
- target: deployment.plan?.steps.find((p) => p.description === s.description)?.target ?? "",
613
- status: s.status,
614
- output: s.output ?? s.error,
615
- })) ?? deployment.plan?.steps.map((s) => ({
616
- description: s.description,
617
- action: s.action,
618
- target: s.target,
619
- status: "completed",
620
- })) ?? [];
621
- const rollbackClient = new EnvoyClient(targetEnvoy.url);
622
- try {
623
- const rollbackPlan = await rollbackClient.requestRollbackPlan({
624
- deploymentId: deployment.id,
625
- artifact: {
626
- name: artifact.name,
627
- type: artifact.type,
628
- analysis: {
629
- summary: artifact.analysis.summary,
630
- dependencies: artifact.analysis.dependencies,
631
- configurationExpectations: artifact.analysis.configurationExpectations,
632
- deploymentIntent: artifact.analysis.deploymentIntent,
633
- confidence: artifact.analysis.confidence,
634
- },
635
- },
636
- environment: {
637
- id: deployment.environmentId ?? "",
638
- name: environment?.name ?? deployment.environmentId ?? "unknown",
639
- },
640
- completedSteps,
641
- deployedVariables: deployment.variables,
642
- version: deployment.version,
643
- failureReason: deployment.failureReason ?? undefined,
644
- });
645
- // Store the generated rollback plan on the deployment
646
- deployment.rollbackPlan = rollbackPlan;
647
- deployments.save(deployment);
648
- const actor = (request.user?.email) ?? "anonymous";
649
- debrief.record({
650
- partitionId: deployment.partitionId ?? null,
651
- deploymentId: deployment.id,
652
- agent: "server",
653
- decisionType: "plan-generation",
654
- decision: `Rollback plan requested and generated for ${artifact.name} v${deployment.version}`,
655
- reasoning: rollbackPlan.reasoning,
656
- context: {
657
- requestedBy: actor,
658
- stepCount: rollbackPlan.steps.length,
659
- envoyId: targetEnvoy.id,
660
- deploymentStatus: deployment.status,
661
- },
662
- actor: request.user?.email,
663
- });
664
- telemetry.record({
665
- actor,
666
- action: "deployment.rollback-plan-requested",
667
- target: { type: "deployment", id: deployment.id },
668
- details: { stepCount: rollbackPlan.steps.length },
669
- });
670
- return reply.status(200).send({ deployment, rollbackPlan });
671
- }
672
- catch (err) {
673
- return reply.status(500).send({
674
- error: "Failed to generate rollback plan",
675
- details: err instanceof Error ? err.message : String(err),
676
- });
677
- }
678
- });
679
- // Execute rollback — runs the stored rollback plan against the envoy
680
- app.post("/api/deployments/:id/execute-rollback", { preHandler: [requirePermission("deployment.approve")] }, async (request, reply) => {
681
- const deployment = deployments.get(request.params.id);
682
- if (!deployment) {
683
- return reply.status(404).send({ error: "Deployment not found" });
684
- }
685
- if (!deployment.rollbackPlan) {
686
- return reply.status(409).send({ error: "No rollback plan available — request one first" });
687
- }
688
- const finishedStatuses = new Set(["succeeded", "failed"]);
689
- if (!finishedStatuses.has(deployment.status)) {
690
- return reply.status(409).send({
691
- error: `Cannot execute rollback for deployment in "${deployment.status}" status`,
692
- });
693
- }
694
- const artifact = artifactStore.get(deployment.artifactId);
695
- const targetEnvoy = deployment.envoyId
696
- ? envoyRegistry?.get(deployment.envoyId)
697
- : envoyRegistry?.list()[0];
698
- if (!targetEnvoy) {
699
- return reply.status(503).send({ error: "No envoy available to execute rollback" });
700
- }
701
- const actor = (request.user?.email) ?? "anonymous";
702
- const serverPort = process.env.PORT ?? "9410";
703
- const serverUrl = process.env.SYNTH_SERVER_URL ?? `http://localhost:${serverPort}`;
704
- const progressCallbackUrl = `${serverUrl}/api/deployments/${deployment.id}/progress`;
705
- deployment.status = "running";
706
- deployments.save(deployment);
707
- debrief.record({
708
- partitionId: deployment.partitionId ?? null,
709
- deploymentId: deployment.id,
710
- agent: "server",
711
- decisionType: "rollback-execution",
712
- decision: `Rollback execution initiated for ${artifact?.name ?? deployment.artifactId} v${deployment.version}`,
713
- reasoning: `Rollback requested by ${actor}. Executing ${deployment.rollbackPlan.steps.length} rollback step(s).`,
714
- context: { initiatedBy: actor, stepCount: deployment.rollbackPlan.steps.length },
715
- actor: request.user?.email,
716
- });
717
- telemetry.record({
718
- actor,
719
- action: "deployment.rollback-executed",
720
- target: { type: "deployment", id: deployment.id },
721
- details: { stepCount: deployment.rollbackPlan.steps.length },
722
- });
723
- const rollbackClient = new EnvoyClient(targetEnvoy.url);
724
- // Execute the rollback plan as if it were a forward plan — it IS a forward plan
725
- // (just in the reverse direction). Use an empty no-op plan as the "rollback of rollback".
726
- const emptyPlan = { steps: [], reasoning: "No rollback of rollback." };
727
- rollbackClient.executeApprovedPlan({
728
- deploymentId: deployment.id,
729
- plan: deployment.rollbackPlan,
730
- rollbackPlan: emptyPlan,
731
- artifactType: artifact?.type ?? "unknown",
732
- artifactName: artifact?.name ?? "unknown",
733
- environmentId: deployment.environmentId ?? "",
734
- progressCallbackUrl,
735
- callbackToken: targetEnvoy.token,
736
- }).then((result) => {
737
- const dep = deployments.get(deployment.id);
738
- if (!dep)
739
- return;
740
- dep.status = result.success ? "rolled_back" : "failed";
741
- if (!result.success) {
742
- dep.failureReason = result.failureReason ?? "Rollback execution failed";
743
- }
744
- dep.completedAt = new Date();
745
- deployments.save(dep);
746
- debrief.record({
747
- partitionId: dep.partitionId ?? null,
748
- deploymentId: dep.id,
749
- agent: "server",
750
- decisionType: "rollback-execution",
751
- decision: result.success
752
- ? `Rollback completed successfully for ${artifact?.name ?? dep.artifactId} v${dep.version}`
753
- : `Rollback failed for ${artifact?.name ?? dep.artifactId} v${dep.version}`,
754
- reasoning: result.success
755
- ? `All rollback steps executed successfully.`
756
- : `Rollback failed: ${result.failureReason}`,
757
- context: { success: result.success, failureReason: result.failureReason },
758
- });
759
- }).catch((err) => {
760
- const dep = deployments.get(deployment.id);
761
- if (!dep)
762
- return;
763
- dep.status = "failed";
764
- dep.failureReason = err instanceof Error ? err.message : "Rollback execution dispatch failed";
765
- deployments.save(dep);
766
- });
767
- return reply.status(202).send({ deployment, accepted: true });
768
- });
769
- // Retry (redeploy) — create a new deployment with the same parameters as the source
770
- app.post("/api/deployments/:id/retry", { preHandler: [requirePermission("deployment.create")] }, async (request, reply) => {
771
- const source = deployments.get(request.params.id);
772
- if (!source) {
773
- return reply.status(404).send({ error: "Deployment not found" });
774
- }
775
- // Calculate attempt number by following the retryOf chain
776
- let attemptNumber = 1;
777
- let cursor = source;
778
- while (cursor?.retryOf) {
779
- attemptNumber++;
780
- cursor = deployments.get(cursor.retryOf);
781
- }
782
- attemptNumber++; // this new deployment is one more
783
- // Validate artifact still exists
784
- const artifact = artifactStore.get(source.artifactId);
785
- if (!artifact) {
786
- return reply.status(404).send({ error: `Artifact not found: ${source.artifactId}` });
787
- }
788
- // Validate environment still exists (if present on source)
789
- const environment = source.environmentId ? environments.get(source.environmentId) : undefined;
790
- if (source.environmentId && !environment) {
791
- return reply.status(404).send({ error: `Environment not found: ${source.environmentId}` });
792
- }
793
- // Validate partition still exists (if present on source)
794
- const partition = source.partitionId ? partitions.get(source.partitionId) : undefined;
795
- if (source.partitionId && !partition) {
796
- return reply.status(404).send({ error: `Partition not found: ${source.partitionId}` });
797
- }
798
- // Validate envoy still exists (if present on source)
799
- const targetEnvoy = source.envoyId ? envoyRegistry?.get(source.envoyId) : undefined;
800
- if (source.envoyId && !targetEnvoy) {
801
- return reply.status(404).send({ error: `Envoy not found: ${source.envoyId}` });
802
- }
803
- // Resolve variables — same logic as POST /api/deployments
804
- const envVars = environment ? environment.variables : {};
805
- const partitionVars = partition?.variables ?? {};
806
- const resolved = { ...partitionVars, ...envVars };
807
- const deployment = {
808
- id: crypto.randomUUID(),
809
- artifactId: source.artifactId,
810
- environmentId: source.environmentId,
811
- partitionId: source.partitionId,
812
- envoyId: targetEnvoy?.id,
813
- version: source.version ?? "",
814
- status: "pending",
815
- variables: resolved,
816
- retryOf: source.id,
817
- debriefEntryIds: [],
818
- createdAt: new Date(),
819
- };
820
- deployments.save(deployment);
821
- const actor = (request.user?.email) ?? "anonymous";
822
- telemetry.record({ actor, action: "deployment.created", target: { type: "deployment", id: deployment.id }, details: { artifactId: source.artifactId, environmentId: source.environmentId, partitionId: source.partitionId, envoyId: source.envoyId, retryOf: source.id } });
823
- // Record retry debrief entry
824
- debrief.record({
825
- partitionId: deployment.partitionId ?? null,
826
- deploymentId: deployment.id,
827
- agent: "server",
828
- decisionType: "system",
829
- decision: `Retry of deployment ${source.id} (attempt #${attemptNumber})`,
830
- reasoning: `User initiated retry of deployment ${source.id}. Same artifact, version, environment, and partition.`,
831
- context: { retryOf: source.id, attemptNumber, actor },
832
- actor: request.user?.email,
833
- });
834
- // Dispatch planning — same logic as POST /api/deployments
835
- if (envoyRegistry) {
836
- const planningEnvoy = targetEnvoy
837
- ?? (environment ? envoyRegistry.findForEnvironment(environment.name) : undefined)
838
- ?? envoyRegistry.list()[0];
839
- if (planningEnvoy) {
840
- const planningClient = new EnvoyClient(planningEnvoy.url);
841
- const environmentForPlanning = environment
842
- ? { id: environment.id, name: environment.name, variables: environment.variables }
843
- : { id: `direct:${planningEnvoy.id}`, name: planningEnvoy.name, variables: {} };
844
- planningClient.requestPlan({
845
- deploymentId: deployment.id,
846
- artifact: {
847
- id: artifact.id,
848
- name: artifact.name,
849
- type: artifact.type,
850
- analysis: {
851
- summary: artifact.analysis.summary,
852
- dependencies: artifact.analysis.dependencies,
853
- configurationExpectations: artifact.analysis.configurationExpectations,
854
- deploymentIntent: artifact.analysis.deploymentIntent,
855
- confidence: artifact.analysis.confidence,
856
- },
857
- },
858
- environment: environmentForPlanning,
859
- partition: partition
860
- ? { id: partition.id, name: partition.name, variables: partition.variables }
861
- : undefined,
862
- version: deployment.version,
863
- resolvedVariables: resolved,
864
- }).then((result) => {
865
- const dep = deployments.get(deployment.id);
866
- if (!dep || dep.status !== "pending")
867
- return;
868
- dep.plan = result.plan;
869
- dep.rollbackPlan = result.rollbackPlan;
870
- dep.envoyId = planningEnvoy.id;
871
- if (result.blocked) {
872
- dep.status = "failed";
873
- dep.failureReason = result.blockReason ?? "Plan blocked due to unrecoverable precondition failures";
874
- deployments.save(dep);
875
- debrief.record({
876
- partitionId: dep.partitionId ?? null,
877
- deploymentId: dep.id,
878
- agent: "envoy",
879
- decisionType: "plan-generation",
880
- decision: `Deployment plan blocked — infrastructure prerequisites not met`,
881
- reasoning: result.blockReason ?? result.plan.reasoning,
882
- context: { stepCount: result.plan.steps.length, envoyId: planningEnvoy.id, blocked: true },
883
- });
884
- }
885
- else {
886
- dep.status = "awaiting_approval";
887
- dep.recommendation = computeRecommendation(dep, deployments, result.assessmentSummary);
888
- deployments.save(dep);
889
- debrief.record({
890
- partitionId: dep.partitionId ?? null,
891
- deploymentId: dep.id,
892
- agent: "envoy",
893
- decisionType: "plan-generation",
894
- decision: `Deployment plan generated with ${result.plan.steps.length} steps`,
895
- reasoning: result.plan.reasoning,
896
- context: { stepCount: result.plan.steps.length, envoyId: planningEnvoy.id, delta: result.delta },
897
- });
898
- }
899
- }).catch((err) => {
900
- const dep = deployments.get(deployment.id);
901
- if (!dep || dep.status !== "pending")
902
- return;
903
- dep.status = "failed";
904
- dep.failureReason = err instanceof Error ? err.message : "Planning failed";
905
- deployments.save(dep);
906
- debrief.record({
907
- partitionId: dep.partitionId ?? null,
908
- deploymentId: dep.id,
909
- agent: "server",
910
- decisionType: "deployment-failure",
911
- decision: "Envoy planning failed",
912
- reasoning: dep.failureReason,
913
- context: { error: dep.failureReason, envoyId: planningEnvoy.id },
914
- });
915
- });
916
- }
917
- }
918
- return reply.status(201).send({ deployment, sourceDeploymentId: source.id, attemptNumber });
919
- });
920
- // Get deployment postmortem
921
- app.get("/api/deployments/:id/postmortem", { preHandler: [requirePermission("deployment.view")] }, async (request, reply) => {
922
- const deployment = deployments.get(request.params.id);
923
- if (!deployment) {
924
- return reply.status(404).send({ error: "Deployment not found" });
925
- }
926
- const entries = debrief.getByDeployment(deployment.id);
927
- const postmortem = generatePostmortem(entries, deployment);
928
- const llmResult = await generatePostmortemAsync(entries, deployment, llm);
929
- return {
930
- postmortem,
931
- ...(llmResult.heuristicFallback ? {} : { llmPostmortem: llmResult.llmPostmortem }),
932
- };
933
- });
934
- // Get recent debrief entries (supports filtering by partition and decision type)
935
- app.get("/api/debrief", { preHandler: [requirePermission("deployment.view")] }, async (request) => {
936
- const qParsed = DebriefQuerySchema.safeParse(request.query);
937
- const { limit, partitionId, decisionType } = qParsed.success ? qParsed.data : {};
938
- const max = limit ?? 50;
939
- // No filters — fast path
940
- if (!partitionId && !decisionType) {
941
- return { entries: debrief.getRecent(max) };
942
- }
943
- // Start with the most selective filter, then narrow
944
- let entries;
945
- if (partitionId && decisionType) {
946
- entries = debrief.getByPartition(partitionId).filter((e) => e.decisionType === decisionType);
947
- }
948
- else if (partitionId) {
949
- entries = debrief.getByPartition(partitionId);
950
- }
951
- else {
952
- entries = debrief.getByType(decisionType);
953
- }
954
- entries.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
955
- return { entries: entries.slice(0, max) };
956
- });
957
- // ---------------------------------------------------------------------------
958
- // Progress streaming — envoy callback and SSE endpoints
959
- // ---------------------------------------------------------------------------
960
- // POST /api/deployments/:id/progress — receives progress events from envoy
961
- app.post("/api/deployments/:id/progress", async (request, reply) => {
962
- if (!progressStore) {
963
- return reply.status(501).send({ error: "Progress streaming not configured" });
964
- }
965
- // Validate envoy token — this route is exempt from JWT auth
966
- if (envoyRegistry) {
967
- const authHeader = (request.headers.authorization ?? "");
968
- const token = authHeader.startsWith("Bearer ") ? authHeader.slice(7) : null;
969
- if (!token || !envoyRegistry.validateToken(token)) {
970
- return reply.status(401).send({ error: "Invalid or missing envoy token" });
971
- }
972
- }
973
- const parsed = ProgressEventSchema.safeParse(request.body);
974
- if (!parsed.success) {
975
- return reply.status(400).send({ error: "Invalid progress event", details: parsed.error.format() });
976
- }
977
- const event = parsed.data;
978
- // Validate the deploymentId in the URL matches the body
979
- if (event.deploymentId !== request.params.id) {
980
- return reply.status(400).send({ error: "Deployment ID in URL does not match event body" });
981
- }
982
- progressStore.push(event);
983
- return reply.status(200).send({ received: true });
984
- });
985
- // GET /api/deployments/:id/stream — SSE endpoint for live progress
986
- // Auth is via ?token= query param since EventSource cannot send headers
987
- app.get("/api/deployments/:id/stream", { preHandler: [requirePermission("deployment.view")] }, (request, reply) => {
988
- if (!progressStore) {
989
- reply.status(501).send({ error: "Progress streaming not configured" });
990
- return;
991
- }
992
- // Hijack the connection so Fastify does not finalize the response
993
- reply.hijack();
994
- // Set SSE headers
995
- reply.raw.writeHead(200, {
996
- "Content-Type": "text/event-stream",
997
- "Cache-Control": "no-cache",
998
- "Connection": "keep-alive",
999
- "X-Accel-Buffering": "no",
1000
- });
1001
- const deploymentId = request.params.id;
1002
- // Check for Last-Event-ID header (reconnection with replay)
1003
- const lastEventIdHeader = request.headers["last-event-id"];
1004
- const lastEventId = lastEventIdHeader ? parseInt(String(lastEventIdHeader), 10) : 0;
1005
- // Send catch-up events — either all (fresh connect) or since last ID (reconnect)
1006
- const existing = lastEventId
1007
- ? progressStore.getEventsSince(deploymentId, lastEventId)
1008
- : progressStore.getEvents(deploymentId);
1009
- for (const event of existing) {
1010
- reply.raw.write(`id: ${event.id}\ndata: ${JSON.stringify(event)}\n\n`);
1011
- }
1012
- // Check if deployment already completed — if so, close after catch-up
1013
- const lastEvent = existing[existing.length - 1];
1014
- if (lastEvent?.type === "deployment-completed") {
1015
- reply.raw.end();
1016
- return;
1017
- }
1018
- // Subscribe to new events
1019
- const listener = (event) => {
1020
- try {
1021
- reply.raw.write(`id: ${event.id}\ndata: ${JSON.stringify(event)}\n\n`);
1022
- // Close the stream when deployment completes
1023
- if (event.type === "deployment-completed") {
1024
- reply.raw.end();
1025
- }
1026
- }
1027
- catch {
1028
- // Client disconnected — clean up
1029
- progressStore.removeListener(deploymentId, listener);
1030
- }
1031
- };
1032
- progressStore.addListener(deploymentId, listener);
1033
- // Clean up on client disconnect
1034
- request.raw.on("close", () => {
1035
- progressStore.removeListener(deploymentId, listener);
1036
- });
1037
- });
1038
- }
1039
- // ---------------------------------------------------------------------------
1040
- // Recommendation engine — synthesizes enrichment context into a verdict
1041
- // ---------------------------------------------------------------------------
1042
- function computeRecommendation(deployment, store, llmSummary) {
1043
- const factors = [];
1044
- let verdict = "proceed";
1045
- const now = new Date();
1046
- const twentyFourHoursAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
1047
- // Check for previously rolled-back version
1048
- if (deployment.version) {
1049
- const rolledBack = store.findByArtifactVersion(deployment.artifactId, deployment.version, "rolled_back");
1050
- if (rolledBack.length > 0) {
1051
- verdict = "caution";
1052
- factors.push("This artifact version was previously rolled back");
1053
- }
1054
- }
1055
- // Check for conflicting deployments (only meaningful when environmentId is set)
1056
- if (deployment.environmentId) {
1057
- const conflicting = store.list().filter((d) => d.environmentId === deployment.environmentId &&
1058
- d.id !== deployment.id &&
1059
- (d.status === "running" || d.status === "approved"));
1060
- if (conflicting.length > 0) {
1061
- verdict = "hold";
1062
- factors.push(`${conflicting.length} other deployment(s) in progress for this environment`);
1063
- }
1064
- }
1065
- // Check deployment frequency
1066
- const recentCount = deployment.environmentId
1067
- ? store.countByEnvironment(deployment.environmentId, twentyFourHoursAgo)
1068
- : 0;
1069
- if (recentCount > 5) {
1070
- if (verdict === "proceed")
1071
- verdict = "caution";
1072
- factors.push(`High deployment frequency: ${recentCount} deployments in the last 24h`);
1073
- }
1074
- // Check last deployment status
1075
- const lastDeploy = deployment.environmentId
1076
- ? store.findLatestByEnvironment(deployment.environmentId)
1077
- : undefined;
1078
- if (lastDeploy && lastDeploy.id !== deployment.id) {
1079
- if (lastDeploy.status === "failed" || lastDeploy.status === "rolled_back") {
1080
- if (verdict === "proceed")
1081
- verdict = "caution";
1082
- factors.push(`Last deployment to this environment ${lastDeploy.status}`);
1083
- }
1084
- else if (lastDeploy.status === "succeeded") {
1085
- factors.push("Last deployment to this environment succeeded");
1086
- }
1087
- }
1088
- if (factors.length === 0) {
1089
- factors.push("No risk factors detected — target is stable");
1090
- }
1091
- const summaryMap = {
1092
- proceed: "Proceed — no conflicting deployments, target environment is stable",
1093
- caution: "Proceed with caution — review risk factors before greenlighting",
1094
- hold: "Hold — resolve conflicting deployments before proceeding",
1095
- };
1096
- return { verdict, summary: llmSummary ?? summaryMap[verdict], factors };
1097
- }
1098
- //# sourceMappingURL=deployments.js.map