@synth-deploy/server 1.0.6 → 1.2.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 (97) hide show
  1. package/dist/agent/envoy-client.d.ts +65 -15
  2. package/dist/agent/envoy-client.d.ts.map +1 -1
  3. package/dist/agent/envoy-client.js +58 -8
  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 +59 -50
  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 +1900 -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 +434 -133
  39. package/dist/api/schemas.d.ts.map +1 -1
  40. package/dist/api/schemas.js +53 -25
  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 +3 -3
  48. package/dist/fleet/fleet-executor.js.map +1 -1
  49. package/dist/graph/graph-executor.d.ts.map +1 -1
  50. package/dist/graph/graph-executor.js +18 -4
  51. package/dist/graph/graph-executor.js.map +1 -1
  52. package/dist/index.js +89 -61
  53. package/dist/index.js.map +1 -1
  54. package/dist/mcp/resources.js +3 -3
  55. package/dist/mcp/resources.js.map +1 -1
  56. package/dist/mcp/tools.d.ts.map +1 -1
  57. package/dist/mcp/tools.js +2 -9
  58. package/dist/mcp/tools.js.map +1 -1
  59. package/dist/middleware/auth.js +1 -1
  60. package/dist/middleware/auth.js.map +1 -1
  61. package/package.json +1 -1
  62. package/src/agent/envoy-client.ts +111 -19
  63. package/src/agent/stale-deployment-detector.ts +1 -1
  64. package/src/agent/synth-agent.ts +76 -56
  65. package/src/alert-webhooks/alert-parsers.ts +291 -0
  66. package/src/api/agent.ts +9 -528
  67. package/src/api/alert-webhooks.ts +354 -0
  68. package/src/api/envoy-reports.ts +2 -2
  69. package/src/api/envoys.ts +1 -1
  70. package/src/api/fleet.ts +14 -15
  71. package/src/api/graph.ts +3 -3
  72. package/src/api/operations.ts +2260 -0
  73. package/src/api/partitions.ts +1 -1
  74. package/src/api/schemas.ts +59 -27
  75. package/src/api/system.ts +23 -21
  76. package/src/artifact-analyzer.ts +2 -2
  77. package/src/fleet/fleet-executor.ts +3 -3
  78. package/src/graph/graph-executor.ts +18 -4
  79. package/src/index.ts +91 -61
  80. package/src/mcp/resources.ts +3 -3
  81. package/src/mcp/tools.ts +5 -9
  82. package/src/middleware/auth.ts +1 -1
  83. package/tests/agent-mode.test.ts +5 -376
  84. package/tests/api-handlers.test.ts +27 -27
  85. package/tests/composite-operations.test.ts +557 -0
  86. package/tests/decision-diary.test.ts +62 -63
  87. package/tests/diary-reader.test.ts +14 -18
  88. package/tests/mcp-tools.test.ts +1 -1
  89. package/tests/orchestration.test.ts +34 -30
  90. package/tests/partition-isolation.test.ts +4 -9
  91. package/tests/rbac-enforcement.test.ts +8 -8
  92. package/tests/ui-journey.test.ts +9 -9
  93. package/dist/api/deployments.d.ts +0 -11
  94. package/dist/api/deployments.d.ts.map +0 -1
  95. package/dist/api/deployments.js +0 -1098
  96. package/dist/api/deployments.js.map +0 -1
  97. package/src/api/deployments.ts +0 -1347
