relay-flow 0.1.0-alpha.0 → 0.2.1-alpha

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 (118) hide show
  1. package/README.md +160 -143
  2. package/cmd/relay-flow/commands_test.go +968 -0
  3. package/cmd/relay-flow/main.go +877 -175
  4. package/cmd/relay-flow/scenario_test.go +1310 -0
  5. package/cmd/relay-flow/serve.go +610 -0
  6. package/examples/default-story-workflow.yaml +88 -0
  7. package/go.mod +69 -2
  8. package/go.sum +185 -0
  9. package/internal/config/config.go +88 -0
  10. package/internal/config/machine.go +99 -48
  11. package/internal/config/machine_test.go +248 -0
  12. package/internal/config/merge_test.go +118 -0
  13. package/internal/config/writeatomic.go +36 -0
  14. package/internal/config/writeatomic_test.go +98 -0
  15. package/internal/execution/goworkflows/activities.go +490 -0
  16. package/internal/execution/goworkflows/engine.go +520 -0
  17. package/internal/execution/goworkflows/engine_test.go +660 -0
  18. package/internal/execution/goworkflows/fakes_test.go +509 -0
  19. package/internal/execution/goworkflows/interpreter.go +613 -0
  20. package/internal/execution/goworkflows/logging_test.go +154 -0
  21. package/internal/execution/goworkflows/mailbox_test.go +423 -0
  22. package/internal/execution/goworkflows/node_runtime_integration_test.go +133 -0
  23. package/internal/execution/goworkflows/node_runtime_test.go +510 -0
  24. package/internal/execution/goworkflows/projection.go +504 -0
  25. package/internal/execution/goworkflows/recovery_test.go +1092 -0
  26. package/internal/execution/goworkflows/retry_log_test.go +59 -0
  27. package/internal/execution/goworkflows/retry_projection_test.go +98 -0
  28. package/internal/harness/contract_test.go +174 -0
  29. package/internal/harness/factory.go +63 -0
  30. package/internal/harness/harness.go +41 -0
  31. package/internal/harness/opencode/opencode.go +166 -0
  32. package/internal/harness/opencode/opencode_test.go +50 -0
  33. package/internal/harness/plugin_selection_test.go +126 -0
  34. package/internal/identity/identity.go +37 -0
  35. package/internal/logging/logging.go +56 -0
  36. package/internal/logging/logging_test.go +116 -0
  37. package/internal/paths/paths.go +69 -0
  38. package/internal/recover/recover.go +115 -0
  39. package/internal/repo/poller.go +186 -0
  40. package/internal/repo/poller_test.go +327 -0
  41. package/internal/repo/repo.go +132 -0
  42. package/internal/repo/service.go +216 -0
  43. package/internal/repo/service_test.go +298 -0
  44. package/internal/retry/retry.go +118 -0
  45. package/internal/router/router.go +84 -0
  46. package/internal/router/router_test.go +231 -0
  47. package/internal/run/manager.go +121 -0
  48. package/internal/run/run.go +140 -0
  49. package/internal/run/run_identity_test.go +52 -0
  50. package/internal/run/run_manager_test.go +286 -0
  51. package/internal/runner/contract_test.go +259 -0
  52. package/internal/runner/factory.go +65 -0
  53. package/internal/runner/orca/orca.go +341 -172
  54. package/internal/runner/orca/orca_test.go +256 -143
  55. package/internal/runner/orca/orcacli/orcacli.go +220 -0
  56. package/internal/runner/orca/orcacli/orcacli_test.go +157 -0
  57. package/internal/runner/orca/orcacli/testdata/repo-list.json +18 -0
  58. package/internal/runner/orca/orcacli/testdata/strict-orca.sh +32 -0
  59. package/internal/runner/orca/orcacli/testdata/terminal-close.json +12 -0
  60. package/internal/runner/orca/orcacli/testdata/terminal-create.json +18 -0
  61. package/internal/runner/orca/orcacli/testdata/terminal-list.json +51 -0
  62. package/internal/runner/orca/orcacli/testdata/terminal-send.json +1 -0
  63. package/internal/runner/orca/orcacli/testdata/terminal-show.json +1 -0
  64. package/internal/runner/orca/orcacli/testdata/worktree-create.json +22 -0
  65. package/internal/runner/orca/orcacli/testdata/worktree-list.json +31 -0
  66. package/internal/runner/orca/orcacli/testdata/worktree-remove.json +6 -0
  67. package/internal/runner/runner.go +54 -64
  68. package/internal/server/api_test.go +300 -0
  69. package/internal/server/client.go +192 -74
  70. package/internal/server/fixture_test.go +248 -0
  71. package/internal/server/server.go +425 -248
  72. package/internal/server/shutdown_test.go +116 -0
  73. package/internal/task/auth_test.go +48 -0
  74. package/internal/task/contract_test.go +225 -0
  75. package/internal/task/factory.go +119 -0
  76. package/internal/task/jira/auth.go +183 -0
  77. package/internal/task/jira/auth_test.go +107 -0
  78. package/internal/task/jira/effects_test.go +39 -0
  79. package/internal/task/jira/filters_test.go +254 -0
  80. package/internal/task/jira/helpers_test.go +70 -0
  81. package/internal/task/jira/jira.go +538 -0
  82. package/internal/task/jira/normalize.go +119 -0
  83. package/internal/task/jira/rest/adf.go +128 -0
  84. package/internal/task/jira/rest/client.go +573 -0
  85. package/internal/task/jira/rest/client_test.go +381 -0
  86. package/internal/task/jira/testdata/jira_search_issues.json +120 -0
  87. package/internal/task/jira/transition_defaults_test.go +158 -0
  88. package/internal/task/jira/validation_test.go +94 -0
  89. package/internal/task/task.go +84 -0
  90. package/internal/workflow/report.go +85 -0
  91. package/internal/workflow/report_test.go +259 -0
  92. package/internal/workflow/service.go +142 -0
  93. package/internal/workflow/store.go +136 -0
  94. package/internal/workflow/store_test.go +282 -0
  95. package/internal/workflow/workflow.go +345 -0
  96. package/internal/workflow/workflow_test.go +412 -0
  97. package/package.json +7 -2
  98. package/internal/acli/acli.go +0 -229
  99. package/internal/config/demo_test.go +0 -17
  100. package/internal/config/schema.go +0 -193
  101. package/internal/config/schema_test.go +0 -162
  102. package/internal/daemon/daemon.go +0 -218
  103. package/internal/daemon/daemon_test.go +0 -204
  104. package/internal/discovery/discovery.go +0 -122
  105. package/internal/discovery/discovery_test.go +0 -62
  106. package/internal/opencode/opencode.go +0 -26
  107. package/internal/orcacli/orcacli.go +0 -264
  108. package/internal/runner/orca/README.md +0 -64
  109. package/internal/runner/runner_test.go +0 -64
  110. package/internal/server/server_test.go +0 -195
  111. package/internal/tasks/jira/README.md +0 -69
  112. package/internal/tasks/jira/component_test.go +0 -16
  113. package/internal/tasks/jira/decode.go +0 -24
  114. package/internal/tasks/jira/jira.go +0 -231
  115. package/internal/tasks/jira/jira_test.go +0 -259
  116. package/internal/tasks/jira/jql_test.go +0 -16
  117. package/internal/tasks/tasks.go +0 -90
  118. package/internal/tasks/tasks_test.go +0 -91
