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,133 @@
1
+ package goworkflows_test
2
+
3
+ import (
4
+ "context"
5
+ "path/filepath"
6
+ "testing"
7
+ "time"
8
+
9
+ "github.com/rajpopat27/relay-flow/internal/execution/goworkflows"
10
+ "github.com/rajpopat27/relay-flow/internal/identity"
11
+ "github.com/rajpopat27/relay-flow/internal/run"
12
+ "github.com/rajpopat27/relay-flow/internal/task"
13
+ "github.com/rajpopat27/relay-flow/internal/workflow"
14
+ )
15
+
16
+ func TestPersistedRuntimeLoopAndRestart(t *testing.T) {
17
+ log := newEventLog()
18
+ sys := newFakeTaskSystem(log)
19
+ fr := newFakeRunner(log)
20
+ fh := newFakeHarness(log)
21
+ wf := workflow.Workflow{
22
+ Name: "loopFlow", Repos: []string{"payments"},
23
+ Nodes: map[string]workflow.Node{
24
+ "start": {OnSuccess: []workflow.Route{{Target: "implement"}}},
25
+ "implement": {Type: workflow.NodeAgent, Agent: "build", Description: "implement",
26
+ OnSuccess: []workflow.Route{{Target: "verify"}}, OnFailure: []workflow.Route{{Target: "verify"}}},
27
+ "verify": {Type: workflow.NodeAgent, Agent: "verify", Description: "verify",
28
+ OnSuccess: []workflow.Route{{Target: "end"}}, OnFailure: []workflow.Route{{Target: "implement"}}},
29
+ "end": {},
30
+ },
31
+ }
32
+ db := filepath.Join(t.TempDir(), "state.db")
33
+ policy := run.RuntimePolicy{KeepTerminalsAlive: true, KeepSessionsAlive: true}
34
+ deps := goworkflows.Dependencies{
35
+ Repos: repoRegistryWith("payments", sys), Runner: fr, Harness: fh, Runtime: &policy,
36
+ }
37
+ e1, err := goworkflows.New(db, deps)
38
+ if err != nil {
39
+ t.Fatal(err)
40
+ }
41
+ if err := e1.Start(context.Background()); err != nil {
42
+ t.Fatal(err)
43
+ }
44
+ rid := identity.NewRunID("payments", "loopFlow", "PAY-101")
45
+ start := run.Start{ID: rid, Repo: "payments", RepoPath: "/srv/payments", Workflow: wf, Ticket: task.TicketRef{ID: "1", Key: "PAY-101"}, Runtime: policy}
46
+ if _, err := e1.EnsureRun(context.Background(), start); err != nil {
47
+ t.Fatal(err)
48
+ }
49
+ waitFor(t, 10*time.Second, func() bool {
50
+ r, _ := e1.GetRun(context.Background(), rid)
51
+ return r.CurrentNode == "implement" && r.CurrentNodeVisitID != ""
52
+ })
53
+ first, _ := e1.GetRun(context.Background(), rid)
54
+ firstRT, _ := e1.GetNodeRuntime(context.Background(), rid, "implement")
55
+ if _, err := e1.RegisterNodeSession(context.Background(), run.NodeRuntimeRegistration{RunID: rid, Node: "implement", SessionID: "session-implement"}); err != nil {
56
+ t.Fatal(err)
57
+ }
58
+ firstReport := reportRequest(rid, "implement", loopReport(workflow.OutcomeSuccess, "verify"))
59
+ if _, err := e1.SubmitReport(context.Background(), firstReport); err != nil {
60
+ t.Fatal(err)
61
+ }
62
+ waitFor(t, 10*time.Second, func() bool { r, _ := e1.GetRun(context.Background(), rid); return r.CurrentNode == "verify" })
63
+ verify, _ := e1.GetRun(context.Background(), rid)
64
+ if _, err := e1.RegisterNodeSession(context.Background(), run.NodeRuntimeRegistration{RunID: rid, Node: "verify", SessionID: "session-verify"}); err != nil {
65
+ t.Fatal(err)
66
+ }
67
+ verifyRT, err := e1.GetNodeRuntime(context.Background(), rid, "verify")
68
+ if err != nil || verifyRT.SessionID != "session-verify" || verifyRT.NodeVisitID != verify.CurrentNodeVisitID {
69
+ t.Fatalf("verify runtime = %+v, %v", verifyRT, err)
70
+ }
71
+ if _, err := e1.SubmitReport(context.Background(), reportRequest(rid, "verify", loopReport(workflow.OutcomeFailure, "implement"))); err != nil {
72
+ t.Fatal(err)
73
+ }
74
+ waitFor(t, 10*time.Second, func() bool {
75
+ r, _ := e1.GetRun(context.Background(), rid)
76
+ return r.CurrentNode == "implement" && r.CurrentNodeVisitID != first.CurrentNodeVisitID
77
+ })
78
+ second, _ := e1.GetRun(context.Background(), rid)
79
+ secondRT, _ := e1.GetNodeRuntime(context.Background(), rid, "implement")
80
+ if secondRT.TerminalID != firstRT.TerminalID || secondRT.SessionID != "session-implement" || secondRT.NodeVisitID != second.CurrentNodeVisitID {
81
+ t.Fatalf("loop runtime = %+v; first=%+v", secondRT, firstRT)
82
+ }
83
+ staleAck, err := e1.SubmitReport(context.Background(), firstReport)
84
+ if err != nil || !staleAck.Duplicate {
85
+ t.Fatalf("stale ack=%+v err=%v", staleAck, err)
86
+ }
87
+ if log.count("findTerminalID:") == 0 {
88
+ t.Fatalf("normal path did not check persisted terminal IDs: %v", log.all())
89
+ }
90
+ if log.count("findSession:") != 0 {
91
+ t.Fatalf("normal path used session discovery: %v", log.all())
92
+ }
93
+
94
+ oldTerminal := secondRT.TerminalID
95
+ fr.killTerminals()
96
+ findTerminalBefore := log.count("findTerminalID:")
97
+ findSessionBefore := log.count("findSession:")
98
+ e2 := restartEngine(t, db, deps, e1)
99
+ waitFor(t, 10*time.Second, func() bool {
100
+ r, _ := e2.GetRun(context.Background(), rid)
101
+ return r.CurrentNodeVisitID == second.CurrentNodeVisitID
102
+ })
103
+ if _, err := e2.EnsureRun(context.Background(), start); err != nil {
104
+ t.Fatal(err)
105
+ }
106
+ resumeEvent := "buildCommand:implement:" + string(second.CurrentNodeVisitID) + ":resume=session-implement"
107
+ waitFor(t, 10*time.Second, func() bool {
108
+ runtime, _ := e2.GetNodeRuntime(context.Background(), rid, "implement")
109
+ return runtime.TerminalID != "" && runtime.TerminalID != oldTerminal
110
+ })
111
+ after, _ := e2.GetNodeRuntime(context.Background(), rid, "implement")
112
+ if after.TerminalID == oldTerminal || after.SessionID != "session-implement" || after.NodeVisitID != second.CurrentNodeVisitID {
113
+ t.Fatalf("restart did not resume/replace direct runtime: old=%+v after=%+v", secondRT, after)
114
+ }
115
+ if log.count("findTerminalID:") == findTerminalBefore || log.count("findSession:") != findSessionBefore {
116
+ t.Fatalf("restart did not use only the persisted terminal/session IDs: %v", log.all())
117
+ }
118
+ if log.count(resumeEvent) < 1 {
119
+ t.Fatalf("restart did not pass persisted session ID to harness: %v", log.all())
120
+ }
121
+ }
122
+
123
+ func loopReport(status workflow.Outcome, next string) workflow.Report {
124
+ r := successReport(next)
125
+ r.Status = status
126
+ if next != "end" {
127
+ r.Feedback.ReasonForNextStep = "route"
128
+ r.Feedback.RequiredActions = "act"
129
+ r.Feedback.RelevantContext = "context"
130
+ r.Feedback.ExpectedResult = "result"
131
+ }
132
+ return r
133
+ }
@@ -0,0 +1,510 @@
1
+ package goworkflows
2
+
3
+ import (
4
+ "context"
5
+ "database/sql"
6
+ "errors"
7
+ "path/filepath"
8
+ "testing"
9
+ "time"
10
+
11
+ "github.com/rajpopat27/relay-flow/internal/harness"
12
+ "github.com/rajpopat27/relay-flow/internal/repo"
13
+ "github.com/rajpopat27/relay-flow/internal/run"
14
+ "github.com/rajpopat27/relay-flow/internal/runner"
15
+ "github.com/rajpopat27/relay-flow/internal/task"
16
+ "github.com/rajpopat27/relay-flow/internal/workflow"
17
+ )
18
+
19
+ func TestNodeRuntimeMigrationAndRestart(t *testing.T) {
20
+ ctx := context.Background()
21
+ path := filepath.Join(t.TempDir(), "state.db")
22
+ db := openProjectionDB(t, path)
23
+
24
+ // Simulate an existing database that predates relay_node_runtime.
25
+ if _, err := db.Exec(`CREATE TABLE relay_runs (
26
+ id TEXT PRIMARY KEY, repo TEXT NOT NULL, workflow TEXT NOT NULL,
27
+ ticket_id TEXT NOT NULL, ticket_key TEXT NOT NULL, state TEXT NOT NULL,
28
+ current_node TEXT, current_node_visit_id TEXT, last_error TEXT,
29
+ retry_error TEXT, retry_attempt INTEGER, next_retry_at DATETIME,
30
+ started_at DATETIME NOT NULL, updated_at DATETIME NOT NULL, finished_at DATETIME
31
+ )`); err != nil {
32
+ t.Fatal(err)
33
+ }
34
+ p := &RunProjection{DB: db}
35
+ if err := p.migrate(); err != nil {
36
+ t.Fatalf("migrate existing database: %v", err)
37
+ }
38
+
39
+ id := run.ID("payments/basic/PAY-101")
40
+ if err := p.insertStart(ctx, run.Start{
41
+ ID: id, Repo: "payments", Workflow: workflow.Workflow{Name: "basic"},
42
+ Ticket: task.TicketRef{ID: "1", Key: "PAY-101"},
43
+ }, time.Now().UTC()); err != nil {
44
+ t.Fatal(err)
45
+ }
46
+ firstVisit := run.NodeVisitID("visit-1")
47
+ if err := p.updateNode(ctx, id, run.StateRunning, "implement", firstVisit); err != nil {
48
+ t.Fatal(err)
49
+ }
50
+ if err := p.updateNodeRuntime(ctx, NodeRuntime{
51
+ RunID: id, Node: "implement", TerminalID: "term-1", SessionID: "session-1", NodeVisitID: firstVisit,
52
+ }); err != nil {
53
+ t.Fatal(err)
54
+ }
55
+
56
+ // Moving to another node retains implement's runtime row.
57
+ if err := p.updateNode(ctx, id, run.StateRunning, "verify", "visit-2"); err != nil {
58
+ t.Fatal(err)
59
+ }
60
+ implement, err := p.getNodeRuntime(ctx, id, "implement")
61
+ if err != nil {
62
+ t.Fatal(err)
63
+ }
64
+ if implement.TerminalID != "term-1" || implement.SessionID != "session-1" || implement.NodeVisitID != firstVisit {
65
+ t.Fatalf("runtime changed across transition: %+v", implement)
66
+ }
67
+
68
+ // Revisiting updates only the visit ID, preserving reusable identities.
69
+ secondVisit := run.NodeVisitID("visit-3")
70
+ if err := p.updateNode(ctx, id, run.StateRunning, "implement", secondVisit); err != nil {
71
+ t.Fatal(err)
72
+ }
73
+ implement, err = p.getNodeRuntime(ctx, id, "implement")
74
+ if err != nil {
75
+ t.Fatal(err)
76
+ }
77
+ if implement.TerminalID != "term-1" || implement.SessionID != "session-1" || implement.NodeVisitID != secondVisit {
78
+ t.Fatalf("runtime not preserved on revisit: %+v", implement)
79
+ }
80
+ if implement.UpdatedAt.IsZero() {
81
+ t.Fatal("runtime updated_at is zero")
82
+ }
83
+
84
+ if err := db.Close(); err != nil {
85
+ t.Fatal(err)
86
+ }
87
+ db = openProjectionDB(t, path)
88
+ defer db.Close()
89
+ p = &RunProjection{DB: db}
90
+ if err := p.migrate(); err != nil {
91
+ t.Fatalf("migrate after restart: %v", err)
92
+ }
93
+ implement, err = p.getNodeRuntime(ctx, id, "implement")
94
+ if err != nil {
95
+ t.Fatalf("query runtime after restart: %v", err)
96
+ }
97
+ if implement.TerminalID != "term-1" || implement.SessionID != "session-1" || implement.NodeVisitID != secondVisit {
98
+ t.Fatalf("runtime changed across restart: %+v", implement)
99
+ }
100
+ }
101
+
102
+ func TestNodeRuntimeRemovedOnlyByRetention(t *testing.T) {
103
+ ctx := context.Background()
104
+ db := openProjectionDB(t, filepath.Join(t.TempDir(), "state.db"))
105
+ defer db.Close()
106
+ p := &RunProjection{DB: db}
107
+ if err := p.migrate(); err != nil {
108
+ t.Fatal(err)
109
+ }
110
+
111
+ id := run.ID("payments/basic/PAY-OLD")
112
+ started := time.Now().UTC().Add(-32 * 24 * time.Hour)
113
+ if err := p.insertStart(ctx, run.Start{
114
+ ID: id, Repo: "payments", Workflow: workflow.Workflow{Name: "basic"},
115
+ Ticket: task.TicketRef{ID: "old", Key: "PAY-OLD"},
116
+ }, started); err != nil {
117
+ t.Fatal(err)
118
+ }
119
+ if err := p.updateNode(ctx, id, run.StateRunning, "implement", "visit-old"); err != nil {
120
+ t.Fatal(err)
121
+ }
122
+ if err := p.updateNodeRuntime(ctx, NodeRuntime{
123
+ RunID: id, Node: "implement", TerminalID: "term-old", SessionID: "session-old", NodeVisitID: "visit-old",
124
+ }); err != nil {
125
+ t.Fatal(err)
126
+ }
127
+ finished := time.Now().UTC().Add(-31 * 24 * time.Hour)
128
+ if err := p.updateState(ctx, id, run.StateCompleted, "", &finished); err != nil {
129
+ t.Fatal(err)
130
+ }
131
+ if _, err := p.getNodeRuntime(ctx, id, "implement"); err != nil {
132
+ t.Fatalf("completion removed runtime before retention: %v", err)
133
+ }
134
+
135
+ ids, err := p.sweepRetention(ctx, time.Now().UTC().Add(-30*24*time.Hour))
136
+ if err != nil {
137
+ t.Fatal(err)
138
+ }
139
+ if len(ids) != 1 || ids[0] != string(id) {
140
+ t.Fatalf("retained ids = %v, want [%s]", ids, id)
141
+ }
142
+ if _, err := p.getNodeRuntime(ctx, id, "implement"); !errors.Is(err, errNodeRuntimeNotFound) {
143
+ t.Fatalf("runtime after retention error = %v, want not found", err)
144
+ }
145
+ }
146
+
147
+ func TestNodeRuntimeSessionRegistrationKeepsOldSessionBoundToOldVisit(t *testing.T) {
148
+ ctx := context.Background()
149
+ db := openProjectionDB(t, filepath.Join(t.TempDir(), "state.db"))
150
+ defer db.Close()
151
+ p := &RunProjection{DB: db}
152
+ if err := p.migrate(); err != nil {
153
+ t.Fatal(err)
154
+ }
155
+ id := run.ID("payments/basic/PAY-101")
156
+ if err := p.insertStart(ctx, run.Start{
157
+ ID: id, Repo: "payments", Workflow: workflow.Workflow{Name: "basic"},
158
+ Ticket: task.TicketRef{ID: "1", Key: "PAY-101"},
159
+ }, time.Now().UTC()); err != nil {
160
+ t.Fatal(err)
161
+ }
162
+ if err := p.updateNodeRuntimeVisit(ctx, id, "implement", "visit-current"); err != nil {
163
+ t.Fatal(err)
164
+ }
165
+
166
+ accepted, err := p.registerNodeSession(ctx, run.NodeRuntimeRegistration{
167
+ RunID: id, Node: "implement", SessionID: "session-current",
168
+ })
169
+ if err != nil || !accepted {
170
+ t.Fatalf("current registration = %v, %v; want accepted", accepted, err)
171
+ }
172
+ if err := p.updateNodeRuntimeVisit(ctx, id, "implement", "visit-next"); err != nil {
173
+ t.Fatal(err)
174
+ }
175
+ accepted, err = p.registerNodeSession(ctx, run.NodeRuntimeRegistration{
176
+ RunID: id, Node: "implement", SessionID: "session-current",
177
+ })
178
+ if err != nil || accepted {
179
+ t.Fatalf("old session registration = %v, %v; want rejected", accepted, err)
180
+ }
181
+ rt, err := p.getNodeRuntime(ctx, id, "implement")
182
+ if err != nil {
183
+ t.Fatal(err)
184
+ }
185
+ if rt.SessionID != "session-current" || rt.NodeVisitID != "visit-next" {
186
+ t.Fatalf("old session changed current visit binding: %+v", rt)
187
+ }
188
+ }
189
+
190
+ func TestEnsureNodeRuntimeUsesDirectIDsAndFallsBackFresh(t *testing.T) {
191
+ ctx := context.Background()
192
+ fr := &runtimeTestRunner{}
193
+ fh := &runtimeTestHarness{}
194
+ db := openProjectionDB(t, filepath.Join(t.TempDir(), "state.db"))
195
+ defer db.Close()
196
+ p := &RunProjection{DB: db}
197
+ if err := p.migrate(); err != nil {
198
+ t.Fatal(err)
199
+ }
200
+ id := run.ID("payments/basic/PAY-101")
201
+ if err := p.insertStart(ctx, run.Start{
202
+ ID: id, Repo: "payments", Workflow: workflow.Workflow{Name: "basic"},
203
+ Ticket: task.TicketRef{ID: "1", Key: "PAY-101"},
204
+ }, time.Now().UTC()); err != nil {
205
+ t.Fatal(err)
206
+ }
207
+ if err := p.updateNodeRuntime(ctx, NodeRuntime{
208
+ RunID: id, Node: "implement", TerminalID: "dead-term", SessionID: "dead-session", NodeVisitID: "visit-2",
209
+ }); err != nil {
210
+ t.Fatal(err)
211
+ }
212
+ a := &Activities{Runner: fr, Harness: fh, Runs: p}
213
+ nw := run.NodeWork{Work: run.Work{RunID: id, Repo: "payments", Workflow: "basic", Parent: task.TicketRef{Key: "PAY-101"}}, Node: "implement", NodeVisitID: "visit-2"}
214
+ spec := harness.LaunchSpec{RunID: id, NodeVisitID: "visit-2", RepoName: "payments", Workflow: "basic", Ticket: "PAY-101", Node: "implement", Agent: "build", Title: "PAY-101:implement", Prompt: "work", NudgePrompt: "custom instructions"}
215
+ if err := a.EnsureNodeRuntime(ctx, nw, "/srv/payments", spec, NodeRuntime{NodeVisitID: "visit-2"}); err != nil {
216
+ t.Fatal(err)
217
+ }
218
+ rt, err := p.getNodeRuntime(ctx, id, "implement")
219
+ if err != nil {
220
+ t.Fatal(err)
221
+ }
222
+ if rt.TerminalID == "" || rt.TerminalID == "dead-term" || rt.SessionID != "dead-session" {
223
+ t.Fatalf("failed direct IDs not replaced atomically: %+v", rt)
224
+ }
225
+ if fr.findCalls != 1 || fh.buildCalls != 1 || fr.createCalls != 1 {
226
+ t.Fatalf("stored-ID replacement calls: find=%d build=%d create=%d", fr.findCalls, fh.buildCalls, fr.createCalls)
227
+ }
228
+ if len(fr.findIDs) != 1 || fr.findIDs[0] != "dead-term" {
229
+ t.Fatalf("FindTerminal IDs = %v, want [dead-term]", fr.findIDs)
230
+ }
231
+ if len(fh.resumeIDs) != 1 || fh.resumeIDs[0] != "dead-session" {
232
+ t.Fatalf("BuildCommand ResumeIDs = %v, want [dead-session]", fh.resumeIDs)
233
+ }
234
+ for _, prompt := range fh.prompts {
235
+ if prompt != "work" {
236
+ t.Fatalf("same-visit relaunch prompt = %q, want standard prompt only", prompt)
237
+ }
238
+ }
239
+ }
240
+
241
+ func TestEnsureNodeRuntimeInitialLaunchAppendsCustomInstructions(t *testing.T) {
242
+ ctx := context.Background()
243
+ db := openProjectionDB(t, filepath.Join(t.TempDir(), "state.db"))
244
+ defer db.Close()
245
+ p := &RunProjection{DB: db}
246
+ if err := p.migrate(); err != nil {
247
+ t.Fatal(err)
248
+ }
249
+ id := run.ID("payments/basic/PAY-100")
250
+ if err := p.insertStart(ctx, run.Start{ID: id, Repo: "payments", Workflow: workflow.Workflow{Name: "basic"}, Ticket: task.TicketRef{ID: "0", Key: "PAY-100"}}, time.Now().UTC()); err != nil {
251
+ t.Fatal(err)
252
+ }
253
+ if err := p.updateNodeRuntimeVisit(ctx, id, "implement", "visit-first"); err != nil {
254
+ t.Fatal(err)
255
+ }
256
+ fh := &runtimeTestHarness{}
257
+ fr := &runtimeTestRunner{}
258
+ a := &Activities{Runner: fr, Harness: fh, Runs: p}
259
+ nw := run.NodeWork{Work: run.Work{RunID: id}, Node: "implement", NodeVisitID: "visit-first"}
260
+ spec := harness.LaunchSpec{RunID: id, NodeVisitID: "visit-first", Node: "implement", NodeType: workflow.NodeHITL, Agent: "build", Prompt: "standard prompt", NudgePrompt: "custom instructions"}
261
+ if err := a.EnsureNodeRuntime(ctx, nw, "", spec, NodeRuntime{}); err != nil {
262
+ t.Fatal(err)
263
+ }
264
+ if len(fh.prompts) != 1 || fh.prompts[0] != "standard prompt\n\ncustom instructions" {
265
+ t.Fatalf("initial prompt = %q", fh.prompts)
266
+ }
267
+ if len(fr.statuses) != 1 || fr.statuses[0] != runner.WorkspaceStatusInReview {
268
+ t.Fatalf("HITL workspace statuses = %v, want in-review", fr.statuses)
269
+ }
270
+ }
271
+
272
+ func TestEnsureNodeRuntimeSendFailureClosesLiveTerminal(t *testing.T) {
273
+ ctx := context.Background()
274
+ db := openProjectionDB(t, filepath.Join(t.TempDir(), "state.db"))
275
+ defer db.Close()
276
+ p := &RunProjection{DB: db}
277
+ if err := p.migrate(); err != nil {
278
+ t.Fatal(err)
279
+ }
280
+ id := run.ID("payments/basic/PAY-102")
281
+ if err := p.insertStart(ctx, run.Start{ID: id, Repo: "payments", Workflow: workflow.Workflow{Name: "basic"}, Ticket: task.TicketRef{ID: "2", Key: "PAY-102"}}, time.Now().UTC()); err != nil {
282
+ t.Fatal(err)
283
+ }
284
+ if err := p.updateNodeRuntime(ctx, NodeRuntime{RunID: id, Node: "implement", TerminalID: "live-old", SessionID: "session-old", NodeVisitID: "visit-old"}); err != nil {
285
+ t.Fatal(err)
286
+ }
287
+ if err := p.updateNodeRuntimeVisit(ctx, id, "implement", "visit-new"); err != nil {
288
+ t.Fatal(err)
289
+ }
290
+ fr := &runtimeTestRunner{live: true, sendErr: errors.New("send failed")}
291
+ fh := &runtimeTestHarness{}
292
+ a := &Activities{Runner: fr, Harness: fh, Runs: p}
293
+ nw := run.NodeWork{Work: run.Work{RunID: id, Repo: "payments", Workflow: "basic", Parent: task.TicketRef{Key: "PAY-102"}}, Node: "implement", NodeVisitID: "visit-new", Mailbox: task.Mailbox{Key: "PAY-234", Node: "implement"}}
294
+ spec := harness.LaunchSpec{RunID: id, NodeVisitID: "visit-new", Node: "implement", Agent: "build", Title: "PAY-102:implement", Prompt: "work", NudgePrompt: "Read the latest review feedback."}
295
+ if err := a.EnsureNodeRuntime(ctx, nw, "/srv/payments", spec, NodeRuntime{RunID: id, Node: "implement", TerminalID: "live-old", SessionID: "session-old", NodeVisitID: "visit-old"}); err != nil {
296
+ t.Fatal(err)
297
+ }
298
+ if fr.closeCalls != 1 || fr.closedIDs[0] != "live-old" {
299
+ t.Fatalf("old live terminal not closed before replacement: %+v", fr.closedIDs)
300
+ }
301
+ if len(fr.sentTexts) != 1 || fr.sentTexts[0] != "New feedback was added to the comments section of your mailbox subtask PAY-234. Read it.\n\nRead the latest review feedback." {
302
+ t.Fatalf("live revisit prompt = %q", fr.sentTexts)
303
+ }
304
+ if len(fh.prompts) != 1 || fh.prompts[0] != "work\n\nRead the latest review feedback." {
305
+ t.Fatalf("revisit replacement prompt = %q", fh.prompts)
306
+ }
307
+ rt, _ := p.getNodeRuntime(ctx, id, "implement")
308
+ if rt.TerminalID == "live-old" || rt.SessionID != "session-old" {
309
+ t.Fatalf("send failure did not replace IDs: %+v", rt)
310
+ }
311
+ if len(fh.resumeIDs) != 1 || fh.resumeIDs[0] != "session-old" {
312
+ t.Fatalf("replacement ResumeIDs = %v, want [session-old]", fh.resumeIDs)
313
+ }
314
+ }
315
+
316
+ func TestEnsureNodeRuntimeSameVisitSendsNothing(t *testing.T) {
317
+ ctx := context.Background()
318
+ db := openProjectionDB(t, filepath.Join(t.TempDir(), "state.db"))
319
+ defer db.Close()
320
+ p := &RunProjection{DB: db}
321
+ if err := p.migrate(); err != nil {
322
+ t.Fatal(err)
323
+ }
324
+ id := run.ID("payments/basic/PAY-103")
325
+ if err := p.insertStart(ctx, run.Start{ID: id, Repo: "payments", Workflow: workflow.Workflow{Name: "basic"}, Ticket: task.TicketRef{ID: "3", Key: "PAY-103"}}, time.Now().UTC()); err != nil {
326
+ t.Fatal(err)
327
+ }
328
+ if err := p.updateNodeRuntime(ctx, NodeRuntime{RunID: id, Node: "implement", TerminalID: "live", SessionID: "session", NodeVisitID: "visit"}); err != nil {
329
+ t.Fatal(err)
330
+ }
331
+ fr := &runtimeTestRunner{live: true}
332
+ a := &Activities{Runner: fr, Harness: &runtimeTestHarness{}, Runs: p}
333
+ nw := run.NodeWork{Work: run.Work{RunID: id}, Node: "implement", NodeVisitID: "visit"}
334
+ spec := harness.LaunchSpec{RunID: id, NodeVisitID: "visit", Node: "implement", Agent: "build", NudgePrompt: "custom instructions"}
335
+ if err := a.EnsureNodeRuntime(ctx, nw, "", spec, NodeRuntime{RunID: id, Node: "implement", TerminalID: "live", SessionID: "session", NodeVisitID: "visit"}); err != nil {
336
+ t.Fatal(err)
337
+ }
338
+ if len(fr.sentTexts) != 0 || fr.createCalls != 0 {
339
+ t.Fatalf("same visit sent=%q creates=%d", fr.sentTexts, fr.createCalls)
340
+ }
341
+ }
342
+
343
+ func TestEnsureNodeRuntimeRejectsStaleVisitWithoutLaunch(t *testing.T) {
344
+ ctx := context.Background()
345
+ db := openProjectionDB(t, filepath.Join(t.TempDir(), "state.db"))
346
+ defer db.Close()
347
+ p := &RunProjection{DB: db}
348
+ if err := p.migrate(); err != nil {
349
+ t.Fatal(err)
350
+ }
351
+ id := run.ID("payments/basic/PAY-103")
352
+ if err := p.insertStart(ctx, run.Start{ID: id, Repo: "payments", Workflow: workflow.Workflow{Name: "basic"}, Ticket: task.TicketRef{ID: "3", Key: "PAY-103"}}, time.Now().UTC()); err != nil {
353
+ t.Fatal(err)
354
+ }
355
+ if err := p.updateNodeRuntimeVisit(ctx, id, "implement", "visit-current"); err != nil {
356
+ t.Fatal(err)
357
+ }
358
+ fr := &runtimeTestRunner{}
359
+ a := &Activities{Runner: fr, Harness: &runtimeTestHarness{}, Runs: p}
360
+ nw := run.NodeWork{Work: run.Work{RunID: id}, Node: "implement", NodeVisitID: "visit-stale"}
361
+ err := a.EnsureNodeRuntime(ctx, nw, "", harness.LaunchSpec{NodeVisitID: "visit-stale", Node: "implement", Agent: "build"}, NodeRuntime{})
362
+ if err == nil || fr.createCalls != 0 {
363
+ t.Fatalf("stale visit err=%v createCalls=%d", err, fr.createCalls)
364
+ }
365
+ }
366
+
367
+ func TestRuntimeKeepPolicies(t *testing.T) {
368
+ ctx := context.Background()
369
+ for _, tc := range []struct {
370
+ name string
371
+ policy run.RuntimePolicy
372
+ wantTerminal string
373
+ wantSession string
374
+ wantCloseCalls int
375
+ }{
376
+ {name: "explicitly close terminal keep session", policy: run.RuntimePolicy{KeepSessionsAlive: true}, wantSession: "session-1", wantCloseCalls: 1},
377
+ {name: "explicitly discard both", policy: run.RuntimePolicy{}, wantCloseCalls: 1},
378
+ {name: "keep both", policy: run.RuntimePolicy{KeepTerminalsAlive: true, KeepSessionsAlive: true}, wantTerminal: "term-1", wantSession: "session-1"},
379
+ } {
380
+ t.Run(tc.name, func(t *testing.T) {
381
+ db := openProjectionDB(t, filepath.Join(t.TempDir(), "state.db"))
382
+ defer db.Close()
383
+ p := &RunProjection{DB: db}
384
+ if err := p.migrate(); err != nil {
385
+ t.Fatal(err)
386
+ }
387
+ id := run.ID("payments/basic/PAY-104")
388
+ if err := p.insertStart(ctx, run.Start{ID: id, Repo: "payments", Workflow: workflow.Workflow{Name: "basic"}, Ticket: task.TicketRef{ID: "4", Key: "PAY-104"}}, time.Now().UTC()); err != nil {
389
+ t.Fatal(err)
390
+ }
391
+ if err := p.updateNodeRuntime(ctx, NodeRuntime{RunID: id, Node: "implement", TerminalID: "term-1", SessionID: "session-1", NodeVisitID: "visit-1"}); err != nil {
392
+ t.Fatal(err)
393
+ }
394
+ fr := &runtimeTestRunner{}
395
+ a := &Activities{Runner: fr, Runs: p}
396
+ nw := run.NodeWork{Work: run.Work{RunID: id, Parent: task.TicketRef{Key: "PAY-104"}}, Node: "implement"}
397
+ if err := a.CheckpointNodeRuntime(ctx, nw, "", tc.policy); err != nil {
398
+ t.Fatal(err)
399
+ }
400
+ rt, err := p.getNodeRuntime(ctx, id, "implement")
401
+ if err != nil {
402
+ t.Fatal(err)
403
+ }
404
+ if rt.TerminalID != tc.wantTerminal || rt.SessionID != tc.wantSession || fr.closeCalls != tc.wantCloseCalls {
405
+ t.Fatalf("runtime=%+v closeCalls=%d", rt, fr.closeCalls)
406
+ }
407
+ })
408
+ }
409
+ }
410
+
411
+ func TestEngineRuntimePolicyDefaultsKeepBoth(t *testing.T) {
412
+ deps := Dependencies{
413
+ Repos: repo.NewRegistry(),
414
+ Runner: &runtimeTestRunner{},
415
+ Harness: &runtimeTestHarness{},
416
+ }
417
+ engine, err := New(filepath.Join(t.TempDir(), "state.db"), deps)
418
+ if err != nil {
419
+ t.Fatal(err)
420
+ }
421
+ defer engine.db.Close()
422
+ if !engine.runtime.KeepTerminalsAlive || !engine.runtime.KeepSessionsAlive {
423
+ t.Fatalf("default runtime policy = %+v, want both true", engine.runtime)
424
+ }
425
+ }
426
+
427
+ type runtimeTestRunner struct {
428
+ findCalls int
429
+ findIDs []string
430
+ createCalls int
431
+ live bool
432
+ liveID string
433
+ sendErr error
434
+ sentTexts []string
435
+ closeCalls int
436
+ closedIDs []string
437
+ statuses []string
438
+ }
439
+
440
+ func (*runtimeTestRunner) DiscoverRepos(context.Context) ([]runner.RepoCandidate, error) {
441
+ return nil, nil
442
+ }
443
+ func (*runtimeTestRunner) ValidateRepo(context.Context, string, string) error { return nil }
444
+ func (*runtimeTestRunner) EnsureEnvironment(context.Context, runner.RunSpec) (runner.Environment, error) {
445
+ return runner.Environment{ID: "env"}, nil
446
+ }
447
+ func (r *runtimeTestRunner) SetEnvironmentStatus(_ context.Context, _ runner.Environment, status string) error {
448
+ r.statuses = append(r.statuses, status)
449
+ return nil
450
+ }
451
+ func (r *runtimeTestRunner) FindTerminal(_ context.Context, terminal runner.Terminal) (runner.Terminal, bool, error) {
452
+ r.findCalls++
453
+ r.findIDs = append(r.findIDs, terminal.ID)
454
+ if !r.live || (r.liveID != "" && terminal.ID != r.liveID) {
455
+ return runner.Terminal{}, false, nil
456
+ }
457
+ return terminal, true, nil
458
+ }
459
+ func (r *runtimeTestRunner) SendTerminal(_ context.Context, _ runner.Terminal, text string) error {
460
+ r.sentTexts = append(r.sentTexts, text)
461
+ return r.sendErr
462
+ }
463
+ func (r *runtimeTestRunner) CreateTerminal(context.Context, runner.Environment, string, runner.Command) (runner.Terminal, error) {
464
+ r.createCalls++
465
+ r.live = true
466
+ r.liveID = "fresh-term"
467
+ return runner.Terminal{ID: r.liveID}, nil
468
+ }
469
+ func (r *runtimeTestRunner) CloseTerminal(_ context.Context, terminal runner.Terminal) error {
470
+ r.closeCalls++
471
+ r.closedIDs = append(r.closedIDs, terminal.ID)
472
+ r.live = false
473
+ return nil
474
+ }
475
+ func (r *runtimeTestRunner) EnsureTerminal(ctx context.Context, env runner.Environment, stored runner.Terminal, title string, command runner.Command) (runner.Terminal, error) {
476
+ if terminal, ok, err := r.FindTerminal(ctx, stored); err != nil {
477
+ return runner.Terminal{}, err
478
+ } else if ok {
479
+ return terminal, nil
480
+ }
481
+ return r.CreateTerminal(ctx, env, title, command)
482
+ }
483
+ func (*runtimeTestRunner) CloseTerminals(context.Context, runner.RunSpec) error { return nil }
484
+ func (*runtimeTestRunner) CleanupRun(context.Context, runner.RunSpec) error { return nil }
485
+
486
+ type runtimeTestHarness struct {
487
+ buildCalls int
488
+ prompts []string
489
+ resumeIDs []string
490
+ }
491
+
492
+ func (*runtimeTestHarness) ValidateAgent(context.Context, string, string) error { return nil }
493
+ func (*runtimeTestHarness) FindSession(context.Context, string, string) (harness.Session, bool, error) {
494
+ return harness.Session{}, false, nil
495
+ }
496
+ func (h *runtimeTestHarness) BuildCommand(spec harness.LaunchSpec) (runner.Command, error) {
497
+ h.buildCalls++
498
+ h.prompts = append(h.prompts, spec.Prompt)
499
+ h.resumeIDs = append(h.resumeIDs, spec.ResumeID)
500
+ return runner.Command{Executable: "opencode", Args: []string{spec.ResumeID}}, nil
501
+ }
502
+
503
+ func openProjectionDB(t *testing.T, path string) *sql.DB {
504
+ t.Helper()
505
+ db, err := sql.Open("sqlite", path)
506
+ if err != nil {
507
+ t.Fatal(err)
508
+ }
509
+ return db
510
+ }