@@ -0,0 +1,1900 @@
1
+ import { generatePostmortem, generatePostmortemAsync, resolveApprovalMode } from "@synth-deploy/core";
2
+ import { requirePermission } from "../middleware/permissions.js";
3
+ import { CreateOperationSchema, 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
+ function getArtifactId(op) {
10
+ return op.input.type === "deploy" ? op.input.artifactId : undefined;
11
+ }
12
+ export function registerOperationRoutes(app, deployments, debrief, partitions, environments, artifactStore, settings, telemetry, progressStore, envoyClient, envoyRegistry, llm) {
13
+ // Create a deployment (plan phase)
14
+ app.post("/api/operations", { preHandler: [requirePermission("deployment.create")] }, async (request, reply) => {
15
+ const parsed = CreateOperationSchema.safeParse(request.body);
16
+ if (!parsed.success) {
17
+ return reply.status(400).send({ error: parsed.error.message });
18
+ }
19
+ const { artifactId, environmentId, partitionId, envoyId, version, type: operationType, intent, allowWrite, condition, responseIntent, parentOperationId, requireApproval } = parsed.data;
20
+ // Validate artifact exists (required for deploy operations)
21
+ if (operationType === "deploy" && !artifactId) {
22
+ return reply.status(400).send({ error: "artifactId is required for deploy operations" });
23
+ }
24
+ const artifact = artifactId ? artifactStore.get(artifactId) : undefined;
25
+ if (operationType === "deploy" && !artifact) {
26
+ return reply.status(404).send({ error: `Artifact not found: ${artifactId}` });
27
+ }
28
+ // Validate environment exists (optional when targeting a partition or envoy)
29
+ const environment = environmentId ? environments.get(environmentId) : undefined;
30
+ if (environmentId && !environment) {
31
+ return reply.status(404).send({ error: `Environment not found: ${environmentId}` });
32
+ }
33
+ // Validate partition if provided
34
+ const partition = partitionId ? partitions.get(partitionId) : undefined;
35
+ if (partitionId && !partition) {
36
+ return reply.status(404).send({ error: `Partition not found: ${partitionId}` });
37
+ }
38
+ // Validate envoy if provided
39
+ const targetEnvoy = envoyId ? envoyRegistry?.get(envoyId) : undefined;
40
+ if (envoyId && !targetEnvoy) {
41
+ return reply.status(404).send({ error: `Envoy not found: ${envoyId}` });
42
+ }
43
+ // Resolve variables — partition vars are base, environment vars take precedence if present
44
+ const envVars = environment ? environment.variables : {};
45
+ const partitionVars = partition?.variables ?? {};
46
+ const resolved = { ...partitionVars, ...envVars };
47
+ const operationInput = operationType === "deploy"
48
+ ? { type: "deploy", artifactId: artifactId, ...(version ? { artifactVersionId: version } : {}) }
49
+ : operationType === "trigger"
50
+ ? { type: "trigger", condition: condition ?? intent ?? "", responseIntent: responseIntent ?? intent ?? "" }
51
+ : operationType === "composite"
52
+ ? { type: "composite", operations: (parsed.data.operations ?? []) }
53
+ : operationType === "investigate"
54
+ ? { type: "investigate", intent: intent ?? "", ...(allowWrite !== undefined ? { allowWrite } : {}) }
55
+ : { type: operationType, intent: intent ?? "" };
56
+ const deployment = {
57
+ id: crypto.randomUUID(),
58
+ input: operationInput,
59
+ intent,
60
+ lineage: parentOperationId,
61
+ triggeredBy: parentOperationId ? "user" : undefined,
62
+ environmentId,
63
+ partitionId,
64
+ envoyId: targetEnvoy?.id,
65
+ version: version ?? "",
66
+ status: "pending",
67
+ variables: resolved,
68
+ debriefEntryIds: [],
69
+ createdAt: new Date(),
70
+ ...(requireApproval ? { forceManualApproval: true } : {}),
71
+ };
72
+ deployments.save(deployment);
73
+ telemetry.record({ actor: (request.user?.email) ?? "anonymous", action: "operation.created", target: { type: "deployment", id: deployment.id }, details: { artifactId, environmentId, partitionId, envoyId } });
74
+ // Dispatch planning to the appropriate envoy asynchronously.
75
+ // The envoy reasons about the deployment (read-only) and POSTs back a plan,
76
+ // which transitions the deployment to awaiting_approval.
77
+ if (envoyRegistry) {
78
+ // Find the target envoy: explicit envoyId > environment-assigned > first available
79
+ const planningEnvoy = targetEnvoy
80
+ ?? (environment ? envoyRegistry.findForEnvironment(environment.name) : undefined)
81
+ ?? envoyRegistry.list()[0];
82
+ const needsArtifact = deployment.input.type === "deploy";
83
+ if (planningEnvoy && (!needsArtifact || artifact)) {
84
+ const planningClient = new EnvoyClient(planningEnvoy.url);
85
+ const environmentForPlanning = environment
86
+ ? { id: environment.id, name: environment.name, variables: environment.variables }
87
+ : { id: `direct:${planningEnvoy.id}`, name: planningEnvoy.name, variables: {} };
88
+ // Composite: orchestrate child planning separately — do not send composite to envoy directly
89
+ if (deployment.input.type === "composite") {
90
+ planCompositeChildren(deployment, envoyRegistry, planningEnvoy).catch((err) => {
91
+ const dep = deployments.get(deployment.id);
92
+ if (dep && (dep.status === "pending" || dep.status === "planning")) {
93
+ dep.status = "failed";
94
+ dep.failureReason = `Composite planning failed unexpectedly: ${err instanceof Error ? err.message : String(err)}`;
95
+ deployments.save(dep);
96
+ }
97
+ });
98
+ return;
99
+ }
100
+ planningClient.requestPlan({
101
+ operationId: deployment.id,
102
+ operationType: deployment.input.type,
103
+ intent: deployment.intent ?? (deployment.input.type === "trigger"
104
+ ? `Monitor: ${deployment.input.condition}. When triggered: ${deployment.input.responseIntent}`
105
+ : undefined),
106
+ ...(deployment.input.type === "trigger" ? {
107
+ triggerCondition: deployment.input.condition,
108
+ triggerResponseIntent: deployment.input.responseIntent,
109
+ } : {}),
110
+ ...(artifact ? {
111
+ artifact: {
112
+ id: artifact.id,
113
+ name: artifact.name,
114
+ type: artifact.type,
115
+ analysis: {
116
+ summary: artifact.analysis.summary,
117
+ dependencies: artifact.analysis.dependencies,
118
+ configurationExpectations: artifact.analysis.configurationExpectations,
119
+ deploymentIntent: artifact.analysis.deploymentIntent,
120
+ confidence: artifact.analysis.confidence,
121
+ },
122
+ },
123
+ } : {}),
124
+ ...(deployment.input.type === "investigate" && "allowWrite" in deployment.input
125
+ ? { allowWrite: deployment.input.allowWrite }
126
+ : {}),
127
+ environment: environmentForPlanning,
128
+ partition: partition
129
+ ? { id: partition.id, name: partition.name, variables: partition.variables }
130
+ : undefined,
131
+ version: deployment.version ?? "",
132
+ resolvedVariables: resolved,
133
+ }).then((result) => {
134
+ const dep = deployments.get(deployment.id);
135
+ if (!dep || dep.status !== "pending")
136
+ return;
137
+ dep.plan = result.plan;
138
+ dep.rollbackPlan = result.rollbackPlan;
139
+ dep.envoyId = planningEnvoy.id;
140
+ // Trigger operations: construct MonitoringDirective from plan, present for approval
141
+ if (dep.input.type === "trigger" && !result.blocked) {
142
+ const triggerInput = dep.input;
143
+ // Use probes from the envoy's trigger planning response (embedded in scriptedPlan reasoning),
144
+ // or fall back to a default probe. The envoy's planTrigger generates these.
145
+ const directive = {
146
+ id: dep.id,
147
+ operationId: dep.id,
148
+ probes: [{
149
+ command: "echo 0",
150
+ label: "default-probe",
151
+ parseAs: "numeric",
152
+ }],
153
+ intervalMs: result.intervalMs ?? 60_000,
154
+ cooldownMs: result.cooldownMs ?? 300_000,
155
+ condition: triggerInput.condition,
156
+ responseIntent: triggerInput.responseIntent,
157
+ responseType: "maintain",
158
+ environmentId: dep.environmentId,
159
+ partitionId: dep.partitionId,
160
+ status: "active",
161
+ };
162
+ dep.monitoringDirective = directive;
163
+ dep.triggerStatus = "active";
164
+ dep.status = "awaiting_approval";
165
+ dep.recommendation = computeRecommendation(dep, deployments, result.assessmentSummary);
166
+ deployments.save(dep);
167
+ // Debrief plan-generation entry is recorded by the envoy's planTrigger — no duplicate here.
168
+ return;
169
+ }
170
+ // Check approval mode for query/investigate operations with findings
171
+ if ((dep.input.type === "query" || dep.input.type === "investigate") &&
172
+ (result.queryFindings || result.investigationFindings)) {
173
+ if (result.queryFindings)
174
+ dep.queryFindings = result.queryFindings;
175
+ if (result.investigationFindings)
176
+ dep.investigationFindings = result.investigationFindings;
177
+ const currentSettings = settings.get();
178
+ const envLookup = (id) => environments.get(id)?.name;
179
+ const approvalMode = dep.forceManualApproval
180
+ ? "required"
181
+ : resolveApprovalMode(dep.input.type, dep.environmentId, currentSettings, envLookup);
182
+ if (approvalMode === "auto") {
183
+ // Auto-approve — findings are the deliverable
184
+ dep.status = "succeeded";
185
+ dep.completedAt = new Date();
186
+ deployments.save(dep);
187
+ const decisionType = dep.input.type === "query"
188
+ ? "query-findings"
189
+ : "investigation-findings";
190
+ const findings = result.queryFindings ?? result.investigationFindings;
191
+ debrief.record({
192
+ partitionId: dep.partitionId ?? null,
193
+ operationId: dep.id,
194
+ agent: "envoy",
195
+ decisionType,
196
+ decision: `${dep.input.type === "query" ? "Query" : "Investigation"} complete — ${findings.targetsSurveyed.length} target(s) surveyed`,
197
+ reasoning: findings.summary,
198
+ context: { targetsSurveyed: findings.targetsSurveyed, findingCount: findings.findings.length },
199
+ });
200
+ return;
201
+ }
202
+ // approvalMode === "required" — fall through to standard approval gate
203
+ }
204
+ if (result.blocked) {
205
+ // Unrecoverable precondition failures — block execution, do not present for approval
206
+ dep.status = "failed";
207
+ dep.failureReason = result.blockReason ?? "Plan blocked due to unrecoverable precondition failures";
208
+ deployments.save(dep);
209
+ debrief.record({
210
+ partitionId: dep.partitionId ?? null,
211
+ operationId: dep.id,
212
+ agent: "envoy",
213
+ decisionType: "plan-generation",
214
+ decision: `Operation plan blocked — infrastructure prerequisites not met`,
215
+ reasoning: result.blockReason ?? result.plan.reasoning,
216
+ context: { stepCount: result.plan.scriptedPlan.stepSummary.length, envoyId: planningEnvoy.id, blocked: true },
217
+ });
218
+ }
219
+ else {
220
+ // Plan is valid — transition to awaiting_approval
221
+ dep.status = "awaiting_approval";
222
+ dep.recommendation = computeRecommendation(dep, deployments, result.assessmentSummary);
223
+ deployments.save(dep);
224
+ debrief.record({
225
+ partitionId: dep.partitionId ?? null,
226
+ operationId: dep.id,
227
+ agent: "envoy",
228
+ decisionType: "plan-generation",
229
+ decision: `Operation plan generated with ${result.plan.scriptedPlan.stepSummary.length} steps`,
230
+ reasoning: result.plan.reasoning,
231
+ context: { stepCount: result.plan.scriptedPlan.stepSummary.length, envoyId: planningEnvoy.id, delta: result.delta },
232
+ });
233
+ }
234
+ }).catch((err) => {
235
+ // Planning failed — mark deployment failed so UI doesn't wait forever
236
+ const dep = deployments.get(deployment.id);
237
+ if (!dep || dep.status !== "pending")
238
+ return;
239
+ dep.status = "failed";
240
+ dep.failureReason = err instanceof Error ? err.message : "Planning failed";
241
+ deployments.save(dep);
242
+ debrief.record({
243
+ partitionId: dep.partitionId ?? null,
244
+ operationId: dep.id,
245
+ agent: "server",
246
+ decisionType: "deployment-failure",
247
+ decision: "Envoy planning failed",
248
+ reasoning: dep.failureReason,
249
+ context: { error: dep.failureReason, envoyId: planningEnvoy.id },
250
+ });
251
+ });
252
+ }
253
+ }
254
+ return reply.status(201).send({ deployment });
255
+ });
256
+ // Get deployment by ID
257
+ app.get("/api/operations/:id", { preHandler: [requirePermission("deployment.view")] }, async (request, reply) => {
258
+ const deployment = deployments.get(request.params.id);
259
+ if (!deployment) {
260
+ return reply.status(404).send({ error: "Operation not found" });
261
+ }
262
+ return {
263
+ deployment,
264
+ debrief: debrief.getByOperation(deployment.id),
265
+ };
266
+ });
267
+ // What's New — compare deployed artifact version against catalog latest
268
+ app.get("/api/operations/:id/whats-new", { preHandler: [requirePermission("deployment.view")] }, async (request, reply) => {
269
+ const deployment = deployments.get(request.params.id);
270
+ if (!deployment) {
271
+ return reply.status(404).send({ error: "Operation not found" });
272
+ }
273
+ const versions = artifactStore.getVersions(getArtifactId(deployment) ?? "");
274
+ const sorted = versions.slice().sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
275
+ const latest = sorted[0] ?? null;
276
+ const deployedVersion = deployment.version;
277
+ const latestVersion = latest?.version ?? null;
278
+ const isLatest = latestVersion === null || latestVersion === deployedVersion;
279
+ return {
280
+ deployedVersion,
281
+ latestVersion,
282
+ isLatest,
283
+ latestCreatedAt: latest?.createdAt ? new Date(latest.createdAt).toISOString() : null,
284
+ };
285
+ });
286
+ // List deployments (optionally filtered by partition, artifact, or envoy)
287
+ app.get("/api/operations", { preHandler: [requirePermission("deployment.view")] }, async (request) => {
288
+ const qParsed = DeploymentListQuerySchema.safeParse(request.query);
289
+ const { partitionId, artifactId, envoyId } = qParsed.success ? qParsed.data : {};
290
+ let list;
291
+ if (partitionId) {
292
+ list = deployments.getByPartition(partitionId);
293
+ }
294
+ else if (artifactId) {
295
+ list = deployments.getByArtifact(artifactId);
296
+ }
297
+ else {
298
+ list = deployments.list();
299
+ }
300
+ if (envoyId) {
301
+ list = list.filter((d) => d.envoyId === envoyId);
302
+ }
303
+ return { deployments: list };
304
+ });
305
+ // Submit a plan from envoy — transitions deployment to awaiting_approval
306
+ app.post("/api/operations/:id/plan", { preHandler: [requirePermission("deployment.create")] }, async (request, reply) => {
307
+ const deployment = deployments.get(request.params.id);
308
+ if (!deployment) {
309
+ return reply.status(404).send({ error: "Operation not found" });
310
+ }
311
+ const parsed = SubmitPlanSchema.safeParse(request.body);
312
+ if (!parsed.success) {
313
+ return reply.status(400).send({ error: "Invalid plan submission", details: parsed.error.format() });
314
+ }
315
+ if ((deployment.status) !== "pending" && (deployment.status) !== "planning") {
316
+ return reply.status(409).send({ error: `Cannot submit plan for operation in "${deployment.status}" status` });
317
+ }
318
+ deployment.plan = parsed.data.plan;
319
+ deployment.rollbackPlan = parsed.data.rollbackPlan;
320
+ deployment.status = "awaiting_approval";
321
+ // Generate recommendation from enrichment context
322
+ deployment.recommendation = computeRecommendation(deployment, deployments);
323
+ deployments.save(deployment);
324
+ debrief.record({
325
+ partitionId: deployment.partitionId ?? null,
326
+ operationId: deployment.id,
327
+ agent: "envoy",
328
+ decisionType: "plan-generation",
329
+ decision: `Operation plan submitted with ${parsed.data.plan.scriptedPlan.stepSummary.length} steps`,
330
+ reasoning: parsed.data.plan.reasoning,
331
+ context: { stepCount: parsed.data.plan.scriptedPlan.stepSummary.length },
332
+ });
333
+ return reply.status(200).send({ deployment });
334
+ });
335
+ // Approve a deployment plan
336
+ app.post("/api/operations/:id/approve", { preHandler: [requirePermission("deployment.approve")] }, async (request, reply) => {
337
+ const deployment = deployments.get(request.params.id);
338
+ if (!deployment) {
339
+ return reply.status(404).send({ error: "Operation not found" });
340
+ }
341
+ const parsed = ApproveDeploymentSchema.safeParse(request.body);
342
+ if (!parsed.success) {
343
+ return reply.status(400).send({ error: parsed.error.message });
344
+ }
345
+ if ((deployment.status) !== "awaiting_approval") {
346
+ return reply.status(409).send({ error: `Cannot approve operation in "${deployment.status}" status — must be "awaiting_approval"` });
347
+ }
348
+ // Transition deployment status
349
+ deployment.approvedBy = parsed.data.approvedBy;
350
+ deployment.approvedAt = new Date();
351
+ deployment.status = "approved";
352
+ deployments.save(deployment);
353
+ const actor = (request.user?.email) ?? parsed.data.approvedBy;
354
+ // Record approval in debrief
355
+ debrief.record({
356
+ partitionId: deployment.partitionId ?? null,
357
+ operationId: deployment.id,
358
+ agent: "server",
359
+ decisionType: "system",
360
+ decision: `Operation approved by ${actor}`,
361
+ reasoning: parsed.data.modifications
362
+ ? `Approved with modifications: ${parsed.data.modifications}`
363
+ : "Approved without modifications",
364
+ context: { approvedBy: actor },
365
+ actor: request.user?.email,
366
+ });
367
+ telemetry.record({ actor, action: "operation.approved", target: { type: "deployment", id: deployment.id }, details: { modifications: parsed.data.modifications } });
368
+ telemetry.record({
369
+ actor,
370
+ action: parsed.data.modifications ? "agent.recommendation.overridden" : "agent.recommendation.followed",
371
+ target: { type: "deployment", id: deployment.id },
372
+ details: parsed.data.modifications
373
+ ? { modifications: parsed.data.modifications }
374
+ : { planStepCount: deployment.plan?.scriptedPlan.stepSummary.length ?? 0 },
375
+ });
376
+ // Composite operations: execute children sequentially
377
+ if (deployment.input.type === "composite") {
378
+ deployment.status = "running";
379
+ deployments.save(deployment);
380
+ const compositeChildren = deployments.list()
381
+ .filter((d) => d.lineage === deployment.id)
382
+ .sort((a, b) => (a.sequenceIndex ?? 0) - (b.sequenceIndex ?? 0));
383
+ // Approve all children before executing sequentially
384
+ for (const child of compositeChildren) {
385
+ child.approvedBy = parsed.data.approvedBy;
386
+ child.approvedAt = new Date();
387
+ child.status = "approved";
388
+ deployments.save(child);
389
+ }
390
+ executeCompositeSequentially(deployment.id, compositeChildren.map((c) => c.id)).catch((err) => {
391
+ const dep = deployments.get(deployment.id);
392
+ if (dep && dep.status === "running") {
393
+ dep.status = "failed";
394
+ dep.failureReason = `Composite execution failed unexpectedly: ${err instanceof Error ? err.message : String(err)}`;
395
+ dep.completedAt = new Date();
396
+ deployments.save(dep);
397
+ }
398
+ });
399
+ return { deployment, approved: true };
400
+ }
401
+ // Trigger operations: install monitoring directive on envoy
402
+ if (deployment.input.type === "trigger" && deployment.monitoringDirective && envoyRegistry) {
403
+ const targetEnvoyForTrigger = deployment.envoyId
404
+ ? envoyRegistry.get(deployment.envoyId)
405
+ : envoyRegistry.list()[0];
406
+ if (targetEnvoyForTrigger) {
407
+ const triggerClient = new EnvoyClient(targetEnvoyForTrigger.url);
408
+ deployment.status = "running";
409
+ deployment.triggerStatus = "active";
410
+ deployments.save(deployment);
411
+ triggerClient.installMonitoringDirective(deployment.monitoringDirective).then(() => {
412
+ deployment.status = "succeeded";
413
+ deployment.completedAt = new Date();
414
+ deployments.save(deployment);
415
+ debrief.record({
416
+ partitionId: deployment.partitionId ?? null,
417
+ operationId: deployment.id,
418
+ agent: "server",
419
+ decisionType: "trigger-activated",
420
+ decision: `Monitoring directive installed on ${targetEnvoyForTrigger.name}`,
421
+ reasoning: `Trigger activated: monitoring "${deployment.monitoringDirective.condition}" every ${deployment.monitoringDirective.intervalMs / 1000}s with ${deployment.monitoringDirective.cooldownMs / 1000}s cooldown`,
422
+ context: { envoyId: targetEnvoyForTrigger.id, directiveId: deployment.monitoringDirective.id },
423
+ });
424
+ telemetry.record({ actor, action: "trigger.activated", target: { type: "trigger", id: deployment.id }, details: { envoyId: targetEnvoyForTrigger.id } });
425
+ }).catch((err) => {
426
+ deployment.status = "failed";
427
+ deployment.triggerStatus = "disabled";
428
+ deployment.failureReason = err instanceof Error ? err.message : "Failed to install monitoring directive";
429
+ deployments.save(deployment);
430
+ debrief.record({
431
+ partitionId: deployment.partitionId ?? null,
432
+ operationId: deployment.id,
433
+ agent: "server",
434
+ decisionType: "deployment-failure",
435
+ decision: "Failed to install monitoring directive on envoy",
436
+ reasoning: deployment.failureReason,
437
+ context: { error: deployment.failureReason },
438
+ });
439
+ });
440
+ }
441
+ }
442
+ // Normal operations: dispatch approved plan to envoy for execution
443
+ else if (envoyClient && deployment.plan && deployment.rollbackPlan) {
444
+ const artifact = artifactStore.get(getArtifactId(deployment) ?? "");
445
+ const serverPort = process.env.PORT ?? "9410";
446
+ const serverUrl = process.env.SYNTH_SERVER_URL ?? `http://localhost:${serverPort}`;
447
+ const progressCallbackUrl = `${serverUrl}/api/operations/${deployment.id}/progress`;
448
+ const callbackToken = envoyRegistry?.list().find(r => r.url === envoyClient.url)?.token;
449
+ deployment.status = "running";
450
+ deployments.save(deployment);
451
+ // Fire-and-forget: execution runs async, progress comes via callback
452
+ envoyClient.executeApprovedPlan({
453
+ operationId: deployment.id,
454
+ plan: deployment.plan,
455
+ rollbackPlan: deployment.rollbackPlan,
456
+ artifactType: artifact?.type ?? "unknown",
457
+ artifactName: artifact?.name ?? "unknown",
458
+ environmentId: deployment.environmentId ?? "",
459
+ progressCallbackUrl,
460
+ callbackToken,
461
+ }).catch((err) => {
462
+ // Execution dispatch failed — record failure
463
+ deployment.status = "failed";
464
+ deployment.failureReason = err instanceof Error ? err.message : "Execution dispatch failed";
465
+ deployments.save(deployment);
466
+ debrief.record({
467
+ partitionId: deployment.partitionId ?? null,
468
+ operationId: deployment.id,
469
+ agent: "server",
470
+ decisionType: "deployment-failure",
471
+ decision: "Failed to dispatch approved plan to envoy",
472
+ reasoning: deployment.failureReason,
473
+ context: { error: deployment.failureReason },
474
+ });
475
+ });
476
+ }
477
+ return { deployment, approved: true };
478
+ });
479
+ // Reject a deployment plan
480
+ app.post("/api/operations/:id/reject", { preHandler: [requirePermission("deployment.reject")] }, async (request, reply) => {
481
+ const deployment = deployments.get(request.params.id);
482
+ if (!deployment) {
483
+ return reply.status(404).send({ error: "Operation not found" });
484
+ }
485
+ const parsed = RejectDeploymentSchema.safeParse(request.body);
486
+ if (!parsed.success) {
487
+ return reply.status(400).send({ error: parsed.error.message });
488
+ }
489
+ if ((deployment.status) !== "awaiting_approval") {
490
+ return reply.status(409).send({ error: `Cannot reject operation in "${deployment.status}" status — must be "awaiting_approval"` });
491
+ }
492
+ // Transition deployment status and store rejection reason
493
+ deployment.status = "rejected";
494
+ deployment.rejectionReason = parsed.data.reason;
495
+ deployments.save(deployment);
496
+ const actor = (request.user?.email) ?? "anonymous";
497
+ // Record rejection in debrief
498
+ debrief.record({
499
+ partitionId: deployment.partitionId ?? null,
500
+ operationId: deployment.id,
501
+ agent: "server",
502
+ decisionType: "system",
503
+ decision: "Operation plan rejected",
504
+ reasoning: parsed.data.reason,
505
+ context: { reason: parsed.data.reason },
506
+ actor: request.user?.email,
507
+ });
508
+ telemetry.record({ actor, action: "operation.rejected", target: { type: "deployment", id: deployment.id }, details: { reason: parsed.data.reason } });
509
+ return { deployment, rejected: true };
510
+ });
511
+ // Modify a deployment plan (user edits steps before approval)
512
+ app.post("/api/operations/:id/modify", { preHandler: [requirePermission("deployment.approve")] }, async (request, reply) => {
513
+ const deployment = deployments.get(request.params.id);
514
+ if (!deployment) {
515
+ return reply.status(404).send({ error: "Operation not found" });
516
+ }
517
+ const parsed = ModifyDeploymentPlanSchema.safeParse(request.body);
518
+ if (!parsed.success) {
519
+ return reply.status(400).send({ error: parsed.error.message });
520
+ }
521
+ if ((deployment.status) !== "awaiting_approval") {
522
+ return reply.status(409).send({ error: `Cannot modify operation in "${deployment.status}" status — must be "awaiting_approval"` });
523
+ }
524
+ if (!deployment.plan) {
525
+ return reply.status(409).send({ error: "Operation has no plan to modify" });
526
+ }
527
+ // Validate modified plan with envoy if available
528
+ if (envoyClient && deployment.plan.scriptedPlan) {
529
+ try {
530
+ const modifiedScript = {
531
+ ...deployment.plan.scriptedPlan,
532
+ executionScript: parsed.data.executionScript,
533
+ ...(parsed.data.rollbackScript !== undefined ? { rollbackScript: parsed.data.rollbackScript } : {}),
534
+ };
535
+ const validation = await envoyClient.validatePlan(modifiedScript);
536
+ if (!validation.valid) {
537
+ return reply.status(422).send({
538
+ error: "Modified plan failed envoy validation",
539
+ violations: validation.violations,
540
+ });
541
+ }
542
+ }
543
+ catch {
544
+ // Envoy unreachable — proceed without validation but note it
545
+ }
546
+ }
547
+ // Compute diff description
548
+ const oldScript = deployment.plan.scriptedPlan?.executionScript ?? "";
549
+ const newScript = parsed.data.executionScript;
550
+ const diffFromPreviousPlan = oldScript !== newScript
551
+ ? "Execution script modified by user"
552
+ : "Plan metadata changed (script unchanged)";
553
+ // Apply modifications
554
+ deployment.plan = {
555
+ ...deployment.plan,
556
+ scriptedPlan: {
557
+ ...deployment.plan.scriptedPlan,
558
+ executionScript: parsed.data.executionScript,
559
+ ...(parsed.data.rollbackScript !== undefined ? { rollbackScript: parsed.data.rollbackScript } : {}),
560
+ },
561
+ diffFromPreviousPlan,
562
+ };
563
+ deployments.save(deployment);
564
+ const actor = (request.user?.email) ?? "anonymous";
565
+ // Record modification in debrief
566
+ debrief.record({
567
+ partitionId: deployment.partitionId ?? null,
568
+ operationId: deployment.id,
569
+ agent: "server",
570
+ decisionType: "plan-modification",
571
+ decision: `Operation plan modified by ${actor}`,
572
+ reasoning: parsed.data.reason,
573
+ context: {
574
+ modifiedBy: actor,
575
+ reason: parsed.data.reason,
576
+ },
577
+ actor: request.user?.email,
578
+ });
579
+ telemetry.record({
580
+ actor,
581
+ action: "operation.modified",
582
+ target: { type: "deployment", id: deployment.id },
583
+ details: { reason: parsed.data.reason },
584
+ });
585
+ telemetry.record({
586
+ actor,
587
+ action: "agent.recommendation.overridden",
588
+ target: { type: "deployment", id: deployment.id },
589
+ details: { reason: parsed.data.reason, diff: diffFromPreviousPlan },
590
+ });
591
+ return { deployment, modified: true };
592
+ });
593
+ // Replan a deployment with user feedback — triggers a new LLM planning pass
594
+ app.post("/api/operations/:id/replan", { preHandler: [requirePermission("deployment.approve")] }, async (request, reply) => {
595
+ const deploymentId = request.params.id;
596
+ const deployment = deployments.get(deploymentId);
597
+ if (!deployment) {
598
+ return reply.status(404).send({ error: "Operation not found" });
599
+ }
600
+ if ((deployment.status) !== "awaiting_approval") {
601
+ return reply.status(409).send({ error: `Cannot replan operation in "${deployment.status}" status — must be "awaiting_approval"` });
602
+ }
603
+ const parsed = ReplanDeploymentSchema.safeParse(request.body);
604
+ if (!parsed.success) {
605
+ return reply.status(400).send({ error: parsed.error.message });
606
+ }
607
+ const artifact = artifactStore.get(getArtifactId(deployment) ?? "");
608
+ if (!artifact) {
609
+ return reply.status(404).send({ error: `Artifact not found: ${getArtifactId(deployment)}` });
610
+ }
611
+ const environment = deployment.environmentId ? environments.get(deployment.environmentId) : undefined;
612
+ const partition = deployment.partitionId ? partitions.get(deployment.partitionId) : undefined;
613
+ const planningEnvoy = deployment.envoyId ? envoyRegistry?.get(deployment.envoyId) : envoyRegistry?.list()[0];
614
+ if (!planningEnvoy) {
615
+ return reply.status(422).send({ error: "No envoy available for replanning" });
616
+ }
617
+ // Validate feedback with LLM before triggering expensive replan
618
+ const planningClientForValidation = new EnvoyClient(planningEnvoy.url);
619
+ try {
620
+ const validation = await planningClientForValidation.validateRefinementFeedback({
621
+ feedback: parsed.data.feedback,
622
+ currentPlanSummary: (deployment.plan?.scriptedPlan?.stepSummary ?? []).map((s) => ({
623
+ description: s.description,
624
+ reversible: s.reversible,
625
+ })),
626
+ artifactName: artifact?.name ?? "unknown",
627
+ environmentName: environment?.name ?? "unknown",
628
+ });
629
+ if (validation.mode === "rejection") {
630
+ return reply.status(422).send({ error: validation.message, mode: "rejection" });
631
+ }
632
+ if (validation.mode === "response") {
633
+ return reply.status(200).send({ mode: "response", message: validation.message });
634
+ }
635
+ // mode === "replan" — fall through to full replan
636
+ }
637
+ catch {
638
+ // Validation call failed — proceed with replan rather than blocking the user
639
+ }
640
+ deployment.status = "planning";
641
+ deployments.save(deployment);
642
+ const planningClient = new EnvoyClient(planningEnvoy.url);
643
+ const environmentForPlanning = environment
644
+ ? { id: environment.id, name: environment.name, variables: environment.variables }
645
+ : { id: `direct:${planningEnvoy.id}`, name: planningEnvoy.name, variables: {} };
646
+ let result;
647
+ try {
648
+ result = await planningClient.requestPlan({
649
+ operationId: deploymentId,
650
+ artifact: {
651
+ id: artifact.id,
652
+ name: artifact.name,
653
+ type: artifact.type,
654
+ analysis: {
655
+ summary: artifact.analysis.summary,
656
+ dependencies: artifact.analysis.dependencies,
657
+ configurationExpectations: artifact.analysis.configurationExpectations,
658
+ deploymentIntent: artifact.analysis.deploymentIntent,
659
+ confidence: artifact.analysis.confidence,
660
+ },
661
+ },
662
+ environment: environmentForPlanning,
663
+ partition: partition
664
+ ? { id: partition.id, name: partition.name, variables: partition.variables }
665
+ : undefined,
666
+ version: deployment.version ?? "",
667
+ resolvedVariables: deployment.variables,
668
+ refinementFeedback: parsed.data.feedback,
669
+ });
670
+ }
671
+ catch (err) {
672
+ const dep = deployments.get(deploymentId);
673
+ if (dep) {
674
+ dep.status = "awaiting_approval";
675
+ deployments.save(dep);
676
+ }
677
+ return reply.status(500).send({ error: err instanceof Error ? err.message : "Replanning failed" });
678
+ }
679
+ const dep = deployments.get(deploymentId);
680
+ if (!dep) {
681
+ return reply.status(404).send({ error: "Operation not found after replanning" });
682
+ }
683
+ dep.plan = result.plan;
684
+ dep.rollbackPlan = result.rollbackPlan;
685
+ dep.recommendation = computeRecommendation(dep, deployments, result.assessmentSummary);
686
+ dep.status = "awaiting_approval";
687
+ deployments.save(dep);
688
+ debrief.record({
689
+ partitionId: dep.partitionId ?? null,
690
+ operationId: dep.id,
691
+ agent: "envoy",
692
+ decisionType: "plan-generation",
693
+ decision: `Plan regenerated with user feedback (${result.plan.scriptedPlan.stepSummary.length} steps)`,
694
+ reasoning: result.plan.reasoning,
695
+ context: { stepCount: result.plan.scriptedPlan.stepSummary.length, envoyId: planningEnvoy.id, refinementFeedback: parsed.data.feedback },
696
+ });
697
+ return { deployment: dep, replanned: true };
698
+ });
699
+ // Get cross-system enrichment context for a deployment
700
+ app.get("/api/operations/:id/context", { preHandler: [requirePermission("deployment.view")] }, async (request, reply) => {
701
+ const deployment = deployments.get(request.params.id);
702
+ if (!deployment) {
703
+ return reply.status(404).send({ error: "Operation not found" });
704
+ }
705
+ const now = new Date();
706
+ const twentyFourHoursAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
707
+ // Count recent operations to the same environment (only meaningful when environmentId is set)
708
+ const recentOperationsToEnv = deployment.environmentId
709
+ ? deployments.countByEnvironment(deployment.environmentId, twentyFourHoursAgo)
710
+ : 0;
711
+ // Check if the same artifact version was previously rolled back
712
+ const previouslyRolledBack = deployment.version
713
+ ? deployments.findByArtifactVersion(getArtifactId(deployment) ?? "", deployment.version, "rolled_back").length > 0
714
+ : false;
715
+ // Check for other in-progress operations to the same environment
716
+ const conflictingOperations = deployment.environmentId
717
+ ? deployments.list()
718
+ .filter((d) => d.environmentId === deployment.environmentId &&
719
+ d.id !== deployment.id &&
720
+ ((d.status) === "running" || (d.status) === "approved" || (d.status) === "awaiting_approval"))
721
+ .map((d) => d.id)
722
+ : [];
723
+ // Find last operation to the same environment
724
+ const lastDeploy = deployment.environmentId
725
+ ? deployments.findLatestByEnvironment(deployment.environmentId)
726
+ : undefined;
727
+ const lastOperationToEnv = lastDeploy && lastDeploy.id !== deployment.id
728
+ ? {
729
+ id: lastDeploy.id,
730
+ status: lastDeploy.status,
731
+ version: lastDeploy.version ?? "",
732
+ completedAt: lastDeploy.completedAt,
733
+ }
734
+ : undefined;
735
+ const enrichment = {
736
+ recentOperationsToEnv,
737
+ previouslyRolledBack,
738
+ conflictingOperations,
739
+ lastOperationToEnv,
740
+ };
741
+ return {
742
+ enrichment,
743
+ recommendation: deployment.recommendation ?? computeRecommendation(deployment, deployments),
744
+ };
745
+ });
746
+ // Request a post-hoc rollback plan — asks the envoy to reason about
747
+ // what actually ran and produce a targeted rollback plan
748
+ app.post("/api/operations/:id/request-rollback-plan", { preHandler: [requirePermission("deployment.approve")] }, async (request, reply) => {
749
+ const deployment = deployments.get(request.params.id);
750
+ if (!deployment) {
751
+ return reply.status(404).send({ error: "Operation not found" });
752
+ }
753
+ const finishedStatuses = new Set(["succeeded", "failed", "rolled_back"]);
754
+ if (!finishedStatuses.has(deployment.status)) {
755
+ return reply.status(409).send({
756
+ error: `Cannot request rollback plan for operation in "${deployment.status}" status — operation must be finished`,
757
+ });
758
+ }
759
+ const artifact = artifactStore.get(getArtifactId(deployment) ?? "");
760
+ if (!artifact) {
761
+ return reply.status(404).send({ error: "Artifact not found" });
762
+ }
763
+ // Determine which envoy to ask
764
+ const targetEnvoy = deployment.envoyId
765
+ ? envoyRegistry?.get(deployment.envoyId)
766
+ : envoyRegistry?.list()[0];
767
+ if (!targetEnvoy) {
768
+ return reply.status(503).send({ error: "No envoy available to generate rollback plan" });
769
+ }
770
+ const environment = deployment.environmentId ? environments.get(deployment.environmentId) : undefined;
771
+ // Build the list of completed steps from execution record (or plan step summaries as fallback)
772
+ const completedSteps = deployment.executionRecord?.steps.map((s) => ({
773
+ description: s.description,
774
+ action: "script-step",
775
+ target: "",
776
+ status: s.status,
777
+ output: s.output ?? s.error,
778
+ })) ?? deployment.plan?.scriptedPlan?.stepSummary.map((s) => ({
779
+ description: s.description,
780
+ action: "script-step",
781
+ target: "",
782
+ status: "completed",
783
+ })) ?? [];
784
+ const rollbackClient = new EnvoyClient(targetEnvoy.url);
785
+ try {
786
+ const rollbackPlan = await rollbackClient.requestRollbackPlan({
787
+ operationId: deployment.id,
788
+ artifact: {
789
+ name: artifact.name,
790
+ type: artifact.type,
791
+ analysis: {
792
+ summary: artifact.analysis.summary,
793
+ dependencies: artifact.analysis.dependencies,
794
+ configurationExpectations: artifact.analysis.configurationExpectations,
795
+ deploymentIntent: artifact.analysis.deploymentIntent,
796
+ confidence: artifact.analysis.confidence,
797
+ },
798
+ },
799
+ environment: {
800
+ id: deployment.environmentId ?? "",
801
+ name: environment?.name ?? deployment.environmentId ?? "unknown",
802
+ },
803
+ completedSteps,
804
+ deployedVariables: deployment.variables,
805
+ version: deployment.version ?? "",
806
+ failureReason: deployment.failureReason ?? undefined,
807
+ });
808
+ // Store the generated rollback plan on the deployment
809
+ deployment.rollbackPlan = rollbackPlan;
810
+ deployments.save(deployment);
811
+ const actor = (request.user?.email) ?? "anonymous";
812
+ debrief.record({
813
+ partitionId: deployment.partitionId ?? null,
814
+ operationId: deployment.id,
815
+ agent: "server",
816
+ decisionType: "plan-generation",
817
+ decision: `Rollback plan requested and generated for ${artifact.name} v${deployment.version}`,
818
+ reasoning: rollbackPlan.reasoning,
819
+ context: {
820
+ requestedBy: actor,
821
+ stepCount: rollbackPlan.scriptedPlan.stepSummary.length,
822
+ envoyId: targetEnvoy.id,
823
+ deploymentStatus: deployment.status,
824
+ },
825
+ actor: request.user?.email,
826
+ });
827
+ telemetry.record({
828
+ actor,
829
+ action: "deployment.rollback-plan-requested",
830
+ target: { type: "deployment", id: deployment.id },
831
+ details: { stepCount: rollbackPlan.scriptedPlan.stepSummary.length },
832
+ });
833
+ return reply.status(200).send({ deployment, rollbackPlan });
834
+ }
835
+ catch (err) {
836
+ return reply.status(500).send({
837
+ error: "Failed to generate rollback plan",
838
+ details: err instanceof Error ? err.message : String(err),
839
+ });
840
+ }
841
+ });
842
+ // Execute rollback — runs the stored rollback plan against the envoy
843
+ app.post("/api/operations/:id/execute-rollback", { preHandler: [requirePermission("deployment.approve")] }, async (request, reply) => {
844
+ const deployment = deployments.get(request.params.id);
845
+ if (!deployment) {
846
+ return reply.status(404).send({ error: "Operation not found" });
847
+ }
848
+ if (!deployment.rollbackPlan) {
849
+ return reply.status(409).send({ error: "No rollback plan available — request one first" });
850
+ }
851
+ const finishedStatuses = new Set(["succeeded", "failed"]);
852
+ if (!finishedStatuses.has(deployment.status)) {
853
+ return reply.status(409).send({
854
+ error: `Cannot execute rollback for operation in "${deployment.status}" status`,
855
+ });
856
+ }
857
+ const artifact = artifactStore.get(getArtifactId(deployment) ?? "");
858
+ const targetEnvoy = deployment.envoyId
859
+ ? envoyRegistry?.get(deployment.envoyId)
860
+ : envoyRegistry?.list()[0];
861
+ if (!targetEnvoy) {
862
+ return reply.status(503).send({ error: "No envoy available to execute rollback" });
863
+ }
864
+ const actor = (request.user?.email) ?? "anonymous";
865
+ const serverPort = process.env.PORT ?? "9410";
866
+ const serverUrl = process.env.SYNTH_SERVER_URL ?? `http://localhost:${serverPort}`;
867
+ const progressCallbackUrl = `${serverUrl}/api/operations/${deployment.id}/progress`;
868
+ deployment.status = "running";
869
+ deployments.save(deployment);
870
+ debrief.record({
871
+ partitionId: deployment.partitionId ?? null,
872
+ operationId: deployment.id,
873
+ agent: "server",
874
+ decisionType: "rollback-execution",
875
+ decision: `Rollback execution initiated for ${artifact?.name ?? getArtifactId(deployment)} v${deployment.version}`,
876
+ reasoning: `Rollback requested by ${actor}. Executing ${deployment.rollbackPlan.scriptedPlan.stepSummary.length} rollback step(s).`,
877
+ context: { initiatedBy: actor, stepCount: deployment.rollbackPlan.scriptedPlan.stepSummary.length },
878
+ actor: request.user?.email,
879
+ });
880
+ telemetry.record({
881
+ actor,
882
+ action: "deployment.rollback-executed",
883
+ target: { type: "deployment", id: deployment.id },
884
+ details: { stepCount: deployment.rollbackPlan.scriptedPlan.stepSummary.length },
885
+ });
886
+ const rollbackClient = new EnvoyClient(targetEnvoy.url);
887
+ // Execute the rollback plan as if it were a forward plan — it IS a forward plan
888
+ // (just in the reverse direction). Use an empty no-op plan as the "rollback of rollback".
889
+ const emptyPlan = {
890
+ scriptedPlan: {
891
+ platform: "bash",
892
+ executionScript: "# No rollback of rollback",
893
+ dryRunScript: null,
894
+ rollbackScript: null,
895
+ reasoning: "No rollback of rollback.",
896
+ stepSummary: [],
897
+ },
898
+ reasoning: "No rollback of rollback.",
899
+ };
900
+ rollbackClient.executeApprovedPlan({
901
+ operationId: deployment.id,
902
+ plan: deployment.rollbackPlan,
903
+ rollbackPlan: emptyPlan,
904
+ artifactType: artifact?.type ?? "unknown",
905
+ artifactName: artifact?.name ?? "unknown",
906
+ environmentId: deployment.environmentId ?? "",
907
+ progressCallbackUrl,
908
+ callbackToken: targetEnvoy.token,
909
+ }).then((result) => {
910
+ const dep = deployments.get(deployment.id);
911
+ if (!dep)
912
+ return;
913
+ dep.status = result.success ? "rolled_back" : "failed";
914
+ if (!result.success) {
915
+ dep.failureReason = result.failureReason ?? "Rollback execution failed";
916
+ }
917
+ dep.completedAt = new Date();
918
+ deployments.save(dep);
919
+ debrief.record({
920
+ partitionId: dep.partitionId ?? null,
921
+ operationId: dep.id,
922
+ agent: "server",
923
+ decisionType: "rollback-execution",
924
+ decision: result.success
925
+ ? `Rollback completed successfully for ${artifact?.name ?? getArtifactId(dep)} v${dep.version}`
926
+ : `Rollback failed for ${artifact?.name ?? getArtifactId(dep)} v${dep.version}`,
927
+ reasoning: result.success
928
+ ? `All rollback steps executed successfully.`
929
+ : `Rollback failed: ${result.failureReason}`,
930
+ context: { success: result.success, failureReason: result.failureReason },
931
+ });
932
+ }).catch((err) => {
933
+ const dep = deployments.get(deployment.id);
934
+ if (!dep)
935
+ return;
936
+ dep.status = "failed";
937
+ dep.failureReason = err instanceof Error ? err.message : "Rollback execution dispatch failed";
938
+ deployments.save(dep);
939
+ });
940
+ return reply.status(202).send({ deployment, accepted: true });
941
+ });
942
+ // Retry (redeploy) — create a new deployment with the same parameters as the source
943
+ app.post("/api/operations/:id/retry", { preHandler: [requirePermission("deployment.create")] }, async (request, reply) => {
944
+ const source = deployments.get(request.params.id);
945
+ if (!source) {
946
+ return reply.status(404).send({ error: "Operation not found" });
947
+ }
948
+ // Calculate attempt number by following the retryOf chain
949
+ let attemptNumber = 1;
950
+ let cursor = source;
951
+ while (cursor?.retryOf) {
952
+ attemptNumber++;
953
+ cursor = deployments.get(cursor.retryOf);
954
+ }
955
+ attemptNumber++; // this new deployment is one more
956
+ // Validate artifact still exists
957
+ const artifact = artifactStore.get(getArtifactId(source) ?? "");
958
+ if (!artifact) {
959
+ return reply.status(404).send({ error: `Artifact not found: ${getArtifactId(source)}` });
960
+ }
961
+ // Validate environment still exists (if present on source)
962
+ const environment = source.environmentId ? environments.get(source.environmentId) : undefined;
963
+ if (source.environmentId && !environment) {
964
+ return reply.status(404).send({ error: `Environment not found: ${source.environmentId}` });
965
+ }
966
+ // Validate partition still exists (if present on source)
967
+ const partition = source.partitionId ? partitions.get(source.partitionId) : undefined;
968
+ if (source.partitionId && !partition) {
969
+ return reply.status(404).send({ error: `Partition not found: ${source.partitionId}` });
970
+ }
971
+ // Validate envoy still exists (if present on source)
972
+ const targetEnvoy = source.envoyId ? envoyRegistry?.get(source.envoyId) : undefined;
973
+ if (source.envoyId && !targetEnvoy) {
974
+ return reply.status(404).send({ error: `Envoy not found: ${source.envoyId}` });
975
+ }
976
+ // Resolve variables — same logic as POST /api/deployments
977
+ const envVars = environment ? environment.variables : {};
978
+ const partitionVars = partition?.variables ?? {};
979
+ const resolved = { ...partitionVars, ...envVars };
980
+ const deployment = {
981
+ id: crypto.randomUUID(),
982
+ input: source.input,
983
+ environmentId: source.environmentId,
984
+ partitionId: source.partitionId,
985
+ envoyId: targetEnvoy?.id,
986
+ version: source.version ?? "",
987
+ status: "pending",
988
+ variables: resolved,
989
+ retryOf: source.id,
990
+ debriefEntryIds: [],
991
+ createdAt: new Date(),
992
+ };
993
+ deployments.save(deployment);
994
+ const actor = (request.user?.email) ?? "anonymous";
995
+ telemetry.record({ actor, action: "operation.created", target: { type: "deployment", id: deployment.id }, details: { artifactId: getArtifactId(source), environmentId: source.environmentId, partitionId: source.partitionId, envoyId: source.envoyId, retryOf: source.id } });
996
+ // Record retry debrief entry
997
+ debrief.record({
998
+ partitionId: deployment.partitionId ?? null,
999
+ operationId: deployment.id,
1000
+ agent: "server",
1001
+ decisionType: "system",
1002
+ decision: `Retry of operation ${source.id} (attempt #${attemptNumber})`,
1003
+ reasoning: `User initiated retry of operation ${source.id}. Same artifact, version, environment, and partition.`,
1004
+ context: { retryOf: source.id, attemptNumber, actor },
1005
+ actor: request.user?.email,
1006
+ });
1007
+ // Dispatch planning — same logic as POST /api/deployments
1008
+ if (envoyRegistry) {
1009
+ const planningEnvoy = targetEnvoy
1010
+ ?? (environment ? envoyRegistry.findForEnvironment(environment.name) : undefined)
1011
+ ?? envoyRegistry.list()[0];
1012
+ if (planningEnvoy) {
1013
+ const planningClient = new EnvoyClient(planningEnvoy.url);
1014
+ const environmentForPlanning = environment
1015
+ ? { id: environment.id, name: environment.name, variables: environment.variables }
1016
+ : { id: `direct:${planningEnvoy.id}`, name: planningEnvoy.name, variables: {} };
1017
+ planningClient.requestPlan({
1018
+ operationId: deployment.id,
1019
+ artifact: {
1020
+ id: artifact.id,
1021
+ name: artifact.name,
1022
+ type: artifact.type,
1023
+ analysis: {
1024
+ summary: artifact.analysis.summary,
1025
+ dependencies: artifact.analysis.dependencies,
1026
+ configurationExpectations: artifact.analysis.configurationExpectations,
1027
+ deploymentIntent: artifact.analysis.deploymentIntent,
1028
+ confidence: artifact.analysis.confidence,
1029
+ },
1030
+ },
1031
+ environment: environmentForPlanning,
1032
+ partition: partition
1033
+ ? { id: partition.id, name: partition.name, variables: partition.variables }
1034
+ : undefined,
1035
+ version: deployment.version ?? "",
1036
+ resolvedVariables: resolved,
1037
+ }).then((result) => {
1038
+ const dep = deployments.get(deployment.id);
1039
+ if (!dep || dep.status !== "pending")
1040
+ return;
1041
+ dep.plan = result.plan;
1042
+ dep.rollbackPlan = result.rollbackPlan;
1043
+ dep.envoyId = planningEnvoy.id;
1044
+ if (result.blocked) {
1045
+ dep.status = "failed";
1046
+ dep.failureReason = result.blockReason ?? "Plan blocked due to unrecoverable precondition failures";
1047
+ deployments.save(dep);
1048
+ debrief.record({
1049
+ partitionId: dep.partitionId ?? null,
1050
+ operationId: dep.id,
1051
+ agent: "envoy",
1052
+ decisionType: "plan-generation",
1053
+ decision: `Operation plan blocked — infrastructure prerequisites not met`,
1054
+ reasoning: result.blockReason ?? result.plan.reasoning,
1055
+ context: { stepCount: result.plan.scriptedPlan.stepSummary.length, envoyId: planningEnvoy.id, blocked: true },
1056
+ });
1057
+ }
1058
+ else {
1059
+ dep.status = "awaiting_approval";
1060
+ dep.recommendation = computeRecommendation(dep, deployments, result.assessmentSummary);
1061
+ deployments.save(dep);
1062
+ debrief.record({
1063
+ partitionId: dep.partitionId ?? null,
1064
+ operationId: dep.id,
1065
+ agent: "envoy",
1066
+ decisionType: "plan-generation",
1067
+ decision: `Operation plan generated with ${result.plan.scriptedPlan.stepSummary.length} steps`,
1068
+ reasoning: result.plan.reasoning,
1069
+ context: { stepCount: result.plan.scriptedPlan.stepSummary.length, envoyId: planningEnvoy.id, delta: result.delta },
1070
+ });
1071
+ }
1072
+ }).catch((err) => {
1073
+ const dep = deployments.get(deployment.id);
1074
+ if (!dep || dep.status !== "pending")
1075
+ return;
1076
+ dep.status = "failed";
1077
+ dep.failureReason = err instanceof Error ? err.message : "Planning failed";
1078
+ deployments.save(dep);
1079
+ debrief.record({
1080
+ partitionId: dep.partitionId ?? null,
1081
+ operationId: dep.id,
1082
+ agent: "server",
1083
+ decisionType: "deployment-failure",
1084
+ decision: "Envoy planning failed",
1085
+ reasoning: dep.failureReason,
1086
+ context: { error: dep.failureReason, envoyId: planningEnvoy.id },
1087
+ });
1088
+ });
1089
+ }
1090
+ }
1091
+ return reply.status(201).send({ deployment, sourceDeploymentId: source.id, attemptNumber });
1092
+ });
1093
+ // Get deployment postmortem
1094
+ app.get("/api/operations/:id/postmortem", { preHandler: [requirePermission("deployment.view")] }, async (request, reply) => {
1095
+ const deployment = deployments.get(request.params.id);
1096
+ if (!deployment) {
1097
+ return reply.status(404).send({ error: "Operation not found" });
1098
+ }
1099
+ const entries = debrief.getByOperation(deployment.id);
1100
+ const postmortem = generatePostmortem(entries, deployment);
1101
+ const llmResult = await generatePostmortemAsync(entries, deployment, llm);
1102
+ return {
1103
+ postmortem,
1104
+ ...(llmResult.heuristicFallback ? {} : { llmPostmortem: llmResult.llmPostmortem }),
1105
+ };
1106
+ });
1107
+ // Get recent debrief entries (supports filtering by partition, decision type, and full-text search)
1108
+ app.get("/api/debrief", { preHandler: [requirePermission("deployment.view")] }, async (request) => {
1109
+ const qParsed = DebriefQuerySchema.safeParse(request.query);
1110
+ const { limit, partitionId, decisionType, q: searchQuery } = qParsed.success ? qParsed.data : {};
1111
+ const max = limit ?? 50;
1112
+ // Full-text search — takes priority over filters
1113
+ if (searchQuery) {
1114
+ let entries = debrief.search(searchQuery, max);
1115
+ if (partitionId)
1116
+ entries = entries.filter((e) => e.partitionId === partitionId);
1117
+ if (decisionType)
1118
+ entries = entries.filter((e) => e.decisionType === decisionType);
1119
+ return { entries };
1120
+ }
1121
+ // No filters — fast path
1122
+ if (!partitionId && !decisionType) {
1123
+ return { entries: debrief.getRecent(max) };
1124
+ }
1125
+ // Start with the most selective filter, then narrow
1126
+ let entries;
1127
+ if (partitionId && decisionType) {
1128
+ entries = debrief.getByPartition(partitionId).filter((e) => e.decisionType === decisionType);
1129
+ }
1130
+ else if (partitionId) {
1131
+ entries = debrief.getByPartition(partitionId);
1132
+ }
1133
+ else {
1134
+ entries = debrief.getByType(decisionType);
1135
+ }
1136
+ entries.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
1137
+ return { entries: entries.slice(0, max) };
1138
+ });
1139
+ // Pin/unpin an operation for quick-access
1140
+ // Static route registered before parameterized :id routes to avoid shadowing
1141
+ app.get("/api/operations/pinned", { preHandler: [requirePermission("deployment.view")] }, async () => {
1142
+ const ids = debrief.getPinnedOperationIds();
1143
+ const operations = ids.map((id) => deployments.get(id)).filter(Boolean);
1144
+ return { operations, pinnedIds: ids };
1145
+ });
1146
+ app.post("/api/operations/:id/pin", { preHandler: [requirePermission("deployment.view")] }, async (request) => {
1147
+ debrief.pinOperation(request.params.id);
1148
+ return { pinned: true };
1149
+ });
1150
+ app.delete("/api/operations/:id/pin", { preHandler: [requirePermission("deployment.view")] }, async (request) => {
1151
+ debrief.unpinOperation(request.params.id);
1152
+ return { pinned: false };
1153
+ });
1154
+ // ---------------------------------------------------------------------------
1155
+ // Progress streaming — envoy callback and SSE endpoints
1156
+ // ---------------------------------------------------------------------------
1157
+ // POST /api/deployments/:id/progress — receives progress events from envoy
1158
+ app.post("/api/operations/:id/progress", async (request, reply) => {
1159
+ if (!progressStore) {
1160
+ return reply.status(501).send({ error: "Progress streaming not configured" });
1161
+ }
1162
+ // Validate envoy token — this route is exempt from JWT auth
1163
+ if (envoyRegistry) {
1164
+ const authHeader = (request.headers.authorization ?? "");
1165
+ const token = authHeader.startsWith("Bearer ") ? authHeader.slice(7) : null;
1166
+ if (!token || !envoyRegistry.validateToken(token)) {
1167
+ return reply.status(401).send({ error: "Invalid or missing envoy token" });
1168
+ }
1169
+ }
1170
+ const parsed = ProgressEventSchema.safeParse(request.body);
1171
+ if (!parsed.success) {
1172
+ return reply.status(400).send({ error: "Invalid progress event", details: parsed.error.format() });
1173
+ }
1174
+ const event = parsed.data;
1175
+ // Validate the deploymentId in the URL matches the body
1176
+ if (event.deploymentId !== request.params.id) {
1177
+ return reply.status(400).send({ error: "Operation ID in URL does not match event body" });
1178
+ }
1179
+ progressStore.push(event);
1180
+ return reply.status(200).send({ received: true });
1181
+ });
1182
+ // GET /api/deployments/:id/stream — SSE endpoint for live progress
1183
+ // Auth is via ?token= query param since EventSource cannot send headers
1184
+ app.get("/api/operations/:id/stream", { preHandler: [requirePermission("deployment.view")] }, (request, reply) => {
1185
+ if (!progressStore) {
1186
+ reply.status(501).send({ error: "Progress streaming not configured" });
1187
+ return;
1188
+ }
1189
+ // Hijack the connection so Fastify does not finalize the response
1190
+ reply.hijack();
1191
+ // Set SSE headers
1192
+ reply.raw.writeHead(200, {
1193
+ "Content-Type": "text/event-stream",
1194
+ "Cache-Control": "no-cache",
1195
+ "Connection": "keep-alive",
1196
+ "X-Accel-Buffering": "no",
1197
+ });
1198
+ const deploymentId = request.params.id;
1199
+ // Check for Last-Event-ID header (reconnection with replay)
1200
+ const lastEventIdHeader = request.headers["last-event-id"];
1201
+ const lastEventId = lastEventIdHeader ? parseInt(String(lastEventIdHeader), 10) : 0;
1202
+ // Send catch-up events — either all (fresh connect) or since last ID (reconnect)
1203
+ const existing = lastEventId
1204
+ ? progressStore.getEventsSince(deploymentId, lastEventId)
1205
+ : progressStore.getEvents(deploymentId);
1206
+ for (const event of existing) {
1207
+ reply.raw.write(`id: ${event.id}\ndata: ${JSON.stringify(event)}\n\n`);
1208
+ }
1209
+ // Check if deployment already completed — if so, close after catch-up
1210
+ const lastEvent = existing[existing.length - 1];
1211
+ if (lastEvent?.type === "deployment-completed") {
1212
+ reply.raw.end();
1213
+ return;
1214
+ }
1215
+ // Subscribe to new events
1216
+ const listener = (event) => {
1217
+ try {
1218
+ reply.raw.write(`id: ${event.id}\ndata: ${JSON.stringify(event)}\n\n`);
1219
+ // Close the stream when deployment completes
1220
+ if (event.type === "deployment-completed") {
1221
+ reply.raw.end();
1222
+ }
1223
+ }
1224
+ catch {
1225
+ // Client disconnected — clean up
1226
+ progressStore.removeListener(deploymentId, listener);
1227
+ }
1228
+ };
1229
+ progressStore.addListener(deploymentId, listener);
1230
+ // Clean up on client disconnect
1231
+ request.raw.on("close", () => {
1232
+ progressStore.removeListener(deploymentId, listener);
1233
+ });
1234
+ });
1235
+ // -- Health reports from envoys (trigger system) ---------------------------
1236
+ app.post("/api/health-reports", async (request, reply) => {
1237
+ // Validate envoy token — same pattern as /api/envoy/report
1238
+ if (envoyRegistry) {
1239
+ const authHeader = (request.headers.authorization ?? "");
1240
+ const token = authHeader.startsWith("Bearer ") ? authHeader.slice(7) : null;
1241
+ if (!token || !envoyRegistry.validateToken(token)) {
1242
+ return reply.status(401).send({ error: "Invalid or missing envoy token" });
1243
+ }
1244
+ }
1245
+ const { HealthReportSchema } = await import("@synth-deploy/core");
1246
+ const parsed = HealthReportSchema.safeParse(request.body);
1247
+ if (!parsed.success) {
1248
+ return reply.status(400).send({ error: "Invalid health report", details: parsed.error.format() });
1249
+ }
1250
+ const report = parsed.data;
1251
+ // Find the trigger operation
1252
+ const triggerOp = deployments.get(report.triggerOperationId);
1253
+ if (!triggerOp || triggerOp.input.type !== "trigger") {
1254
+ return reply.status(404).send({ error: `Trigger operation not found: ${report.triggerOperationId}` });
1255
+ }
1256
+ // Record the health report
1257
+ debrief.record({
1258
+ partitionId: report.partitionId ?? null,
1259
+ operationId: triggerOp.id,
1260
+ agent: "envoy",
1261
+ decisionType: "health-report-received",
1262
+ decision: `Health report: ${report.summary}`,
1263
+ reasoning: `Trigger condition met on ${report.envoyId}. Probes: ${report.probeResults.map(p => `${p.label}=${p.parsedValue ?? p.output}`).join(", ")}`,
1264
+ context: { directiveId: report.directiveId, envoyId: report.envoyId, probeResults: report.probeResults },
1265
+ });
1266
+ // Deduplication: check for active child operations from this trigger
1267
+ const allOps = deployments.list();
1268
+ const activeChild = allOps.find((op) => op.lineage === triggerOp.id &&
1269
+ ["pending", "planning", "awaiting_approval", "approved", "running"].includes(op.status));
1270
+ if (activeChild) {
1271
+ // Suppress — record that we suppressed
1272
+ triggerOp.triggerSuppressedCount = (triggerOp.triggerSuppressedCount ?? 0) + 1;
1273
+ deployments.save(triggerOp);
1274
+ debrief.record({
1275
+ partitionId: report.partitionId ?? null,
1276
+ operationId: triggerOp.id,
1277
+ agent: "server",
1278
+ decisionType: "trigger-suppressed",
1279
+ decision: `Trigger suppressed — child operation ${activeChild.id} is still in progress (${activeChild.status})`,
1280
+ reasoning: `Deduplication: an operation spawned by this trigger is already active. Suppressed ${triggerOp.triggerSuppressedCount} time(s) total.`,
1281
+ context: { activeChildId: activeChild.id, activeChildStatus: activeChild.status, suppressedCount: triggerOp.triggerSuppressedCount },
1282
+ });
1283
+ return reply.status(200).send({ spawned: false, reason: "deduplicated", activeChildId: activeChild.id });
1284
+ }
1285
+ // Spawn child operation
1286
+ const triggerInput = triggerOp.input;
1287
+ const responseType = triggerOp.monitoringDirective?.responseType ?? "maintain";
1288
+ const childOp = {
1289
+ id: crypto.randomUUID(),
1290
+ input: responseType === "deploy"
1291
+ ? { type: "deploy", artifactId: "" }
1292
+ : { type: "maintain", intent: triggerInput.responseIntent },
1293
+ intent: triggerInput.responseIntent,
1294
+ lineage: triggerOp.id,
1295
+ triggeredBy: "trigger",
1296
+ environmentId: report.environmentId ?? triggerOp.environmentId,
1297
+ partitionId: report.partitionId ?? triggerOp.partitionId,
1298
+ envoyId: report.envoyId,
1299
+ version: "",
1300
+ status: "pending",
1301
+ variables: triggerOp.variables,
1302
+ debriefEntryIds: [],
1303
+ createdAt: new Date(),
1304
+ };
1305
+ deployments.save(childOp);
1306
+ // Update trigger stats
1307
+ triggerOp.triggerFireCount = (triggerOp.triggerFireCount ?? 0) + 1;
1308
+ triggerOp.triggerLastFiredAt = new Date();
1309
+ deployments.save(triggerOp);
1310
+ debrief.record({
1311
+ partitionId: childOp.partitionId ?? null,
1312
+ operationId: childOp.id,
1313
+ agent: "server",
1314
+ decisionType: "trigger-fired",
1315
+ decision: `Trigger fired — spawned child operation ${childOp.id}`,
1316
+ reasoning: `Condition "${triggerInput.condition}" met. Response: "${triggerInput.responseIntent}". Fire count: ${triggerOp.triggerFireCount}.`,
1317
+ context: { triggerId: triggerOp.id, envoyId: report.envoyId, fireCount: triggerOp.triggerFireCount },
1318
+ });
1319
+ telemetry.record({ actor: "agent", action: "trigger.fired", target: { type: "trigger", id: triggerOp.id }, details: { childOperationId: childOp.id } });
1320
+ // Dispatch planning for the child operation (same as new operation flow)
1321
+ if (envoyRegistry) {
1322
+ const childEnvoy = report.envoyId
1323
+ ? envoyRegistry.get(report.envoyId)
1324
+ : envoyRegistry.list()[0];
1325
+ if (childEnvoy) {
1326
+ const planningClient = new EnvoyClient(childEnvoy.url);
1327
+ const environment = childOp.environmentId ? environments.get(childOp.environmentId) : undefined;
1328
+ const environmentForPlanning = environment
1329
+ ? { id: environment.id, name: environment.name, variables: environment.variables }
1330
+ : { id: `direct:${childEnvoy.id}`, name: childEnvoy.name, variables: {} };
1331
+ planningClient.requestPlan({
1332
+ operationId: childOp.id,
1333
+ operationType: responseType,
1334
+ intent: childOp.intent,
1335
+ environment: environmentForPlanning,
1336
+ version: "",
1337
+ resolvedVariables: childOp.variables,
1338
+ }).then((result) => {
1339
+ const dep = deployments.get(childOp.id);
1340
+ if (!dep || dep.status !== "pending")
1341
+ return;
1342
+ dep.plan = result.plan;
1343
+ dep.rollbackPlan = result.rollbackPlan;
1344
+ dep.envoyId = childEnvoy.id;
1345
+ if (result.blocked) {
1346
+ dep.status = "failed";
1347
+ dep.failureReason = result.blockReason ?? "Plan blocked";
1348
+ deployments.save(dep);
1349
+ }
1350
+ else {
1351
+ dep.status = "awaiting_approval";
1352
+ dep.recommendation = computeRecommendation(dep, deployments, result.assessmentSummary);
1353
+ deployments.save(dep);
1354
+ }
1355
+ }).catch((err) => {
1356
+ const dep = deployments.get(childOp.id);
1357
+ if (!dep || dep.status !== "pending")
1358
+ return;
1359
+ dep.status = "failed";
1360
+ dep.failureReason = err instanceof Error ? err.message : "Planning failed";
1361
+ deployments.save(dep);
1362
+ });
1363
+ }
1364
+ }
1365
+ return reply.status(201).send({ spawned: true, childOperationId: childOp.id });
1366
+ });
1367
+ // -- Trigger management (pause/resume/disable) ----------------------------
1368
+ app.post("/api/operations/:id/trigger/pause", { preHandler: [requirePermission("deployment.approve")] }, async (request, reply) => {
1369
+ const op = deployments.get(request.params.id);
1370
+ if (!op || op.input.type !== "trigger") {
1371
+ return reply.status(404).send({ error: "Trigger operation not found" });
1372
+ }
1373
+ if (op.triggerStatus !== "active") {
1374
+ return reply.status(409).send({ error: `Cannot pause trigger in "${op.triggerStatus}" status` });
1375
+ }
1376
+ // Pause on envoy
1377
+ if (op.envoyId && envoyRegistry) {
1378
+ const envoy = envoyRegistry.get(op.envoyId);
1379
+ if (envoy) {
1380
+ const client = new EnvoyClient(envoy.url);
1381
+ await client.pauseMonitoringDirective(op.id);
1382
+ }
1383
+ }
1384
+ op.triggerStatus = "paused";
1385
+ if (op.monitoringDirective)
1386
+ op.monitoringDirective.status = "paused";
1387
+ deployments.save(op);
1388
+ const actor = (request.user?.email) ?? "anonymous";
1389
+ debrief.record({
1390
+ partitionId: op.partitionId ?? null,
1391
+ operationId: op.id,
1392
+ agent: "server",
1393
+ decisionType: "trigger-paused",
1394
+ decision: `Trigger paused by ${actor}`,
1395
+ reasoning: "User requested trigger pause",
1396
+ context: {},
1397
+ actor: request.user?.email,
1398
+ });
1399
+ telemetry.record({ actor, action: "trigger.paused", target: { type: "trigger", id: op.id }, details: {} });
1400
+ return { operation: op, paused: true };
1401
+ });
1402
+ app.post("/api/operations/:id/trigger/resume", { preHandler: [requirePermission("deployment.approve")] }, async (request, reply) => {
1403
+ const op = deployments.get(request.params.id);
1404
+ if (!op || op.input.type !== "trigger") {
1405
+ return reply.status(404).send({ error: "Trigger operation not found" });
1406
+ }
1407
+ if (op.triggerStatus !== "paused") {
1408
+ return reply.status(409).send({ error: `Cannot resume trigger in "${op.triggerStatus}" status` });
1409
+ }
1410
+ // Resume on envoy
1411
+ if (op.envoyId && envoyRegistry) {
1412
+ const envoy = envoyRegistry.get(op.envoyId);
1413
+ if (envoy) {
1414
+ const client = new EnvoyClient(envoy.url);
1415
+ await client.resumeMonitoringDirective(op.id);
1416
+ }
1417
+ }
1418
+ op.triggerStatus = "active";
1419
+ if (op.monitoringDirective)
1420
+ op.monitoringDirective.status = "active";
1421
+ deployments.save(op);
1422
+ const actor = (request.user?.email) ?? "anonymous";
1423
+ debrief.record({
1424
+ partitionId: op.partitionId ?? null,
1425
+ operationId: op.id,
1426
+ agent: "server",
1427
+ decisionType: "trigger-resumed",
1428
+ decision: `Trigger resumed by ${actor}`,
1429
+ reasoning: "User requested trigger resume",
1430
+ context: {},
1431
+ actor: request.user?.email,
1432
+ });
1433
+ telemetry.record({ actor, action: "trigger.resumed", target: { type: "trigger", id: op.id }, details: {} });
1434
+ return { operation: op, resumed: true };
1435
+ });
1436
+ app.post("/api/operations/:id/trigger/disable", { preHandler: [requirePermission("deployment.approve")] }, async (request, reply) => {
1437
+ const op = deployments.get(request.params.id);
1438
+ if (!op || op.input.type !== "trigger") {
1439
+ return reply.status(404).send({ error: "Trigger operation not found" });
1440
+ }
1441
+ // Remove from envoy
1442
+ if (op.envoyId && envoyRegistry) {
1443
+ const envoy = envoyRegistry.get(op.envoyId);
1444
+ if (envoy) {
1445
+ const client = new EnvoyClient(envoy.url);
1446
+ await client.removeMonitoringDirective(op.id).catch(() => { });
1447
+ }
1448
+ }
1449
+ op.triggerStatus = "disabled";
1450
+ if (op.monitoringDirective)
1451
+ op.monitoringDirective.status = "disabled";
1452
+ deployments.save(op);
1453
+ const actor = (request.user?.email) ?? "anonymous";
1454
+ debrief.record({
1455
+ partitionId: op.partitionId ?? null,
1456
+ operationId: op.id,
1457
+ agent: "server",
1458
+ decisionType: "trigger-disabled",
1459
+ decision: `Trigger disabled by ${actor}`,
1460
+ reasoning: "User requested trigger disable",
1461
+ context: {},
1462
+ actor: request.user?.email,
1463
+ });
1464
+ telemetry.record({ actor, action: "trigger.disabled", target: { type: "trigger", id: op.id }, details: {} });
1465
+ return { operation: op, disabled: true };
1466
+ });
1467
+ // ---------------------------------------------------------------------------
1468
+ // Composite operation helpers — defined inside registerOperationRoutes so
1469
+ // they close over the stores and registry.
1470
+ // ---------------------------------------------------------------------------
1471
+ async function planCompositeChildren(parentOp, _registry, planningEnvoy) {
1472
+ const compositeInput = parentOp.input;
1473
+ const childInputs = compositeInput.operations;
1474
+ if (childInputs.length === 0) {
1475
+ const dep = deployments.get(parentOp.id);
1476
+ if (dep) {
1477
+ dep.status = "failed";
1478
+ dep.failureReason = "Composite operation has no child operations";
1479
+ deployments.save(dep);
1480
+ }
1481
+ return;
1482
+ }
1483
+ const childIds = [];
1484
+ const environment = parentOp.environmentId ? environments.get(parentOp.environmentId) : undefined;
1485
+ const partition = parentOp.partitionId ? partitions.get(parentOp.partitionId) : undefined;
1486
+ for (let seqIdx = 0; seqIdx < childInputs.length; seqIdx++) {
1487
+ const childInput = childInputs[seqIdx];
1488
+ const childOp = {
1489
+ id: crypto.randomUUID(),
1490
+ input: childInput,
1491
+ intent: "intent" in childInput ? childInput.intent
1492
+ : childInput.type === "trigger" ? `Monitor: ${childInput.condition}`
1493
+ : undefined,
1494
+ lineage: parentOp.id,
1495
+ triggeredBy: "agent",
1496
+ environmentId: parentOp.environmentId,
1497
+ partitionId: parentOp.partitionId,
1498
+ envoyId: planningEnvoy.id,
1499
+ version: parentOp.version ?? "",
1500
+ status: "pending",
1501
+ variables: parentOp.variables,
1502
+ debriefEntryIds: [],
1503
+ createdAt: new Date(),
1504
+ sequenceIndex: seqIdx,
1505
+ };
1506
+ deployments.save(childOp);
1507
+ childIds.push(childOp.id);
1508
+ }
1509
+ debrief.record({
1510
+ partitionId: parentOp.partitionId ?? null,
1511
+ operationId: parentOp.id,
1512
+ agent: "server",
1513
+ decisionType: "composite-started",
1514
+ decision: `Composite operation started — planning ${childIds.length} child operation(s) sequentially`,
1515
+ reasoning: `Sequential composite: ${childInputs.map((c) => c.type).join(" → ")}`,
1516
+ context: { childIds, childCount: childIds.length, sequence: childInputs.map((c) => c.type) },
1517
+ });
1518
+ const environmentForPlanning = environment
1519
+ ? { id: environment.id, name: environment.name, variables: environment.variables }
1520
+ : { id: `direct:${planningEnvoy.id}`, name: planningEnvoy.name, variables: {} };
1521
+ let anyFailed = false;
1522
+ for (const childId of childIds) {
1523
+ const child = deployments.get(childId);
1524
+ if (!child)
1525
+ continue;
1526
+ const childInput = child.input;
1527
+ const childArtifact = childInput.type === "deploy"
1528
+ ? artifactStore.get(childInput.artifactId)
1529
+ : undefined;
1530
+ const planningClient = new EnvoyClient(planningEnvoy.url);
1531
+ try {
1532
+ const result = await planningClient.requestPlan({
1533
+ operationId: childId,
1534
+ operationType: childInput.type,
1535
+ intent: "intent" in childInput ? childInput.intent
1536
+ : childInput.type === "trigger" ? `Monitor: ${childInput.condition}`
1537
+ : undefined,
1538
+ ...(childArtifact ? {
1539
+ artifact: {
1540
+ id: childArtifact.id,
1541
+ name: childArtifact.name,
1542
+ type: childArtifact.type,
1543
+ analysis: childArtifact.analysis,
1544
+ },
1545
+ } : {}),
1546
+ ...(childInput.type === "investigate" && "allowWrite" in childInput
1547
+ ? { allowWrite: childInput.allowWrite }
1548
+ : {}),
1549
+ environment: environmentForPlanning,
1550
+ partition: partition ? { id: partition.id, name: partition.name, variables: partition.variables } : undefined,
1551
+ version: parentOp.version ?? "",
1552
+ resolvedVariables: parentOp.variables,
1553
+ });
1554
+ const childDep = deployments.get(childId);
1555
+ if (!childDep)
1556
+ continue;
1557
+ if (result.blocked) {
1558
+ childDep.status = "failed";
1559
+ childDep.failureReason = result.blockReason ?? "Plan blocked";
1560
+ deployments.save(childDep);
1561
+ anyFailed = true;
1562
+ const parentDep = deployments.get(parentOp.id);
1563
+ if (parentDep && parentDep.status === "pending") {
1564
+ parentDep.status = "failed";
1565
+ parentDep.failureReason = `Child operation (${childInput.type}) plan blocked: ${childDep.failureReason}`;
1566
+ deployments.save(parentDep);
1567
+ debrief.record({
1568
+ partitionId: parentDep.partitionId ?? null,
1569
+ operationId: parentDep.id,
1570
+ agent: "server",
1571
+ decisionType: "composite-failed",
1572
+ decision: `Child operation planning blocked — composite cannot proceed`,
1573
+ reasoning: childDep.failureReason,
1574
+ context: { childId, childType: childInput.type },
1575
+ });
1576
+ }
1577
+ break;
1578
+ }
1579
+ childDep.plan = result.plan;
1580
+ childDep.rollbackPlan = result.rollbackPlan;
1581
+ childDep.envoyId = planningEnvoy.id;
1582
+ if (childInput.type === "query" && result.queryFindings)
1583
+ childDep.queryFindings = result.queryFindings;
1584
+ if (childInput.type === "investigate" && result.investigationFindings)
1585
+ childDep.investigationFindings = result.investigationFindings;
1586
+ childDep.status = "awaiting_approval";
1587
+ deployments.save(childDep);
1588
+ debrief.record({
1589
+ partitionId: childDep.partitionId ?? null,
1590
+ operationId: childDep.id,
1591
+ agent: "envoy",
1592
+ decisionType: "plan-generation",
1593
+ decision: `Child operation plan generated with ${result.plan.scriptedPlan.stepSummary.length} steps`,
1594
+ reasoning: result.plan.reasoning,
1595
+ context: { stepCount: result.plan.scriptedPlan.stepSummary.length, envoyId: planningEnvoy.id, parentOperationId: parentOp.id },
1596
+ });
1597
+ }
1598
+ catch (err) {
1599
+ const childDep = deployments.get(childId);
1600
+ if (childDep) {
1601
+ childDep.status = "failed";
1602
+ childDep.failureReason = err instanceof Error ? err.message : "Planning failed";
1603
+ deployments.save(childDep);
1604
+ }
1605
+ anyFailed = true;
1606
+ const parentDep = deployments.get(parentOp.id);
1607
+ if (parentDep && parentDep.status === "pending") {
1608
+ parentDep.status = "failed";
1609
+ parentDep.failureReason = `Child operation (${childInput.type}) planning failed: ${err instanceof Error ? err.message : "unknown error"}`;
1610
+ deployments.save(parentDep);
1611
+ debrief.record({
1612
+ partitionId: parentDep.partitionId ?? null,
1613
+ operationId: parentDep.id,
1614
+ agent: "server",
1615
+ decisionType: "composite-failed",
1616
+ decision: `Child operation planning failed — composite cannot proceed`,
1617
+ reasoning: parentDep.failureReason,
1618
+ context: { childId, childType: childInput.type, error: parentDep.failureReason },
1619
+ });
1620
+ }
1621
+ break;
1622
+ }
1623
+ }
1624
+ if (!anyFailed) {
1625
+ // All children planned — build combined summary plan and await approval
1626
+ const allChildren = childIds.map((id) => deployments.get(id)).filter(Boolean);
1627
+ const combinedStepSummary = allChildren.flatMap((c, idx) => {
1628
+ if (!c.plan?.scriptedPlan)
1629
+ return [];
1630
+ return c.plan.scriptedPlan.stepSummary.map((step) => ({
1631
+ ...step,
1632
+ description: `[${idx + 1}/${allChildren.length}: ${c.input.type}] ${step.description}`,
1633
+ }));
1634
+ });
1635
+ const combinedReasoning = allChildren.map((c, idx) => `Step ${idx + 1} (${c.input.type}): ${c.plan?.reasoning ?? "no reasoning"}`).join("\n\n");
1636
+ // Combine child execution scripts into a single composite script
1637
+ const combinedScript = allChildren
1638
+ .map((c, idx) => `# --- Child ${idx + 1}/${allChildren.length}: ${c.input.type} ---\n${c.plan?.scriptedPlan?.executionScript ?? "# no script"}`)
1639
+ .join("\n\n");
1640
+ const parentDep = deployments.get(parentOp.id);
1641
+ if (parentDep && parentDep.status === "pending") {
1642
+ parentDep.plan = {
1643
+ scriptedPlan: {
1644
+ platform: "bash",
1645
+ executionScript: combinedScript,
1646
+ dryRunScript: null,
1647
+ rollbackScript: null,
1648
+ reasoning: combinedReasoning,
1649
+ stepSummary: combinedStepSummary,
1650
+ },
1651
+ reasoning: combinedReasoning,
1652
+ };
1653
+ parentDep.rollbackPlan = {
1654
+ scriptedPlan: {
1655
+ platform: "bash",
1656
+ executionScript: "# Child operations handle their own rollback",
1657
+ dryRunScript: null,
1658
+ rollbackScript: null,
1659
+ reasoning: "Child operations handle their own rollback",
1660
+ stepSummary: [],
1661
+ },
1662
+ reasoning: "Child operations handle their own rollback",
1663
+ };
1664
+ parentDep.status = "awaiting_approval";
1665
+ parentDep.recommendation = computeRecommendation(parentDep, deployments);
1666
+ deployments.save(parentDep);
1667
+ debrief.record({
1668
+ partitionId: parentDep.partitionId ?? null,
1669
+ operationId: parentDep.id,
1670
+ agent: "server",
1671
+ decisionType: "composite-plan-ready",
1672
+ decision: `All ${allChildren.length} child plans ready — composite awaiting approval`,
1673
+ reasoning: combinedReasoning,
1674
+ context: { childIds, totalSteps: combinedStepSummary.length },
1675
+ });
1676
+ }
1677
+ }
1678
+ }
1679
+ async function executeCompositeSequentially(parentId, childIds) {
1680
+ const parentOp = deployments.get(parentId);
1681
+ if (!parentOp)
1682
+ return;
1683
+ debrief.record({
1684
+ partitionId: parentOp.partitionId ?? null,
1685
+ operationId: parentOp.id,
1686
+ agent: "server",
1687
+ decisionType: "composite-started",
1688
+ decision: `Composite execution started — running ${childIds.length} child operations sequentially`,
1689
+ reasoning: `Composite operation approved — executing children in order`,
1690
+ context: { childIds, totalChildren: childIds.length },
1691
+ });
1692
+ for (let i = 0; i < childIds.length; i++) {
1693
+ const childId = childIds[i];
1694
+ const child = deployments.get(childId);
1695
+ if (!child || !child.plan || !child.rollbackPlan) {
1696
+ const dep = deployments.get(parentId);
1697
+ if (dep) {
1698
+ dep.status = "failed";
1699
+ dep.failureReason = `Child operation ${i + 1} has no plan — cannot execute`;
1700
+ deployments.save(dep);
1701
+ debrief.record({
1702
+ partitionId: dep.partitionId ?? null,
1703
+ operationId: dep.id,
1704
+ agent: "server",
1705
+ decisionType: "composite-failed",
1706
+ decision: `Child operation ${i + 1} missing plan — composite failed`,
1707
+ reasoning: dep.failureReason,
1708
+ context: { childId, childIndex: i },
1709
+ });
1710
+ }
1711
+ return;
1712
+ }
1713
+ const targetEnvoy = child.envoyId ? envoyRegistry?.get(child.envoyId) : envoyRegistry?.list()[0];
1714
+ if (!targetEnvoy) {
1715
+ const dep = deployments.get(parentId);
1716
+ if (dep) {
1717
+ dep.status = "failed";
1718
+ dep.failureReason = `No envoy available for child operation ${i + 1}`;
1719
+ deployments.save(dep);
1720
+ }
1721
+ return;
1722
+ }
1723
+ child.status = "running";
1724
+ deployments.save(child);
1725
+ debrief.record({
1726
+ partitionId: child.partitionId ?? null,
1727
+ operationId: child.id,
1728
+ agent: "server",
1729
+ decisionType: "composite-child-started",
1730
+ decision: `Executing child operation ${i + 1}/${childIds.length} (${child.input.type})`,
1731
+ reasoning: `Sequential composite execution — child ${i + 1} of ${childIds.length}`,
1732
+ context: { childId, childIndex: i, parentOperationId: parentId, childType: child.input.type },
1733
+ });
1734
+ const artifact = artifactStore.get(getArtifactId(child) ?? "");
1735
+ const serverPort = process.env.PORT ?? "9410";
1736
+ const serverUrl = process.env.SYNTH_SERVER_URL ?? `http://localhost:${serverPort}`;
1737
+ const progressCallbackUrl = `${serverUrl}/api/operations/${child.id}/progress`;
1738
+ const callbackToken = envoyRegistry?.list().find((r) => r.url === targetEnvoy.url)?.token;
1739
+ const childEnvoyClient = new EnvoyClient(targetEnvoy.url);
1740
+ try {
1741
+ await childEnvoyClient.executeApprovedPlan({
1742
+ operationId: child.id,
1743
+ plan: child.plan,
1744
+ rollbackPlan: child.rollbackPlan,
1745
+ artifactType: artifact?.type ?? "unknown",
1746
+ artifactName: artifact?.name ?? "unknown",
1747
+ environmentId: child.environmentId ?? "",
1748
+ progressCallbackUrl,
1749
+ callbackToken,
1750
+ });
1751
+ }
1752
+ catch (err) {
1753
+ const dep = deployments.get(parentId);
1754
+ if (dep) {
1755
+ dep.status = "failed";
1756
+ dep.failureReason = `Child operation ${i + 1} (${child.input.type}) execution dispatch failed: ${err instanceof Error ? err.message : "unknown error"}`;
1757
+ dep.completedAt = new Date();
1758
+ deployments.save(dep);
1759
+ debrief.record({
1760
+ partitionId: dep.partitionId ?? null,
1761
+ operationId: dep.id,
1762
+ agent: "server",
1763
+ decisionType: "composite-failed",
1764
+ decision: `Child operation ${i + 1} execution dispatch failed`,
1765
+ reasoning: dep.failureReason,
1766
+ context: { childId, childIndex: i, error: dep.failureReason },
1767
+ });
1768
+ }
1769
+ return;
1770
+ }
1771
+ // Wait for child to complete (poll every 2 seconds, 5-minute timeout)
1772
+ const timeoutMs = 300_000;
1773
+ const pollIntervalMs = 2_000;
1774
+ const start = Date.now();
1775
+ let childSucceeded = false;
1776
+ while (Date.now() - start < timeoutMs) {
1777
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
1778
+ const updated = deployments.get(childId);
1779
+ if (updated?.status === "succeeded") {
1780
+ childSucceeded = true;
1781
+ break;
1782
+ }
1783
+ if (updated?.status === "failed" || updated?.status === "rolled_back" || updated?.status === "cancelled") {
1784
+ break;
1785
+ }
1786
+ // Stop if the parent was externally cancelled or failed while we were waiting
1787
+ const parentNow = deployments.get(parentId);
1788
+ if (!parentNow || parentNow.status === "failed" || parentNow.status === "cancelled") {
1789
+ return;
1790
+ }
1791
+ }
1792
+ const finalChild = deployments.get(childId);
1793
+ if (!childSucceeded) {
1794
+ const reason = finalChild?.failureReason ?? `Child operation ${i + 1} did not complete in time`;
1795
+ const dep = deployments.get(parentId);
1796
+ if (dep) {
1797
+ dep.status = "failed";
1798
+ dep.failureReason = `Composite stopped at step ${i + 1}/${childIds.length} (${child.input.type}): ${reason}`;
1799
+ dep.completedAt = new Date();
1800
+ deployments.save(dep);
1801
+ debrief.record({
1802
+ partitionId: dep.partitionId ?? null,
1803
+ operationId: dep.id,
1804
+ agent: "server",
1805
+ decisionType: "composite-failed",
1806
+ decision: `Composite stopped at child ${i + 1}/${childIds.length} — ${child.input.type} failed`,
1807
+ reasoning: dep.failureReason,
1808
+ context: { childId, childIndex: i, failedChildType: child.input.type, completedChildren: i },
1809
+ });
1810
+ }
1811
+ return;
1812
+ }
1813
+ debrief.record({
1814
+ partitionId: finalChild?.partitionId ?? null,
1815
+ operationId: childId,
1816
+ agent: "server",
1817
+ decisionType: "composite-child-completed",
1818
+ decision: `Child operation ${i + 1}/${childIds.length} (${child.input.type}) completed successfully`,
1819
+ reasoning: `Child execution succeeded — proceeding to next child`,
1820
+ context: { childId, childIndex: i, parentOperationId: parentId },
1821
+ });
1822
+ }
1823
+ // All children succeeded
1824
+ const dep = deployments.get(parentId);
1825
+ if (dep) {
1826
+ dep.status = "succeeded";
1827
+ dep.completedAt = new Date();
1828
+ deployments.save(dep);
1829
+ debrief.record({
1830
+ partitionId: dep.partitionId ?? null,
1831
+ operationId: dep.id,
1832
+ agent: "server",
1833
+ decisionType: "composite-completed",
1834
+ decision: `Composite operation completed — all ${childIds.length} child operations succeeded`,
1835
+ reasoning: `All child operations executed successfully in sequence`,
1836
+ context: { childIds, totalChildren: childIds.length },
1837
+ });
1838
+ }
1839
+ }
1840
+ }
1841
+ // ---------------------------------------------------------------------------
1842
+ // Recommendation engine — synthesizes enrichment context into a verdict
1843
+ // ---------------------------------------------------------------------------
1844
+ function computeRecommendation(deployment, store, llmSummary) {
1845
+ const factors = [];
1846
+ let verdict = "proceed";
1847
+ const now = new Date();
1848
+ const twentyFourHoursAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
1849
+ // Check for previously rolled-back version
1850
+ if (deployment.version) {
1851
+ const rolledBack = store.findByArtifactVersion(getArtifactId(deployment) ?? "", deployment.version, "rolled_back");
1852
+ if (rolledBack.length > 0) {
1853
+ verdict = "caution";
1854
+ factors.push("This artifact version was previously rolled back");
1855
+ }
1856
+ }
1857
+ // Check for conflicting deployments (only meaningful when environmentId is set)
1858
+ if (deployment.environmentId) {
1859
+ const conflicting = store.list().filter((d) => d.environmentId === deployment.environmentId &&
1860
+ d.id !== deployment.id &&
1861
+ ((d.status) === "running" || (d.status) === "approved"));
1862
+ if (conflicting.length > 0) {
1863
+ verdict = "hold";
1864
+ factors.push(`${conflicting.length} other operation(s) in progress for this environment`);
1865
+ }
1866
+ }
1867
+ // Check deployment frequency
1868
+ const recentCount = deployment.environmentId
1869
+ ? store.countByEnvironment(deployment.environmentId, twentyFourHoursAgo)
1870
+ : 0;
1871
+ if (recentCount > 5) {
1872
+ if (verdict === "proceed")
1873
+ verdict = "caution";
1874
+ factors.push(`High operation frequency: ${recentCount} operations in the last 24h`);
1875
+ }
1876
+ // Check last deployment status
1877
+ const lastDeploy = deployment.environmentId
1878
+ ? store.findLatestByEnvironment(deployment.environmentId)
1879
+ : undefined;
1880
+ if (lastDeploy && lastDeploy.id !== deployment.id) {
1881
+ if ((lastDeploy.status) === "failed" || (lastDeploy.status) === "rolled_back") {
1882
+ if (verdict === "proceed")
1883
+ verdict = "caution";
1884
+ factors.push(`Last operation to this environment ${lastDeploy.status}`);
1885
+ }
1886
+ else if ((lastDeploy.status) === "succeeded") {
1887
+ factors.push("Last operation to this environment succeeded");
1888
+ }
1889
+ }
1890
+ if (factors.length === 0) {
1891
+ factors.push("No risk factors detected — target is stable");
1892
+ }
1893
+ const summaryMap = {
1894
+ proceed: "Proceed — no conflicting operations, target environment is stable",
1895
+ caution: "Proceed with caution — review risk factors before greenlighting",
1896
+ hold: "Hold — resolve conflicting operations before proceeding",
1897
+ };
1898
+ return { verdict, summary: llmSummary ?? summaryMap[verdict], factors };
1899
+ }
1900
+ //# sourceMappingURL=operations.js.map