@@ -0,0 +1,613 @@
1
+ package goworkflows
2
+
3
+ import (
4
+ "crypto/rand"
5
+ "fmt"
6
+ "log/slog"
7
+ "reflect"
8
+ "sort"
9
+ "strings"
10
+ "time"
11
+
12
+ goworkflow "github.com/cschleiden/go-workflows/workflow"
13
+
14
+ "github.com/rajpopat27/relay-flow/internal/harness"
15
+ "github.com/rajpopat27/relay-flow/internal/identity"
16
+ "github.com/rajpopat27/relay-flow/internal/retry"
17
+ "github.com/rajpopat27/relay-flow/internal/run"
18
+ "github.com/rajpopat27/relay-flow/internal/runner"
19
+ "github.com/rajpopat27/relay-flow/internal/task"
20
+ "github.com/rajpopat27/relay-flow/internal/workflow"
21
+ )
22
+
23
+ // Signal names. The workflow deduplicates report IDs across all node visits;
24
+ // the reconcile channel asks it to relaunch the current visit's terminal.
25
+ const (
26
+ reportSignalName = "report"
27
+ reconcileSignal = "reconcile"
28
+ )
29
+
30
+ type reportSignal struct {
31
+ ReportID string
32
+ Node string
33
+ NodeVisitID run.NodeVisitID
34
+ Report workflow.Report
35
+ }
36
+
37
+ // noNativeRetries keeps the engine-native activity retry count at one; the
38
+ // private typed retry loops below implement the shared backoff policy.
39
+ var noNativeRetries = goworkflow.ActivityOptions{
40
+ RetryOptions: goworkflow.RetryOptions{MaxAttempts: 1},
41
+ }
42
+
43
+ // jitter draws a replay-safe random in [0,1) for backoff.
44
+ func jitter(ctx goworkflow.Context) (float64, error) {
45
+ return goworkflow.SideEffect(ctx, func(goworkflow.Context) float64 {
46
+ var b [1]byte
47
+ if _, err := rand.Read(b[:]); err != nil {
48
+ return 0
49
+ }
50
+ return float64(b[0]) / 256
51
+ }).Get(ctx)
52
+ }
53
+
54
+ // TicketWorkflow is the one generic interpreter registered with the workflow
55
+ // worker. It consumes ONLY the workflow value snapshot carried in start; it
56
+ // never re-reads the workflow file or registry mid-run, so replay is
57
+ // deterministic. On cancellation it runs cancellation cleanup on a
58
+ // disconnected context.
59
+ func (a *Activities) TicketWorkflow(ctx goworkflow.Context, start run.Start) error {
60
+ err := a.runGraph(ctx, start)
61
+ if err != nil && ctx.Err() != nil {
62
+ work := run.Work{
63
+ RunID: start.ID,
64
+ Repo: start.Repo,
65
+ Workflow: start.Workflow.Name,
66
+ Parent: start.Ticket,
67
+ WorkflowTaskConfig: start.Workflow.TaskConfig,
68
+ Runtime: start.Runtime,
69
+ }
70
+ return a.cancelCleanup(ctx, work, start.RepoPath, "canceled")
71
+ }
72
+ return err
73
+ }
74
+
75
+ func (a *Activities) runGraph(ctx goworkflow.Context, start run.Start) error {
76
+ wf := start.Workflow // value snapshot
77
+ work := run.Work{
78
+ RunID: start.ID,
79
+ Repo: start.Repo,
80
+ Workflow: wf.Name,
81
+ Parent: start.Ticket,
82
+ WorkflowTaskConfig: wf.TaskConfig,
83
+ Runtime: start.Runtime,
84
+ }
85
+
86
+ // Ensure every work-node mailbox (find existing, create only missing).
87
+ specs := MailboxSpecs(&wf, start.Ticket.Key)
88
+ mailboxes, err := retryLoop(ctx, start.ID, a, work, "",
89
+ func(ctx2 goworkflow.Context) goworkflow.Future[map[string]task.Mailbox] {
90
+ return goworkflow.ExecuteActivity[map[string]task.Mailbox](ctx2, noNativeRetries, a.EnsureMailboxes, work, specs)
91
+ })
92
+ if err != nil {
93
+ return err
94
+ }
95
+
96
+ // Validate every referenced agent before the start edge.
97
+ agentSet := map[string]bool{}
98
+ for _, n := range wf.Nodes {
99
+ if n.Agent != "" {
100
+ agentSet[n.Agent] = true
101
+ }
102
+ }
103
+ agentList := make([]string, 0, len(agentSet))
104
+ for agent := range agentSet {
105
+ agentList = append(agentList, agent)
106
+ }
107
+ sort.Strings(agentList)
108
+ if _, err := retryLoop(ctx, start.ID, a, work, "",
109
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
110
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries, a.ValidateAgents, start.RepoPath, agentList)
111
+ }); err != nil {
112
+ return err
113
+ }
114
+
115
+ // Process the reserved start taskConfig (parent target).
116
+ startNode := wf.Nodes["start"]
117
+ if _, err := retryLoop(ctx, start.ID, a, work, "start",
118
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
119
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries, a.ApplyTaskConfig,
120
+ work, "start", (*task.Mailbox)(nil), mergeTaskConfig(wf.TaskConfig, startNode.TaskConfig))
121
+ }); err != nil {
122
+ return err
123
+ }
124
+
125
+ // Ensure the runner environment before following the start edge.
126
+ if _, err := retryLoop(ctx, start.ID, a, work, "",
127
+ func(ctx2 goworkflow.Context) goworkflow.Future[runner.Environment] {
128
+ return goworkflow.ExecuteActivity[runner.Environment](ctx2, noNativeRetries, a.EnsureEnvironment, work, start.RepoPath)
129
+ }); err != nil {
130
+ return err
131
+ }
132
+
133
+ target, err := wf.StartTarget()
134
+ if err != nil {
135
+ return err
136
+ }
137
+
138
+ current := target
139
+ seenReportIDs := map[string]bool{}
140
+ for current != "end" {
141
+ node := wf.Nodes[current]
142
+
143
+ // One fresh visit identity per node entry, durable across replay.
144
+ visit, err := goworkflow.SideEffect(ctx, func(goworkflow.Context) identity.NodeVisitID {
145
+ return identity.NewNodeVisitID()
146
+ }).Get(ctx)
147
+ if err != nil {
148
+ return err
149
+ }
150
+ visitID := run.NodeVisitID(visit)
151
+ runtime, err := retryLoop(ctx, start.ID, a, work, current,
152
+ func(ctx2 goworkflow.Context) goworkflow.Future[NodeRuntime] {
153
+ return goworkflow.ExecuteActivity[NodeRuntime](ctx2, noNativeRetries,
154
+ a.LoadNodeRuntime, start.ID, current)
155
+ })
156
+ if err != nil {
157
+ return err
158
+ }
159
+
160
+ // Publish the visit guard before launching OpenCode so its earliest
161
+ // session event can register against this exact run/node/visit tuple.
162
+ // Revisit preparation preserves reusable terminal/session IDs.
163
+ if _, err := retryLoop(ctx, start.ID, a, work, current,
164
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
165
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries,
166
+ a.ProjectionUpdateNodeRuntimeVisit, start.ID, current, visitID)
167
+ }); err != nil {
168
+ return err
169
+ }
170
+
171
+ // Process the node in the task system.
172
+ mb := mailboxes[current]
173
+ nodeCfg := mergeTaskConfig(wf.TaskConfig, node.TaskConfig)
174
+ if _, err := retryLoop(ctx, start.ID, a, work, current,
175
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
176
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries, a.ApplyTaskConfig, work, current, &mb, nodeCfg)
177
+ }); err != nil {
178
+ return err
179
+ }
180
+
181
+ // Ensure the runner environment for this node entry (idempotent).
182
+ if _, err := retryLoop(ctx, start.ID, a, work, current,
183
+ func(ctx2 goworkflow.Context) goworkflow.Future[runner.Environment] {
184
+ return goworkflow.ExecuteActivity[runner.Environment](ctx2, noNativeRetries, a.EnsureEnvironment, work, start.RepoPath)
185
+ }); err != nil {
186
+ return err
187
+ }
188
+
189
+ title := start.Ticket.Key + ":" + current
190
+
191
+ // Build the finished launch metadata from the workflow snapshot: the
192
+ // prompt carries the node description, optional custom instructions,
193
+ // complete report contract, and valid next steps. Custom instructions
194
+ // are also retained separately for live-terminal revisits.
195
+ nextSteps := append(append([]workflow.Route{}, node.OnSuccess...), node.OnFailure...)
196
+ nudge, err := wf.RenderNudge(current, workflow.NudgeTemplateData{
197
+ TaskSystem: a.TaskSystem,
198
+ Ticket: start.Ticket.Key,
199
+ Workflow: wf.Name,
200
+ Repo: start.Repo,
201
+ Node: current,
202
+ NextSteps: nextStepsText(nextSteps),
203
+ })
204
+ if err != nil {
205
+ return err
206
+ }
207
+ spec := harness.LaunchSpec{
208
+ RunID: start.ID,
209
+ NodeVisitID: visitID,
210
+ RepoName: start.Repo,
211
+ RepoPath: start.RepoPath,
212
+ Workflow: wf.Name,
213
+ Ticket: start.Ticket.Key,
214
+ Node: current,
215
+ NodeType: node.Type,
216
+ Agent: node.Agent,
217
+ Title: title,
218
+ Prompt: BuildLaunchSpecPrompt(a.TaskSystem, start.Ticket.Key, mb.Key),
219
+ NudgePrompt: nudge,
220
+ NextSteps: nextSteps,
221
+ }
222
+ if runtime.SessionID != "" {
223
+ spec.ResumeID = runtime.SessionID
224
+ }
225
+ nodeWork := run.NodeWork{
226
+ Work: work, Node: current, NodeVisitID: visitID,
227
+ Mailbox: mb, NodeTaskConfig: nodeCfg,
228
+ }
229
+ if _, err := retryLoop(ctx, start.ID, a, work, current,
230
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
231
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries,
232
+ a.EnsureNodeRuntime, nodeWork, start.RepoPath, spec, runtime)
233
+ }); err != nil {
234
+ return err
235
+ }
236
+
237
+ // Publish the current node+visit only after the terminal exists, so
238
+ // observers never see a visit whose terminal is not up yet.
239
+ if _, err := retryLoop(ctx, start.ID, a, work, current,
240
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
241
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries, a.ProjectionUpdateNode, start.ID, run.StateRunning, current, visitID)
242
+ }); err != nil {
243
+ return err
244
+ }
245
+ if _, err := retryLoop(ctx, start.ID, a, work, current,
246
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
247
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries, a.ProjectionUpdateState, start.ID, run.StateWaiting, "", (*time.Time)(nil))
248
+ }); err != nil {
249
+ return err
250
+ }
251
+
252
+ // Wait for this visit's report; duplicate report IDs are ignored across
253
+ // the entire run, including later revisits to this node.
254
+ reportCh := goworkflow.NewSignalChannel[reportSignal](ctx, reportSignalName)
255
+ reconcileCh := goworkflow.NewSignalChannel[struct{}](ctx, reconcileSignal)
256
+ var report workflow.Report
257
+ var reportID string
258
+ gotReport := false
259
+ for !gotReport && ctx.Err() == nil {
260
+ goworkflow.Select(ctx,
261
+ goworkflow.Receive(reportCh, func(_ goworkflow.Context, signal reportSignal, ok bool) {
262
+ if seenReportIDs[signal.ReportID] {
263
+ return
264
+ }
265
+ seenReportIDs[signal.ReportID] = true
266
+ if signal.Node != current || signal.NodeVisitID != visitID {
267
+ return
268
+ }
269
+ reportID = signal.ReportID
270
+ report = signal.Report
271
+ gotReport = true
272
+ }),
273
+ goworkflow.Receive(reconcileCh, func(ctx2 goworkflow.Context, _ struct{}, ok bool) {
274
+ // Reconcile addresses only the persisted direct identity;
275
+ // missing/unusable IDs are replaced without discovery.
276
+ _, _ = retryLoop(ctx2, start.ID, a, work, current,
277
+ func(ctx3 goworkflow.Context) goworkflow.Future[struct{}] {
278
+ return goworkflow.ExecuteActivity[struct{}](ctx3, noNativeRetries,
279
+ a.EnsureNodeRuntime, nodeWork, start.RepoPath, spec,
280
+ NodeRuntime{NodeVisitID: visitID})
281
+ })
282
+ }),
283
+ // Wake on cancellation; the loop condition then exits.
284
+ goworkflow.Receive(ctx.Done(), func(goworkflow.Context, struct{}, bool) {}),
285
+ )
286
+ }
287
+ if ctx.Err() != nil {
288
+ return ctx.Err()
289
+ }
290
+
291
+ // Validate against the current node; the server boundary already
292
+ // validated, and durable-side validation keeps replay honest.
293
+ if err := wf.ValidateReport(current, report); err != nil {
294
+ return fmt.Errorf("workflow %q node %q: invalid accepted report: %w", wf.Name, current, err)
295
+ }
296
+ if _, err := retryLoop(ctx, start.ID, a, work, current,
297
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
298
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries,
299
+ a.ProjectionRecordProcessedReport, start.ID, visitID, reportID)
300
+ }); err != nil {
301
+ return err
302
+ }
303
+
304
+ // Ordered transition: summary -> feedback (selected next only) ->
305
+ // complete current -> process next node.
306
+ if _, err := retryLoop(ctx, start.ID, a, work, current,
307
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
308
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries, a.Comment, start.Repo, run.CommentWork{
309
+ RunID: start.ID,
310
+ Item: task.Target{Parent: work.Parent, Mailbox: &mb},
311
+ Body: renderSummary(report),
312
+ Marker: string(visitID) + ":summary",
313
+ })
314
+ }); err != nil {
315
+ return err
316
+ }
317
+
318
+ next := report.NextStep
319
+ if next != "end" {
320
+ nextMb := mailboxes[next]
321
+ if _, err := retryLoop(ctx, start.ID, a, work, current,
322
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
323
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries, a.Comment, start.Repo, run.CommentWork{
324
+ RunID: start.ID,
325
+ Item: task.Target{Parent: work.Parent, Mailbox: &nextMb},
326
+ Body: renderFeedback(current, report),
327
+ Marker: string(visitID) + ":feedback",
328
+ })
329
+ }); err != nil {
330
+ return err
331
+ }
332
+ }
333
+
334
+ // Complete the current mailbox. A conflict (a human moved it) marks
335
+ // the run blocked and keeps retrying until external state is
336
+ // compatible again; no blind overwrite ever runs.
337
+ if _, err := retryLoop(ctx, start.ID, a, work, current,
338
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
339
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries, a.CompleteMailbox, work, mb)
340
+ }); err != nil {
341
+ return err
342
+ }
343
+ if _, err := retryLoop(ctx, start.ID, a, work, current,
344
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
345
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries,
346
+ a.CheckpointNodeRuntime, nodeWork, start.RepoPath, work.Runtime)
347
+ }); err != nil {
348
+ return err
349
+ }
350
+
351
+ current = next
352
+ }
353
+
354
+ // end: apply end task config, then optional runner cleanup, then mark
355
+ // the run completed.
356
+ endNode := wf.Nodes["end"]
357
+ if _, err := retryLoop(ctx, start.ID, a, work, "end",
358
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
359
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries, a.ApplyTaskConfig,
360
+ work, "end", (*task.Mailbox)(nil), mergeTaskConfig(wf.TaskConfig, endNode.TaskConfig))
361
+ }); err != nil {
362
+ return err
363
+ }
364
+ if _, err := retryLoop(ctx, start.ID, a, work, "end",
365
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
366
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries,
367
+ a.SetEnvironmentStatus, work, start.RepoPath, runner.WorkspaceStatusCompleted)
368
+ }); err != nil {
369
+ return err
370
+ }
371
+ finalPolicy := work.Runtime
372
+ if wf.CleanupRunnerOnEnd {
373
+ finalPolicy.KeepTerminalsAlive = false
374
+ }
375
+ if _, err := retryLoop(ctx, start.ID, a, work, "",
376
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
377
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries,
378
+ a.FinalizeNodeRuntimes, work, start.RepoPath, finalPolicy)
379
+ }); err != nil {
380
+ return err
381
+ }
382
+ if wf.CleanupRunnerOnEnd {
383
+ if _, err := retryLoop(ctx, start.ID, a, work, "",
384
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
385
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries, a.CleanupRun, work, start.RepoPath)
386
+ }); err != nil {
387
+ return err
388
+ }
389
+ }
390
+ if _, err := retryLoop(ctx, start.ID, a, work, "",
391
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
392
+ now := goworkflow.Now(ctx).UTC()
393
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries, a.ProjectionUpdateState, start.ID, run.StateCompleted, "", &now)
394
+ }); err != nil {
395
+ return err
396
+ }
397
+ return nil
398
+ }
399
+
400
+ // retryLoop runs one scheduled activity under the shared policy: transient
401
+ // failures retry forever with exponential backoff and replay-safe jitter;
402
+ // conflict failures mark the run blocked and keep retrying on the capped
403
+ // schedule. Cancellation stops scheduling.
404
+ //
405
+ // 9.6: each scheduling failure emits ONE info line with the retry
406
+ // classification (transient|conflict) and the next retry delay. work
407
+ // carries the always-known ticket/repo/workflow context; node is the
408
+ // enclosing node when the activity runs inside a node body (empty for
409
+ // run-level activities like EnsureMailboxes / start/end ApplyTaskConfig).
410
+ // The log is wrapped in a replay-safe SideEffect so replays never re-emit
411
+ // it, and the error message is sanitized so info logs never embed argv
412
+ // payloads (Jira/Orca request bodies, commands, JQL, and prompt strings).
413
+ func retryLoop[T any](ctx goworkflow.Context, id run.ID, a *Activities, work run.Work, node string, schedule func(goworkflow.Context) goworkflow.Future[T]) (T, error) {
414
+ var zero T
415
+ attempt := 0
416
+ blocked := false
417
+ for {
418
+ if err := ctx.Err(); err != nil {
419
+ return zero, err
420
+ }
421
+ result, err := schedule(ctx).Get(ctx)
422
+ if err == nil {
423
+ if attempt > 0 {
424
+ if _, clearErr := goworkflow.ExecuteActivity[struct{}](ctx, noNativeRetries, a.ProjectionUpdateRetry, id, (*run.RetryStatus)(nil)).Get(ctx); clearErr != nil {
425
+ return zero, clearErr
426
+ }
427
+ }
428
+ if blocked {
429
+ // External state is compatible again: leave blocked.
430
+ _, _ = scheduleState(ctx, a, id, run.StateWaiting, "")
431
+ }
432
+ return result, nil
433
+ }
434
+ if ctx.Err() != nil {
435
+ return zero, ctx.Err()
436
+ }
437
+ f := classifyActivityError(err)
438
+ if f.Kind == retry.Conflict {
439
+ // Mark blocked, keep retrying on the capped schedule.
440
+ _, _ = scheduleState(ctx, a, id, run.StateBlocked, f.Message)
441
+ blocked = true
442
+ }
443
+ delay := retry.DefaultBackoffPolicy.Delay(attempt, mustJitter(ctx))
444
+ logRetry(ctx, work, node, f, delay)
445
+ nextRetry := goworkflow.Now(ctx).UTC().Add(delay)
446
+ status := &run.RetryStatus{
447
+ Attempt: attempt + 1, LastError: sanitizeRetryMessage(f.Message), NextRetryAt: nextRetry,
448
+ }
449
+ if _, projectionErr := goworkflow.ExecuteActivity[struct{}](ctx, noNativeRetries, a.ProjectionUpdateRetry, id, status).Get(ctx); projectionErr != nil {
450
+ return zero, projectionErr
451
+ }
452
+ if _, err := goworkflow.ScheduleTimer(ctx, delay).Get(ctx); err != nil {
453
+ return zero, err
454
+ }
455
+ attempt++
456
+ }
457
+ }
458
+
459
+ // logRetry emits the 9.6 retry-classification info line, replay-safe.
460
+ // Attrs come from the always-known run.Work value carried by the caller,
461
+ // so ticket/repo/workflow are present even if the projection is briefly
462
+ // unreadable; node is included whenever the retry runs inside a node body.
463
+ func logRetry(ctx goworkflow.Context, work run.Work, node string, f retry.Failure, delay time.Duration) {
464
+ kind := string(f.Kind)
465
+ delayMs := delay.Milliseconds()
466
+ msg := sanitizeRetryMessage(f.Message)
467
+ attrs := []any{
468
+ "ticket", work.Parent.Key,
469
+ "runID", string(work.RunID),
470
+ "repo", work.Repo,
471
+ "workflow", work.Workflow,
472
+ "kind", kind,
473
+ "delayMs", delayMs,
474
+ "error", msg,
475
+ }
476
+ if node != "" {
477
+ attrs = append(attrs, "node", node)
478
+ }
479
+ _, _ = goworkflow.SideEffect(ctx, func(goworkflow.Context) struct{} {
480
+ slog.Info("retry scheduled", attrs...)
481
+ return struct{}{}
482
+ }).Get(ctx)
483
+ }
484
+
485
+ // sanitizeRetryMessage strips each "[...]: " argv-listing span that adapter
486
+ // wrappers may embed argv/request context, so the info-level retry
487
+ // record never leaks --body/--command/JQL/prompt payloads. Keeps the
488
+ // surrounding wrap context and trailing exit status / stderr fragment that
489
+ // carry the failure reason. The original error returned to callers is
490
+ // unchanged; this sanitizes only the logged string.
491
+ func sanitizeRetryMessage(s string) string {
492
+ for {
493
+ i := strings.Index(s, "[")
494
+ if i < 0 {
495
+ return s
496
+ }
497
+ j := strings.Index(s[i:], "]: ")
498
+ if j < 0 {
499
+ return s
500
+ }
501
+ // Remove the "[...]: " span, keeping any preceding text (minus a
502
+ // trailing space) and everything after.
503
+ s = strings.TrimSuffix(s[:i], " ") + s[i+j+3:]
504
+ }
505
+ }
506
+
507
+ // classifyActivityError classifies an activity error after its durable
508
+ // round-trip. The engine serializes error causes, so the concrete
509
+ // retry conflict wrapper does not survive; its stable type name does.
510
+ func classifyActivityError(err error) retry.Failure {
511
+ if err == nil {
512
+ return retry.Failure{}
513
+ }
514
+ if isConflictRoundTrip(err) {
515
+ return retry.Failure{Kind: retry.Conflict, Message: err.Error()}
516
+ }
517
+ return retry.Classify(err)
518
+ }
519
+
520
+ // isConflictRoundTrip reports whether err (or any serialized cause) carries
521
+ // the conflict marker type name produced by retry.ConflictError.
522
+ func isConflictRoundTrip(err error) bool {
523
+ for e := err; e != nil; {
524
+ v := reflect.ValueOf(e)
525
+ if v.Kind() == reflect.Ptr {
526
+ v = v.Elem()
527
+ }
528
+ if v.IsValid() && v.Kind() == reflect.Struct {
529
+ if f := v.FieldByName("Type"); f.IsValid() && f.Kind() == reflect.String && f.String() == "conflictError" {
530
+ return true
531
+ }
532
+ }
533
+ u, ok := e.(interface{ Unwrap() error })
534
+ if !ok {
535
+ return false
536
+ }
537
+ e = u.Unwrap()
538
+ }
539
+ return false
540
+ }
541
+
542
+ // scheduleState records a state change via the projection activity.
543
+ func scheduleState(ctx goworkflow.Context, a *Activities, id run.ID, state run.State, msg string) (struct{}, error) {
544
+ return goworkflow.ExecuteActivity[struct{}](ctx, noNativeRetries, a.ProjectionUpdateState, id, state, msg, (*time.Time)(nil)).Get(ctx)
545
+ }
546
+
547
+ func mustJitter(ctx goworkflow.Context) float64 {
548
+ v, err := jitter(ctx)
549
+ if err != nil {
550
+ return 0
551
+ }
552
+ return v
553
+ }
554
+
555
+ // cancelCleanup runs cancellation cleanup on a disconnected workflow
556
+ // context: close run-owned terminals (preserving the workspace), write the
557
+ // parent cancellation comment with the stable marker, and mark the run
558
+ // canceled. No rollback/compensation ever runs.
559
+ func (a *Activities) cancelCleanup(ctx goworkflow.Context, work run.Work, repoPath, reason string) error {
560
+ dctx := goworkflow.NewDisconnectedContext(ctx)
561
+ if _, err := retryLoop(dctx, work.RunID, a, work, "",
562
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
563
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries,
564
+ a.FinalizeNodeRuntimes, work, repoPath, work.Runtime)
565
+ }); err != nil {
566
+ return err
567
+ }
568
+ if _, err := retryLoop(dctx, work.RunID, a, work, "",
569
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
570
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries, a.Comment, work.Repo, run.CommentWork{
571
+ RunID: work.RunID,
572
+ Item: task.Target{Parent: work.Parent},
573
+ Body: "Run canceled: " + reason,
574
+ Marker: run.CancellationMarker(work.RunID),
575
+ })
576
+ }); err != nil {
577
+ return err
578
+ }
579
+ if _, err := retryLoop(dctx, work.RunID, a, work, "",
580
+ func(ctx2 goworkflow.Context) goworkflow.Future[struct{}] {
581
+ now := goworkflow.Now(dctx).UTC()
582
+ return goworkflow.ExecuteActivity[struct{}](ctx2, noNativeRetries, a.ProjectionUpdateState, work.RunID, run.StateCanceled, "", &now)
583
+ }); err != nil {
584
+ return err
585
+ }
586
+ return nil
587
+ }
588
+
589
+ // nextStepsText renders the legal next steps with their when explanations
590
+ // for nudge templates.
591
+ func nextStepsText(routes []workflow.Route) string {
592
+ var b strings.Builder
593
+ for i, r := range routes {
594
+ if i > 0 {
595
+ b.WriteString("; ")
596
+ }
597
+ b.WriteString(r.Target)
598
+ if r.When != "" {
599
+ b.WriteString(" (when: " + r.When + ")")
600
+ }
601
+ }
602
+ return b.String()
603
+ }
604
+
605
+ func renderSummary(r workflow.Report) string {
606
+ return fmt.Sprintf("SUMMARY\nCOMPLETED:\n%s\n\nCOMMITS:\n%s\n\nNOT COMPLETED:\n%s\n\nISSUES DISCOVERED:\n%s\n\nVERIFICATION:\n%s\n\nNOTES:\n%s\n",
607
+ r.Summary.Completed, r.Summary.Commits, r.Summary.NotCompleted, r.Summary.IssuesDiscovered, r.Summary.Verification, r.Summary.Notes)
608
+ }
609
+
610
+ func renderFeedback(source string, r workflow.Report) string {
611
+ return fmt.Sprintf("Feedback from %s\nCOMMITS:\n%s\n\nREASON FOR NEXT STEP:\n%s\n\nREQUIRED ACTIONS:\n%s\n\nRELEVANT CONTEXT:\n%s\n\nEXPECTED RESULT:\n%s\n",
612
+ source, r.Summary.Commits, r.Feedback.ReasonForNextStep, r.Feedback.RequiredActions, r.Feedback.RelevantContext, r.Feedback.ExpectedResult)
613
+ }