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,660 @@
1
+ package goworkflows_test
2
+
3
+ import (
4
+ "context"
5
+ "database/sql"
6
+ "path/filepath"
7
+ "strings"
8
+ "testing"
9
+ "time"
10
+
11
+ "github.com/rajpopat27/relay-flow/internal/execution/goworkflows"
12
+ "github.com/rajpopat27/relay-flow/internal/identity"
13
+ "github.com/rajpopat27/relay-flow/internal/repo"
14
+ "github.com/rajpopat27/relay-flow/internal/run"
15
+ "github.com/rajpopat27/relay-flow/internal/task"
16
+ "github.com/rajpopat27/relay-flow/internal/workflow"
17
+ )
18
+
19
+ // 3.14-3.16, 3.20, 3.22, 3.26: durable run execution behavior per
20
+ // specs/durable-run-execution. Fakes live in fakes_test.go and record one
21
+ // ordered event log so ordering and no-replay claims are observable.
22
+
23
+ func linearWorkflow(cleanup bool) workflow.Workflow {
24
+ return workflow.Workflow{
25
+ Name: "basicFlow",
26
+ Repos: []string{"payments"},
27
+ CleanupRunnerOnEnd: cleanup,
28
+ TaskConfig: map[string]any{
29
+ "transitionTo": map[string]any{"parentStatus": "In Progress"},
30
+ },
31
+ Nodes: map[string]workflow.Node{
32
+ "start": {OnSuccess: []workflow.Route{{Target: "coding"}}},
33
+ "coding": {
34
+ Type: workflow.NodeAgent, Agent: "build", Description: "work",
35
+ OnSuccess: []workflow.Route{{Target: "end"}},
36
+ OnFailure: []workflow.Route{{Target: "coding"}},
37
+ },
38
+ "end": {TaskConfig: map[string]any{"transitionTo": map[string]any{"parentStatus": "Done"}}},
39
+ },
40
+ }
41
+ }
42
+
43
+ func TestMailboxDescriptionAndLaunchPromptAreTaskSystemNeutral(t *testing.T) {
44
+ wf := linearWorkflow(false)
45
+ node := wf.Nodes["coding"]
46
+ node.Type = workflow.NodeHITL
47
+ description := goworkflows.MailboxSpecForNode(&wf, "PAY-101", "coding", node).Description
48
+ for _, want := range []string{
49
+ "Parent ticket: PAY-101",
50
+ "Do not make code changes",
51
+ "until the human is satisfied with the review",
52
+ } {
53
+ if !strings.Contains(description, want) {
54
+ t.Fatalf("HITL mailbox description missing %q:\n%s", want, description)
55
+ }
56
+ }
57
+ for _, unwanted := range []string{"Jira", "OpenCode", "Question tool"} {
58
+ if strings.Contains(description, unwanted) {
59
+ t.Fatalf("generic mailbox description contains %q:\n%s", unwanted, description)
60
+ }
61
+ }
62
+
63
+ node.Type = workflow.NodeAgent
64
+ agentDescription := goworkflows.MailboxSpecForNode(&wf, "PAY-101", "coding", node).Description
65
+ if strings.Contains(agentDescription, "Question tool") {
66
+ t.Fatalf("agent mailbox description contains HITL Question instruction:\n%s", agentDescription)
67
+ }
68
+
69
+ for _, taskSystem := range []string{"jira", "linear"} {
70
+ prompt := goworkflows.BuildLaunchSpecPrompt(taskSystem, "PAY-101", "PAY-234")
71
+ want := "Task system: " + taskSystem + "\nUse the " + taskSystem + " tools to read the parent ticket PAY-101.\n\nYour mailbox is PAY-234. Read its description and comments for node instructions and feedback."
72
+ if prompt != want {
73
+ t.Fatalf("BuildLaunchSpecPrompt(%s) = %q, want %q", taskSystem, prompt, want)
74
+ }
75
+ if strings.Contains(prompt, "Jira") || strings.Contains(prompt, "subtask") {
76
+ t.Fatalf("launch prompt contains task-system-specific mailbox wording: %q", prompt)
77
+ }
78
+ if strings.Contains(prompt, "STATUS:") || strings.Contains(prompt, node.Description) {
79
+ t.Fatalf("launch prompt duplicates mailbox instructions: %q", prompt)
80
+ }
81
+ }
82
+ }
83
+
84
+ func startRun(engine *goworkflows.Engine, wf workflow.Workflow) (run.ID, error) {
85
+ rid := identity.NewRunID("payments", wf.Name, "PAY-101")
86
+ _, err := engine.EnsureRun(context.Background(), run.Start{
87
+ ID: rid,
88
+ Repo: "payments",
89
+ RepoPath: "/srv/payments",
90
+ Workflow: wf,
91
+ Ticket: task.TicketRef{ID: "1", Key: "PAY-101", Title: "parent"},
92
+ })
93
+ return rid, err
94
+ }
95
+
96
+ func newEngine(t *testing.T, deps goworkflows.Dependencies) *goworkflows.Engine {
97
+ t.Helper()
98
+ path := filepath.Join(t.TempDir(), "state.db")
99
+ e, err := goworkflows.New(path, deps)
100
+ if err != nil {
101
+ t.Fatalf("goworkflows.New failed: %v", err)
102
+ }
103
+ if err := e.Start(context.Background()); err != nil {
104
+ t.Fatalf("engine.Start failed: %v", err)
105
+ }
106
+ t.Cleanup(func() {
107
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
108
+ defer cancel()
109
+ _ = e.Shutdown(ctx)
110
+ })
111
+ return e
112
+ }
113
+
114
+ func TestEnsureRunCreatesMissingWorkflowForExistingProjection(t *testing.T) {
115
+ log := newEventLog()
116
+ sys := newFakeTaskSystem(log)
117
+ path := filepath.Join(t.TempDir(), "state.db")
118
+ deps := goworkflows.Dependencies{
119
+ Repos: repoRegistryWith("payments", sys), Runner: newFakeRunner(log), Harness: newFakeHarness(log),
120
+ }
121
+ engine, err := goworkflows.New(path, deps)
122
+ if err != nil {
123
+ t.Fatal(err)
124
+ }
125
+ wf := linearWorkflow(false)
126
+ rid := identity.NewRunID("payments", wf.Name, "PAY-101")
127
+ db, err := sql.Open("sqlite", path)
128
+ if err != nil {
129
+ t.Fatal(err)
130
+ }
131
+ if _, err := db.Exec(`INSERT INTO relay_runs
132
+ (id, repo, workflow, ticket_id, ticket_key, state, started_at, updated_at)
133
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, rid, "payments", wf.Name, "1", "PAY-101", run.StateStarting, time.Now(), time.Now()); err != nil {
134
+ t.Fatal(err)
135
+ }
136
+ db.Close()
137
+ if err := engine.Start(context.Background()); err != nil {
138
+ t.Fatal(err)
139
+ }
140
+ t.Cleanup(func() { _ = engine.Shutdown(context.Background()) })
141
+
142
+ created, err := engine.EnsureRun(context.Background(), run.Start{
143
+ ID: rid, Repo: "payments", RepoPath: "/srv/payments", Workflow: wf,
144
+ Ticket: task.TicketRef{ID: "1", Key: "PAY-101"},
145
+ })
146
+ if err != nil {
147
+ t.Fatal(err)
148
+ }
149
+ if !created {
150
+ t.Fatal("EnsureRun did not create the missing workflow instance")
151
+ }
152
+ waitFor(t, 10*time.Second, func() bool {
153
+ r, err := engine.GetRun(context.Background(), rid)
154
+ return err == nil && r.CurrentNode == "coding"
155
+ })
156
+ }
157
+
158
+ func successReport(next string) workflow.Report {
159
+ none := "None"
160
+ return workflow.Report{
161
+ Status: workflow.OutcomeSuccess,
162
+ NextStep: next,
163
+ Summary: workflow.Summary{
164
+ Completed: "done", Commits: "abc123", NotCompleted: none, IssuesDiscovered: none,
165
+ Verification: "tested", Notes: none,
166
+ },
167
+ Feedback: workflow.Feedback{
168
+ ReasonForNextStep: none, RequiredActions: none,
169
+ RelevantContext: none, ExpectedResult: none,
170
+ },
171
+ }
172
+ }
173
+
174
+ // --- 3.15: serial graph ---
175
+
176
+ func TestRunBeginsAtStartAndFollowsEntryEdge(t *testing.T) {
177
+ log := newEventLog()
178
+ sys := newFakeTaskSystem(log)
179
+ fr := newFakeRunner(log)
180
+ fh := newFakeHarness(log)
181
+ engine := newEngine(t, goworkflows.Dependencies{
182
+ Repos: repoRegistryWith("payments", sys), Runner: fr, Harness: fh,
183
+ })
184
+
185
+ rid, err := startRun(engine, linearWorkflow(false))
186
+ if err != nil {
187
+ t.Fatalf("EnsureRun failed: %v", err)
188
+ }
189
+
190
+ waitFor(t, 10*time.Second, func() bool {
191
+ r, err := engine.GetRun(context.Background(), rid)
192
+ return err == nil && r.CurrentNode == "coding" && r.CurrentNodeVisitID != ""
193
+ })
194
+
195
+ r, _ := engine.GetRun(context.Background(), rid)
196
+ if r.State != run.StateWaiting && r.State != run.StateRunning {
197
+ t.Fatalf("state = %q, want waiting/running at coding", r.State)
198
+ }
199
+ if len(fr.envs) != 1 {
200
+ t.Fatalf("runner environments = %d, want exactly 1 ticket-scoped env", len(fr.envs))
201
+ }
202
+ runtime, err := engine.GetNodeRuntime(context.Background(), rid, "coding")
203
+ if err != nil {
204
+ t.Fatalf("GetNodeRuntime: %v", err)
205
+ }
206
+ if runtime.TerminalID == "" || runtime.NodeVisitID != r.CurrentNodeVisitID {
207
+ t.Fatalf("terminal was not persisted for current visit: %+v", runtime)
208
+ }
209
+
210
+ // Pre-edge gate: before following the start edge the run ensures the
211
+ // runner environment AND validates every referenced agent, and applies
212
+ // the start taskConfig. Assert all three happened before the coding
213
+ // terminal was started.
214
+ events := log.all()
215
+ envIdx, validateIdx, applyIdx, terminalIdx := -1, -1, -1, -1
216
+ for i, e := range events {
217
+ switch {
218
+ case envIdx < 0 && hasPrefix(e, "ensureEnvironment:"):
219
+ envIdx = i
220
+ case validateIdx < 0 && hasPrefix(e, "validateAgent:build"):
221
+ validateIdx = i
222
+ case applyIdx < 0 && hasPrefix(e, "applyTaskConfig:"):
223
+ applyIdx = i
224
+ case terminalIdx < 0 && hasPrefix(e, "ensureTerminal:PAY-101:coding"):
225
+ terminalIdx = i
226
+ }
227
+ }
228
+ if envIdx < 0 {
229
+ t.Fatal("runner environment never ensured before start edge")
230
+ }
231
+ if validateIdx < 0 {
232
+ t.Fatal("referenced agent never validated before start edge")
233
+ }
234
+ if applyIdx < 0 {
235
+ t.Fatal("start taskConfig never applied")
236
+ }
237
+ if terminalIdx < 0 {
238
+ t.Fatal("coding terminal never started")
239
+ }
240
+ if !(envIdx < terminalIdx && validateIdx < terminalIdx && applyIdx < terminalIdx) {
241
+ t.Fatalf("pre-edge gate violated; events=%v", events)
242
+ }
243
+ }
244
+
245
+ func TestSerialGraphOneNodeAtATime(t *testing.T) {
246
+ log := newEventLog()
247
+ sys := newFakeTaskSystem(log)
248
+ fr := newFakeRunner(log)
249
+ engine := newEngine(t, goworkflows.Dependencies{
250
+ Repos: repoRegistryWith("payments", sys), Runner: fr, Harness: newFakeHarness(log),
251
+ })
252
+
253
+ rid, err := startRun(engine, linearWorkflow(false))
254
+ if err != nil {
255
+ t.Fatal(err)
256
+ }
257
+ waitFor(t, 10*time.Second, func() bool {
258
+ r, _ := engine.GetRun(context.Background(), rid)
259
+ return r.CurrentNode == "coding" && r.CurrentNodeVisitID != ""
260
+ })
261
+
262
+ ack, err := engine.SubmitReport(context.Background(), reportRequest(rid, "coding", successReport("end")))
263
+ if err != nil {
264
+ t.Fatalf("SubmitReport failed: %v", err)
265
+ }
266
+ if !ack.Accepted {
267
+ t.Fatalf("ack = %+v, want accepted", ack)
268
+ }
269
+
270
+ waitFor(t, 10*time.Second, func() bool {
271
+ r, _ := engine.GetRun(context.Background(), rid)
272
+ return r.State == run.StateCompleted
273
+ })
274
+ }
275
+
276
+ func TestRevisitCreatesNewVisit(t *testing.T) {
277
+ log := newEventLog()
278
+ sys := newFakeTaskSystem(log)
279
+ engine := newEngine(t, goworkflows.Dependencies{
280
+ Repos: repoRegistryWith("payments", sys), Runner: newFakeRunner(log), Harness: newFakeHarness(log),
281
+ })
282
+ rid, _ := startRun(engine, linearWorkflow(false))
283
+ waitFor(t, 10*time.Second, func() bool {
284
+ r, _ := engine.GetRun(context.Background(), rid)
285
+ return r.CurrentNode == "coding" && r.CurrentNodeVisitID != ""
286
+ })
287
+ if indexOf(log.all(), "environmentStatus:in-progress") < 0 {
288
+ t.Fatalf("agent node did not set workspace status in-progress; events=%v", log.all())
289
+ }
290
+
291
+ r, _ := engine.GetRun(context.Background(), rid)
292
+ first := r.CurrentNodeVisitID
293
+
294
+ fail := successReport("coding")
295
+ fail.Status = workflow.OutcomeFailure
296
+ if _, err := engine.SubmitReport(context.Background(), reportRequest(rid, "coding", fail)); err != nil {
297
+ t.Fatal(err)
298
+ }
299
+
300
+ waitFor(t, 10*time.Second, func() bool {
301
+ r, _ := engine.GetRun(context.Background(), rid)
302
+ return r.CurrentNode == "coding" && r.CurrentNodeVisitID != "" && r.CurrentNodeVisitID != first
303
+ })
304
+ }
305
+
306
+ func TestEndAppliesConfigAndCompletes(t *testing.T) {
307
+ log := newEventLog()
308
+ sys := newFakeTaskSystem(log)
309
+ fr := newFakeRunner(log)
310
+ wf := linearWorkflow(true) // cleanupRunnerOnEnd
311
+ engine := newEngine(t, goworkflows.Dependencies{
312
+ Repos: repoRegistryWith("payments", sys), Runner: fr, Harness: newFakeHarness(log),
313
+ Runtime: &run.RuntimePolicy{KeepTerminalsAlive: true, KeepSessionsAlive: true},
314
+ })
315
+ rid, _ := startRun(engine, wf)
316
+ waitFor(t, 10*time.Second, func() bool {
317
+ r, _ := engine.GetRun(context.Background(), rid)
318
+ return r.CurrentNode == "coding"
319
+ })
320
+ if _, err := engine.RegisterNodeSession(context.Background(), run.NodeRuntimeRegistration{
321
+ RunID: rid, Node: "coding", SessionID: "session-coding",
322
+ }); err != nil {
323
+ t.Fatal(err)
324
+ }
325
+ if _, err := engine.SubmitReport(context.Background(), reportRequest(rid, "coding", successReport("end"))); err != nil {
326
+ t.Fatal(err)
327
+ }
328
+ waitFor(t, 10*time.Second, func() bool {
329
+ r, _ := engine.GetRun(context.Background(), rid)
330
+ return r.State == run.StateCompleted
331
+ })
332
+
333
+ // end taskConfig applied (parent Done) before runner cleanup.
334
+ events := log.all()
335
+ endApplyIdx, cleanupIdx := -1, -1
336
+ for i, e := range events {
337
+ if endApplyIdx < 0 && e == "applyTaskConfig:PAY-101" && i > 0 {
338
+ // the second parent application is the end config (start applied first)
339
+ endApplyIdx = i
340
+ }
341
+ if cleanupIdx < 0 && hasPrefix(e, "cleanupRun:") {
342
+ cleanupIdx = i
343
+ }
344
+ }
345
+ if endApplyIdx < 0 {
346
+ t.Fatalf("end taskConfig never applied to the parent; events=%v", events)
347
+ }
348
+ if len(fr.cleaned) != 1 {
349
+ t.Fatalf("CleanupRun calls = %v, want 1 with cleanupRunnerOnEnd despite terminal retention", fr.cleaned)
350
+ }
351
+ if cleanupIdx < endApplyIdx {
352
+ t.Fatalf("runner cleanup ran before end taskConfig; events=%v", events)
353
+ }
354
+ r2, _ := engine.GetRun(context.Background(), rid)
355
+ if r2.State == run.StateCompleted && r2.FinishedAt == nil {
356
+ t.Fatal("completed run has no FinishedAt")
357
+ }
358
+ rt, err := engine.GetNodeRuntime(context.Background(), rid, "coding")
359
+ if err != nil {
360
+ t.Fatal(err)
361
+ }
362
+ if rt.TerminalID != "" || rt.SessionID != "session-coding" {
363
+ t.Fatalf("runtime after end cleanup = %+v, want terminal cleared and session retained", rt)
364
+ }
365
+ }
366
+
367
+ func TestEndCleanupDisabledKeepsRetainedRunner(t *testing.T) {
368
+ log := newEventLog()
369
+ fr := newFakeRunner(log)
370
+ engine := newEngine(t, goworkflows.Dependencies{
371
+ Repos: repoRegistryWith("payments", newFakeTaskSystem(log)), Runner: fr, Harness: newFakeHarness(log),
372
+ Runtime: &run.RuntimePolicy{KeepTerminalsAlive: true, KeepSessionsAlive: true},
373
+ })
374
+ rid, _ := startRun(engine, linearWorkflow(false))
375
+ waitFor(t, 10*time.Second, func() bool {
376
+ r, _ := engine.GetRun(context.Background(), rid)
377
+ return r.CurrentNode == "coding"
378
+ })
379
+ if _, err := engine.SubmitReport(context.Background(), reportRequest(rid, "coding", successReport("end"))); err != nil {
380
+ t.Fatal(err)
381
+ }
382
+ waitFor(t, 10*time.Second, func() bool {
383
+ r, _ := engine.GetRun(context.Background(), rid)
384
+ return r.State == run.StateCompleted
385
+ })
386
+ if indexOf(log.all(), "environmentStatus:completed") < 0 {
387
+ t.Fatalf("end did not set workspace status completed; events=%v", log.all())
388
+ }
389
+ if len(fr.cleaned) != 0 || fr.liveTerminals() != 1 {
390
+ t.Fatalf("cleanup disabled: CleanupRun calls=%v live terminals=%d, want 0 and 1", fr.cleaned, fr.liveTerminals())
391
+ }
392
+ }
393
+
394
+ // --- 3.16: transition ordering ---
395
+
396
+ func TestTransitionOrdering(t *testing.T) {
397
+ log := newEventLog()
398
+ sys := newFakeTaskSystem(log)
399
+ fr := newFakeRunner(log)
400
+ wf := workflow.Workflow{
401
+ Name: "reviewFlow", Repos: []string{"payments"},
402
+ Nodes: map[string]workflow.Node{
403
+ "start": {OnSuccess: []workflow.Route{{Target: "coding"}}},
404
+ "coding": {
405
+ Type: workflow.NodeAgent, Agent: "build", Description: "code",
406
+ OnSuccess: []workflow.Route{{Target: "review"}},
407
+ OnFailure: []workflow.Route{{Target: "coding"}},
408
+ },
409
+ "review": {
410
+ Type: workflow.NodeHITL, Agent: "reviewer", Description: "review",
411
+ OnSuccess: []workflow.Route{{Target: "end"}},
412
+ OnFailure: []workflow.Route{{Target: "coding"}},
413
+ },
414
+ "end": {},
415
+ },
416
+ }
417
+ engine := newEngine(t, goworkflows.Dependencies{
418
+ Repos: repoRegistryWith("payments", sys), Runner: fr, Harness: newFakeHarness(log),
419
+ })
420
+ rid, _ := startRun(engine, wf)
421
+ waitFor(t, 10*time.Second, func() bool {
422
+ r, _ := engine.GetRun(context.Background(), rid)
423
+ return r.CurrentNode == "coding" && r.CurrentNodeVisitID != ""
424
+ })
425
+ report := successReport("review")
426
+ report.Feedback = workflow.Feedback{
427
+ ReasonForNextStep: "ready", RequiredActions: "review it",
428
+ RelevantContext: "diff", ExpectedResult: "approval",
429
+ }
430
+ if _, err := engine.SubmitReport(context.Background(), reportRequest(rid, "coding", report)); err != nil {
431
+ t.Fatal(err)
432
+ }
433
+
434
+ waitFor(t, 10*time.Second, func() bool {
435
+ r, _ := engine.GetRun(context.Background(), rid)
436
+ return r.CurrentNode == "review"
437
+ })
438
+ events := log.all()
439
+ if statusIdx, terminalIdx := indexOf(events, "environmentStatus:in-review"), indexOf(events, "ensureTerminal:PAY-101:review"); statusIdx < 0 || terminalIdx < 0 || statusIdx >= terminalIdx {
440
+ t.Fatalf("HITL status was not set before terminal start; events=%v", events)
441
+ }
442
+
443
+ // Exact cross-primitive order, observed through the fake-adapter and fake-
444
+ // runner call logs (the settled observation seam):
445
+ // summary(current) -> feedback(selected next) -> CompleteMailbox(current)
446
+ // -> ApplyTaskConfig(next) -> next terminal.
447
+ // That the report+selected route are persisted BEFORE any of these effects
448
+ // is proven at the outcome level by TestCrashImmediatelyAfterReportPersistence
449
+ // (recovery_test.go): a crash after acceptance, with comment injection
450
+ // failing, restarts on the same db and resumes the PERSISTED selected route
451
+ // without re-asking the agent or re-running effects.
452
+ idx := map[string]int{}
453
+ for _, want := range []string{
454
+ "comment:PAY-101-coding", // summary to current mailbox
455
+ "comment:PAY-101-review", // feedback to selected next mailbox
456
+ "completeMailbox:PAY-101-coding", // complete current
457
+ "applyTaskConfig:PAY-101-review", // apply next node config
458
+ "ensureTerminal:PAY-101:review", // start next terminal
459
+ } {
460
+ idx[want] = indexOf(events, want)
461
+ if idx[want] < 0 {
462
+ t.Fatalf("missing event %q; events=%v", want, events)
463
+ }
464
+ }
465
+ order := []string{
466
+ "comment:PAY-101-coding", "comment:PAY-101-review", "completeMailbox:PAY-101-coding",
467
+ "applyTaskConfig:PAY-101-review", "ensureTerminal:PAY-101:review",
468
+ }
469
+ for i := 0; i+1 < len(order); i++ {
470
+ if idx[order[i]] >= idx[order[i+1]] {
471
+ t.Fatalf("order violated: %q(%d) !< %q(%d); events=%v",
472
+ order[i], idx[order[i]], order[i+1], idx[order[i+1]], events)
473
+ }
474
+ }
475
+ }
476
+
477
+ func TestEndSkipsFeedbackComment(t *testing.T) {
478
+ log := newEventLog()
479
+ sys := newFakeTaskSystem(log)
480
+ engine := newEngine(t, goworkflows.Dependencies{
481
+ Repos: repoRegistryWith("payments", sys), Runner: newFakeRunner(log), Harness: newFakeHarness(log),
482
+ })
483
+ rid, _ := startRun(engine, linearWorkflow(false))
484
+ waitFor(t, 10*time.Second, func() bool {
485
+ r, _ := engine.GetRun(context.Background(), rid)
486
+ return r.CurrentNode == "coding"
487
+ })
488
+ if _, err := engine.SubmitReport(context.Background(), reportRequest(rid, "coding", successReport("end"))); err != nil {
489
+ t.Fatal(err)
490
+ }
491
+ waitFor(t, 10*time.Second, func() bool {
492
+ r, _ := engine.GetRun(context.Background(), rid)
493
+ return r.State == run.StateCompleted
494
+ })
495
+ for _, e := range log.all() {
496
+ if e == "comment:PAY-end" {
497
+ t.Fatal("feedback comment written to an end mailbox; end has none")
498
+ }
499
+ }
500
+ }
501
+
502
+ // --- 3.20/3.22: report delivery, dedup, ack semantics ---
503
+
504
+ func TestReportAckOnlyAfterDurablePersistence(t *testing.T) {
505
+ log := newEventLog()
506
+ sys := newFakeTaskSystem(log)
507
+ engine := newEngine(t, goworkflows.Dependencies{
508
+ Repos: repoRegistryWith("payments", sys), Runner: newFakeRunner(log), Harness: newFakeHarness(log),
509
+ })
510
+ rid, _ := startRun(engine, linearWorkflow(false))
511
+ waitFor(t, 10*time.Second, func() bool {
512
+ r, _ := engine.GetRun(context.Background(), rid)
513
+ return r.CurrentNode == "coding"
514
+ })
515
+ ack, err := engine.SubmitReport(context.Background(), reportRequest(rid, "coding", successReport("end")))
516
+ if err != nil {
517
+ t.Fatal(err)
518
+ }
519
+ if !ack.Accepted || ack.Duplicate {
520
+ t.Fatalf("first report ack = %+v, want {accepted:true, duplicate:false}", ack)
521
+ }
522
+ // After the ack, the report is durably persisted: a crash/restart at
523
+ // this exact point must resume the persisted route without re-asking
524
+ // the agent. Covered by the crash-boundary test in recovery_test.go.
525
+ }
526
+
527
+ func TestNonCurrentVisitAckedAsOldDuplicate(t *testing.T) {
528
+ log := newEventLog()
529
+ sys := newFakeTaskSystem(log)
530
+ engine := newEngine(t, goworkflows.Dependencies{
531
+ Repos: repoRegistryWith("payments", sys), Runner: newFakeRunner(log), Harness: newFakeHarness(log),
532
+ })
533
+ rid, _ := startRun(engine, linearWorkflow(false))
534
+ waitFor(t, 10*time.Second, func() bool {
535
+ r, _ := engine.GetRun(context.Background(), rid)
536
+ return r.CurrentNode == "coding"
537
+ })
538
+ req := reportRequest(rid, "coding", successReport("end"))
539
+ if _, err := engine.SubmitReport(context.Background(), req); err != nil {
540
+ t.Fatal(err)
541
+ }
542
+ waitFor(t, 10*time.Second, func() bool {
543
+ r, _ := engine.GetRun(context.Background(), rid)
544
+ return r.State == run.StateCompleted
545
+ })
546
+
547
+ commentsBefore := log.count("comment:")
548
+ // Once reportId is processed, its body is irrelevant. Even a changed,
549
+ // invalid payload is dropped before validation.
550
+ req.Report.NextStep = "not-a-route"
551
+ ack, err := engine.SubmitReport(context.Background(), req)
552
+ if err != nil {
553
+ t.Fatal(err)
554
+ }
555
+ if !ack.Accepted || !ack.Duplicate {
556
+ t.Fatalf("stale report ack = %+v, want {accepted:true, duplicate:true}", ack)
557
+ }
558
+ if log.count("comment:") != commentsBefore {
559
+ t.Fatal("duplicate report caused repeated mailbox comments")
560
+ }
561
+ if log.count("completeMailbox:") != 1 {
562
+ t.Fatal("duplicate report caused repeated mailbox completion")
563
+ }
564
+ }
565
+
566
+ func TestFirstReportOnlyConsumed(t *testing.T) {
567
+ log := newEventLog()
568
+ sys := newFakeTaskSystem(log)
569
+ engine := newEngine(t, goworkflows.Dependencies{
570
+ Repos: repoRegistryWith("payments", sys), Runner: newFakeRunner(log), Harness: newFakeHarness(log),
571
+ })
572
+ rid, _ := startRun(engine, linearWorkflow(false))
573
+ waitFor(t, 10*time.Second, func() bool {
574
+ r, _ := engine.GetRun(context.Background(), rid)
575
+ return r.CurrentNode == "coding"
576
+ })
577
+ req := reportRequest(rid, "coding", successReport("end"))
578
+ ack1, err := engine.SubmitReport(context.Background(), req)
579
+ if err != nil || !ack1.Accepted || ack1.Duplicate {
580
+ t.Fatalf("first ack = %+v err=%v", ack1, err)
581
+ }
582
+ ack2, err := engine.SubmitReport(context.Background(), req)
583
+ if err != nil {
584
+ t.Fatal(err)
585
+ }
586
+ if !ack2.Accepted {
587
+ t.Fatalf("second ack = %+v, want accepted (harmless)", ack2)
588
+ }
589
+ waitFor(t, 10*time.Second, func() bool {
590
+ r, _ := engine.GetRun(context.Background(), rid)
591
+ return r.State == run.StateCompleted
592
+ })
593
+ if n := log.count("comment:PAY-101-coding"); n != 1 {
594
+ t.Fatalf("coding summaries = %d, want exactly 1 (no repeated graph effects)", n)
595
+ }
596
+ }
597
+
598
+ // --- 3.14: run identity (engine-level) ---
599
+
600
+ func TestEnsureRunIdempotentAndVisitStableAcrossReplay(t *testing.T) {
601
+ log := newEventLog()
602
+ sys := newFakeTaskSystem(log)
603
+ engine := newEngine(t, goworkflows.Dependencies{
604
+ Repos: repoRegistryWith("payments", sys), Runner: newFakeRunner(log), Harness: newFakeHarness(log),
605
+ })
606
+ wf := linearWorkflow(false)
607
+ rid, _ := startRun(engine, wf)
608
+ waitFor(t, 10*time.Second, func() bool {
609
+ r, _ := engine.GetRun(context.Background(), rid)
610
+ return r.CurrentNode == "coding" && r.CurrentNodeVisitID != ""
611
+ })
612
+ r, _ := engine.GetRun(context.Background(), rid)
613
+ visit := r.CurrentNodeVisitID
614
+
615
+ // Repeated EnsureRun with the same deterministic ID returns the existing
616
+ // run without restarting and without changing the current visit.
617
+ created, err := engine.EnsureRun(context.Background(), run.Start{
618
+ ID: rid, Repo: "payments", RepoPath: "/srv/payments", Workflow: wf,
619
+ Ticket: task.TicketRef{ID: "1", Key: "PAY-101"},
620
+ })
621
+ if err != nil {
622
+ t.Fatal(err)
623
+ }
624
+ if created {
625
+ t.Fatal("repeated EnsureRun reported created=true; want existing run")
626
+ }
627
+ r2, _ := engine.GetRun(context.Background(), rid)
628
+ if r2.CurrentNodeVisitID != visit {
629
+ t.Fatalf("visit changed on repeated EnsureRun: %q -> %q", visit, r2.CurrentNodeVisitID)
630
+ }
631
+ }
632
+
633
+ // --- helpers ---
634
+
635
+ func repoRegistryWith(name string, sys task.System) *repo.Registry {
636
+ reg := &repo.Registry{}
637
+ reg.Replace(&repo.Repo{Name: name, Path: "/srv/" + name, TaskSystem: sys})
638
+ return reg
639
+ }
640
+
641
+ func waitFor(t *testing.T, d time.Duration, cond func() bool) {
642
+ t.Helper()
643
+ deadline := time.Now().Add(d)
644
+ for time.Now().Before(deadline) {
645
+ if cond() {
646
+ return
647
+ }
648
+ time.Sleep(20 * time.Millisecond)
649
+ }
650
+ t.Fatal("condition not met within " + d.String())
651
+ }
652
+
653
+ func indexOf(events []string, want string) int {
654
+ for i, e := range events {
655
+ if e == want {
656
+ return i
657
+ }
658
+ }
659
+ return -1
660
+ }