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,84 @@
1
+ // Package router is the pure Ticket Router. It has no Jira, SQLite, runner,
2
+ // or goroutine dependency.
3
+ package router
4
+
5
+ import (
6
+ "errors"
7
+ "fmt"
8
+ "sort"
9
+ "strings"
10
+
11
+ "github.com/rajpopat27/relay-flow/internal/repo"
12
+ "github.com/rajpopat27/relay-flow/internal/task"
13
+ "github.com/rajpopat27/relay-flow/internal/workflow"
14
+ )
15
+
16
+ // ErrNoMatch means an unclaimed ticket matches no workflow filter; the
17
+ // polling handler ignores it.
18
+ var ErrNoMatch = errors.New("ticket matches no workflow")
19
+
20
+ // AmbiguousError means an unclaimed ticket matches more than one workflow.
21
+ // No ticket mutation occurs.
22
+ type AmbiguousError struct {
23
+ Ticket string
24
+ Workflows []string
25
+ }
26
+
27
+ func (e *AmbiguousError) Error() string {
28
+ return fmt.Sprintf("ticket %s matches multiple workflows: %s", e.Ticket, strings.Join(e.Workflows, ", "))
29
+ }
30
+
31
+ // InvalidClaimError means the ticket carries several workflow claims, or a
32
+ // claim naming an unknown workflow or one not registered for the repo.
33
+ type InvalidClaimError struct {
34
+ Ticket string
35
+ Workflow string
36
+ Repo string
37
+ }
38
+
39
+ func (e *InvalidClaimError) Error() string {
40
+ return fmt.Sprintf("ticket %s has invalid workflow claim %q for repo %s", e.Ticket, e.Workflow, e.Repo)
41
+ }
42
+
43
+ const claimPrefix = "wf:"
44
+
45
+ // ResolveWorkflow routes a ticket to exactly one workflow following the
46
+ // deterministic routing order: multiple claims are invalid; a single claim
47
+ // resolves directly from repo bindings without re-running filters; an
48
+ // unknown or unbound claim is invalid; otherwise precompiled matchers run —
49
+ // zero matches is ErrNoMatch, one match wins, several is ambiguous.
50
+ func ResolveWorkflow(registered *repo.Repo, ticket task.Ticket) (*workflow.Workflow, error) {
51
+ claims := ticket.WorkflowClaims
52
+ if len(claims) > 1 {
53
+ return nil, &InvalidClaimError{Ticket: ticket.Key, Workflow: strings.Join(claims, ","), Repo: registered.Name}
54
+ }
55
+ bindings := registered.Bindings()
56
+ if len(claims) == 1 {
57
+ name := strings.TrimPrefix(claims[0], claimPrefix)
58
+ for _, b := range bindings {
59
+ if b.Workflow.Name == name {
60
+ return b.Workflow, nil
61
+ }
62
+ }
63
+ return nil, &InvalidClaimError{Ticket: ticket.Key, Workflow: name, Repo: registered.Name}
64
+ }
65
+ var matched []*workflow.Workflow
66
+ for _, b := range bindings {
67
+ if b.Match != nil && b.Match(ticket) {
68
+ matched = append(matched, b.Workflow)
69
+ }
70
+ }
71
+ switch len(matched) {
72
+ case 0:
73
+ return nil, ErrNoMatch
74
+ case 1:
75
+ return matched[0], nil
76
+ default:
77
+ names := make([]string, 0, len(matched))
78
+ for _, wf := range matched {
79
+ names = append(names, wf.Name)
80
+ }
81
+ sort.Strings(names)
82
+ return nil, &AmbiguousError{Ticket: ticket.Key, Workflows: names}
83
+ }
84
+ }
@@ -0,0 +1,231 @@
1
+ package router_test
2
+
3
+ import (
4
+ "context"
5
+ "errors"
6
+ "fmt"
7
+ "sync/atomic"
8
+ "testing"
9
+ "time"
10
+
11
+ "github.com/rajpopat27/relay-flow/internal/config"
12
+ "github.com/rajpopat27/relay-flow/internal/repo"
13
+ "github.com/rajpopat27/relay-flow/internal/router"
14
+ "github.com/rajpopat27/relay-flow/internal/task"
15
+ "github.com/rajpopat27/relay-flow/internal/workflow"
16
+ )
17
+
18
+ // 3.11: Ticket Router tests (pure) per specs/repo-workflow-routing
19
+ // "Existing workflow claims take precedence" and "Unclaimed routing is
20
+ // unambiguous", following design decision 6's exact routing order.
21
+
22
+ func wf(name string) *workflow.Workflow {
23
+ return &workflow.Workflow{
24
+ Name: name,
25
+ Repos: []string{"payments"},
26
+ Nodes: map[string]workflow.Node{
27
+ "start": {OnSuccess: []workflow.Route{{Target: "coding"}}},
28
+ "coding": {
29
+ Type: workflow.NodeAgent, Agent: "build", Description: "work",
30
+ OnSuccess: []workflow.Route{{Target: "end"}},
31
+ OnFailure: []workflow.Route{{Target: "coding"}},
32
+ },
33
+ "end": {},
34
+ },
35
+ }
36
+ }
37
+
38
+ func binding(w *workflow.Workflow, match func(task.Ticket) bool) repo.WorkflowBinding {
39
+ return repo.WorkflowBinding{Workflow: w, Match: match}
40
+ }
41
+
42
+ func repoWith(bindings ...repo.WorkflowBinding) *repo.Repo {
43
+ return &repo.Repo{Name: "payments", Path: "/srv/payments", Workflows: bindings}
44
+ }
45
+
46
+ func TestMultipleClaimsInvalid(t *testing.T) {
47
+ r := repoWith(binding(wf("aFlow"), nil), binding(wf("bFlow"), nil))
48
+ ticket := task.Ticket{Key: "PAY-101", WorkflowClaims: []string{"wf:aFlow", "wf:bFlow"}}
49
+
50
+ _, err := router.ResolveWorkflow(r, ticket)
51
+ var ice *router.InvalidClaimError
52
+ if !errors.As(err, &ice) {
53
+ t.Fatalf("err = %v, want InvalidClaimError", err)
54
+ }
55
+ }
56
+
57
+ func TestSingleClaimResolvesDirectly(t *testing.T) {
58
+ // Filters must NOT be re-run for a claimed ticket: the matcher would
59
+ // reject this ticket, and the claim still wins.
60
+ matchCalled := false
61
+ r := repoWith(binding(wf("basicFlow"), func(task.Ticket) bool {
62
+ matchCalled = true
63
+ return false
64
+ }))
65
+ ticket := task.Ticket{Key: "PAY-101", WorkflowClaims: []string{"wf:basicFlow"}}
66
+
67
+ got, err := router.ResolveWorkflow(r, ticket)
68
+ if err != nil {
69
+ t.Fatalf("ResolveWorkflow failed: %v", err)
70
+ }
71
+ if got.Name != "basicFlow" {
72
+ t.Fatalf("resolved %q, want basicFlow", got.Name)
73
+ }
74
+ if matchCalled {
75
+ t.Fatal("matcher re-evaluated for a singly claimed ticket; claim resolves directly")
76
+ }
77
+ }
78
+
79
+ func TestUnknownClaimInvalid(t *testing.T) {
80
+ r := repoWith(binding(wf("basicFlow"), nil))
81
+ ticket := task.Ticket{Key: "PAY-101", WorkflowClaims: []string{"wf:ghost"}}
82
+
83
+ _, err := router.ResolveWorkflow(r, ticket)
84
+ var ice *router.InvalidClaimError
85
+ if !errors.As(err, &ice) {
86
+ t.Fatalf("err = %v, want InvalidClaimError for unknown claim", err)
87
+ }
88
+ }
89
+
90
+ func TestClaimForWorkflowNotBoundToRepo(t *testing.T) {
91
+ // otherFlow exists but targets another repo, so it is not in this
92
+ // repo's bindings.
93
+ r := repoWith(binding(wf("basicFlow"), nil))
94
+ ticket := task.Ticket{Key: "PAY-101", WorkflowClaims: []string{"wf:otherFlow"}}
95
+
96
+ _, err := router.ResolveWorkflow(r, ticket)
97
+ var ice *router.InvalidClaimError
98
+ if !errors.As(err, &ice) {
99
+ t.Fatalf("err = %v, want InvalidClaimError for unbound claim", err)
100
+ }
101
+ }
102
+
103
+ func TestZeroMatchesIgnored(t *testing.T) {
104
+ r := repoWith(binding(wf("basicFlow"), func(task.Ticket) bool { return false }))
105
+ ticket := task.Ticket{Key: "PAY-101"}
106
+
107
+ _, err := router.ResolveWorkflow(r, ticket)
108
+ if !errors.Is(err, router.ErrNoMatch) {
109
+ t.Fatalf("err = %v, want ErrNoMatch", err)
110
+ }
111
+ }
112
+
113
+ func TestOneMatchSelected(t *testing.T) {
114
+ r := repoWith(
115
+ binding(wf("basicFlow"), func(task.Ticket) bool { return true }),
116
+ binding(wf("otherFlow"), func(task.Ticket) bool { return false }),
117
+ )
118
+ ticket := task.Ticket{Key: "PAY-101"}
119
+
120
+ got, err := router.ResolveWorkflow(r, ticket)
121
+ if err != nil {
122
+ t.Fatalf("ResolveWorkflow failed: %v", err)
123
+ }
124
+ if got.Name != "basicFlow" {
125
+ t.Fatalf("resolved %q, want basicFlow", got.Name)
126
+ }
127
+ }
128
+
129
+ func TestMultipleMatchesAmbiguous(t *testing.T) {
130
+ r := repoWith(
131
+ binding(wf("basicFlow"), func(task.Ticket) bool { return true }),
132
+ binding(wf("otherFlow"), func(task.Ticket) bool { return true }),
133
+ )
134
+ ticket := task.Ticket{Key: "PAY-101", WorkflowClaims: nil}
135
+
136
+ before := ticket
137
+ _, err := router.ResolveWorkflow(r, ticket)
138
+ var amb *router.AmbiguousError
139
+ if !errors.As(err, &amb) {
140
+ t.Fatalf("err = %v, want AmbiguousError", err)
141
+ }
142
+ if len(amb.Workflows) != 2 {
143
+ t.Fatalf("AmbiguousError.Workflows = %v, want both workflows", amb.Workflows)
144
+ }
145
+ // No mutation on ambiguity.
146
+ if ticket.WorkflowClaims != nil || ticket.Key != before.Key {
147
+ t.Fatalf("ticket mutated on ambiguity: %+v", ticket)
148
+ }
149
+ }
150
+
151
+ type routingTaskSystem struct{ task.System }
152
+
153
+ func (routingTaskSystem) Poll(context.Context) ([]task.Ticket, error) {
154
+ return []task.Ticket{{Key: "PAY-101"}}, nil
155
+ }
156
+
157
+ func (routingTaskSystem) CompileFilter(config.RawValues) (func(task.Ticket) bool, error) {
158
+ return func(task.Ticket) bool { return true }, nil
159
+ }
160
+
161
+ func TestPollerRoutesWhileBindingsAreReplaced(t *testing.T) {
162
+ registry := repo.NewRegistry()
163
+ registered := &repo.Repo{Name: "payments", TaskSystem: routingTaskSystem{}}
164
+ registry.Replace(registered)
165
+
166
+ first, second := wf("firstFlow"), wf("secondFlow")
167
+ if err := registry.BindWorkflows([]*workflow.Workflow{first}); err != nil {
168
+ t.Fatal(err)
169
+ }
170
+
171
+ var routed atomic.Int64
172
+ failures := make(chan error, 1)
173
+ poller := &repo.RepoPoller{
174
+ Repo: registered,
175
+ Interval: time.Microsecond,
176
+ Handle: func(_ context.Context, registered *repo.Repo, tickets []task.Ticket) {
177
+ for _, ticket := range tickets {
178
+ resolved, err := router.ResolveWorkflow(registered, ticket)
179
+ if err != nil {
180
+ select {
181
+ case failures <- err:
182
+ default:
183
+ }
184
+ continue
185
+ }
186
+ if resolved != first && resolved != second {
187
+ select {
188
+ case failures <- fmt.Errorf("resolved unexpected workflow %q", resolved.Name):
189
+ default:
190
+ }
191
+ }
192
+ routed.Add(1)
193
+ }
194
+ },
195
+ }
196
+
197
+ ctx, cancel := context.WithCancel(context.Background())
198
+ done := make(chan struct{})
199
+ go func() {
200
+ poller.Run(ctx)
201
+ close(done)
202
+ }()
203
+
204
+ for i := 0; i < 1_000; i++ {
205
+ bindings := []*workflow.Workflow{first}
206
+ if i%2 == 1 {
207
+ bindings = []*workflow.Workflow{second}
208
+ }
209
+ if err := registry.BindWorkflows(bindings); err != nil {
210
+ cancel()
211
+ <-done
212
+ t.Fatal(err)
213
+ }
214
+ }
215
+
216
+ deadline := time.Now().Add(time.Second)
217
+ for routed.Load() == 0 && time.Now().Before(deadline) {
218
+ time.Sleep(time.Millisecond)
219
+ }
220
+ cancel()
221
+ <-done
222
+
223
+ select {
224
+ case err := <-failures:
225
+ t.Fatalf("routing during binding replacement failed: %v", err)
226
+ default:
227
+ }
228
+ if routed.Load() == 0 {
229
+ t.Fatal("poller did not route while bindings were replaced")
230
+ }
231
+ }
@@ -0,0 +1,121 @@
1
+ package run
2
+
3
+ import (
4
+ "context"
5
+ "fmt"
6
+ "log/slog"
7
+ "sync"
8
+
9
+ "github.com/rajpopat27/relay-flow/internal/identity"
10
+ "github.com/rajpopat27/relay-flow/internal/repo"
11
+ "github.com/rajpopat27/relay-flow/internal/task"
12
+ "github.com/rajpopat27/relay-flow/internal/workflow"
13
+ )
14
+
15
+ // CancellationMarker is the stable parent comment marker recording that the
16
+ // run was canceled; a missing claimed run carrying it is never recreated.
17
+ func CancellationMarker(id ID) string {
18
+ return string(id) + ":cancellation"
19
+ }
20
+
21
+ // RunManager performs only assignment and durable-run creation.
22
+ type RunManager struct {
23
+ Executor Executor
24
+ Runs RunQueries
25
+ // Gate, when non-nil, is the lifecycle mutex shared with
26
+ // workflow.Service.Submit/Remove (design.md decision 23): run creation
27
+ // holds it from final workflow resolution through claim + EnsureRun so
28
+ // a run never starts against a workflow definition that is concurrently
29
+ // being replaced or removed. A plain *sync.Mutex — no lock service.
30
+ Gate *sync.Mutex
31
+ }
32
+
33
+ // EnsureRun claims the ticket if unassigned, skips claiming when the ticket
34
+ // is already assigned to this workflow, checks the stable cancellation
35
+ // marker before recreating a missing claimed run, then ensures the durable
36
+ // run with a value snapshot of the workflow.
37
+ func (m *RunManager) EnsureRun(ctx context.Context, rp *repo.Repo, wf *workflow.Workflow, ticket task.Ticket) error {
38
+ if m.Gate != nil {
39
+ m.Gate.Lock()
40
+ defer m.Gate.Unlock()
41
+ }
42
+ id := identity.NewRunID(rp.Name, wf.Name, ticket.Key)
43
+ claimed := false
44
+ for _, c := range ticket.WorkflowClaims {
45
+ if c == "wf:"+wf.Name {
46
+ claimed = true
47
+ break
48
+ }
49
+ }
50
+ existingRun := false
51
+ if claimed && m.Runs != nil {
52
+ existing, err := m.Runs.ListRuns(ctx, Filter{Repo: rp.Name, Workflow: wf.Name, Ticket: ticket.Key})
53
+ if err != nil {
54
+ return fmt.Errorf("check existing run %s: %w", id, err)
55
+ }
56
+ for _, candidate := range existing {
57
+ if candidate.ID == id {
58
+ existingRun = true
59
+ break
60
+ }
61
+ }
62
+ }
63
+ if !claimed {
64
+ if err := rp.TaskSystem.Claim(ctx, ticket.Ref(), wf.Name); err != nil {
65
+ slog.Info("ensure-run outcome",
66
+ "ticket", ticket.Key, "repo", rp.Name, "workflow", wf.Name, "runID", string(id),
67
+ "outcome", "error", "stage", "claim", "error", err)
68
+ return fmt.Errorf("claim %s for workflow %s: %w", ticket.Key, wf.Name, err)
69
+ }
70
+ } else if !existingRun {
71
+ // Claimed but possibly missing its run (claim-before-run crash gap or
72
+ // retention cleanup): never recreate a canceled run.
73
+ marked, err := rp.TaskSystem.HasComment(ctx, task.Target{Parent: ticket.Ref()}, CancellationMarker(id))
74
+ if err != nil {
75
+ slog.Info("ensure-run outcome",
76
+ "ticket", ticket.Key, "repo", rp.Name, "workflow", wf.Name, "runID", string(id),
77
+ "outcome", "error", "stage", "cancellation-marker", "error", err)
78
+ return fmt.Errorf("check cancellation marker on %s: %w", ticket.Key, err)
79
+ }
80
+ if marked {
81
+ slog.Info("ensure-run outcome",
82
+ "ticket", ticket.Key, "repo", rp.Name, "workflow", wf.Name, "runID", string(id),
83
+ "outcome", "skipped-cancellation-marker")
84
+ return nil
85
+ }
86
+ }
87
+ created, err := m.Executor.EnsureRun(ctx, Start{
88
+ ID: id,
89
+ Repo: rp.Name,
90
+ RepoPath: rp.Path,
91
+ Workflow: *wf,
92
+ Ticket: ticket.Ref(),
93
+ })
94
+ if err != nil {
95
+ slog.Info("ensure-run outcome",
96
+ "ticket", ticket.Key, "repo", rp.Name, "workflow", wf.Name, "runID", string(id),
97
+ "outcome", "error", "stage", "executor", "error", err)
98
+ return fmt.Errorf("ensure run %s: %w", id, err)
99
+ }
100
+ outcome := "exists"
101
+ if created {
102
+ outcome = "created"
103
+ }
104
+ slog.Info("ensure-run outcome",
105
+ "ticket", ticket.Key, "repo", rp.Name, "workflow", wf.Name, "runID", string(id),
106
+ "outcome", outcome)
107
+ return nil
108
+ }
109
+
110
+ // CancelByTicket resolves the active run through FindRunByTicket, then
111
+ // calls Executor.CancelRun.
112
+ func (m *RunManager) CancelByTicket(ctx context.Context, ticket, reason string) error {
113
+ r, err := m.Runs.FindRunByTicket(ctx, ticket)
114
+ if err != nil {
115
+ return fmt.Errorf("find run for ticket %s: %w", ticket, err)
116
+ }
117
+ if err := m.Executor.CancelRun(ctx, r.ID, reason); err != nil {
118
+ return fmt.Errorf("cancel run %s: %w", r.ID, err)
119
+ }
120
+ return nil
121
+ }
@@ -0,0 +1,140 @@
1
+ // Package run defines run IDs/state, orchestration values, the durable
2
+ // Executor boundary, run queries, and the Run Manager.
3
+ package run
4
+
5
+ import (
6
+ "context"
7
+ "time"
8
+
9
+ "github.com/rajpopat27/relay-flow/internal/config"
10
+ "github.com/rajpopat27/relay-flow/internal/identity"
11
+ "github.com/rajpopat27/relay-flow/internal/task"
12
+ "github.com/rajpopat27/relay-flow/internal/workflow"
13
+ )
14
+
15
+ type ID = identity.RunID
16
+ type NodeVisitID = identity.NodeVisitID
17
+
18
+ type State string
19
+
20
+ const (
21
+ StateStarting State = "starting"
22
+ StateRunning State = "running"
23
+ StateWaiting State = "waiting"
24
+ StateBlocked State = "blocked"
25
+ StateCompleted State = "completed"
26
+ StateCanceling State = "canceling"
27
+ StateCanceled State = "canceled"
28
+ )
29
+
30
+ // Start carries the immutable value snapshot of the accepted workflow for
31
+ // deterministic replay. The interpreter consumes only this snapshot.
32
+ type Start struct {
33
+ ID ID `json:"id"`
34
+ Repo string `json:"repo"`
35
+ RepoPath string `json:"repoPath"`
36
+ Workflow workflow.Workflow `json:"workflow"`
37
+ Ticket task.TicketRef `json:"ticket"`
38
+ Runtime RuntimePolicy `json:"runtime"`
39
+ }
40
+
41
+ type RuntimePolicy struct {
42
+ KeepTerminalsAlive bool `json:"keepTerminalsAlive"`
43
+ KeepSessionsAlive bool `json:"keepSessionsAlive"`
44
+ }
45
+
46
+ type Work struct {
47
+ RunID ID
48
+ Repo string
49
+ Workflow string
50
+ Parent task.TicketRef
51
+ WorkflowTaskConfig config.RawValues
52
+ Runtime RuntimePolicy
53
+ }
54
+
55
+ type NodeWork struct {
56
+ Work
57
+ Node string
58
+ NodeVisitID NodeVisitID
59
+ Mailbox task.Mailbox
60
+ NodeTaskConfig config.RawValues
61
+ }
62
+
63
+ type CommentWork struct {
64
+ // RunID is the enclosing durable run; the comment activity uses it to
65
+ // attribute its 9.3 transition log lines (ticket/runID/node attrs).
66
+ RunID ID
67
+ Item task.Target
68
+ Body string
69
+ Marker string
70
+ }
71
+
72
+ // RetryStatus describes the currently pending durable activity retry without
73
+ // replacing the run's lifecycle state.
74
+ type RetryStatus struct {
75
+ Attempt int `json:"attempt"`
76
+ LastError string `json:"lastError"`
77
+ NextRetryAt time.Time `json:"nextRetryAt"`
78
+ }
79
+
80
+ type Run struct {
81
+ ID ID `json:"id"`
82
+ Repo string `json:"repo"`
83
+ Workflow string `json:"workflow"`
84
+ Ticket task.TicketRef `json:"ticket"`
85
+ State State `json:"state"`
86
+ CurrentNode string `json:"currentNode,omitempty"`
87
+ CurrentNodeVisitID NodeVisitID `json:"currentNodeVisitId,omitempty"`
88
+ LastError string `json:"lastError,omitempty"`
89
+ Retry *RetryStatus `json:"retry,omitempty"`
90
+ StartedAt time.Time `json:"startedAt"`
91
+ UpdatedAt time.Time `json:"updatedAt"`
92
+ FinishedAt *time.Time `json:"finishedAt,omitempty"`
93
+ }
94
+
95
+ type ReportRequest struct {
96
+ RunID ID `json:"runId"`
97
+ Node string `json:"node"`
98
+ ReportID string `json:"reportId"`
99
+ Report workflow.Report `json:"report"`
100
+ }
101
+
102
+ type ReportAck struct {
103
+ Accepted bool `json:"accepted"`
104
+ Duplicate bool `json:"duplicate"`
105
+ }
106
+
107
+ // NodeRuntimeRegistration binds the OpenCode session emitted for one run/node.
108
+ type NodeRuntimeRegistration struct {
109
+ RunID ID `json:"runId"`
110
+ Node string `json:"node"`
111
+ SessionID string `json:"sessionId"`
112
+ }
113
+
114
+ type NodeRuntimeRegistrationAck struct {
115
+ Accepted bool `json:"accepted"`
116
+ }
117
+
118
+ type Filter struct {
119
+ Repo string
120
+ Workflow string
121
+ Ticket string
122
+ Active *bool
123
+ }
124
+
125
+ // Executor is the replacement boundary for go-workflows, Temporal, or
126
+ // another durable engine. No go-workflows context, instance, backend,
127
+ // queue, or error crosses this interface.
128
+ type Executor interface {
129
+ EnsureRun(ctx context.Context, start Start) (created bool, err error)
130
+ SubmitReport(ctx context.Context, report ReportRequest) (ReportAck, error)
131
+ CancelRun(ctx context.Context, id ID, reason string) error
132
+ }
133
+
134
+ type RunQueries interface {
135
+ GetRun(ctx context.Context, id ID) (Run, error)
136
+ FindRunByTicket(ctx context.Context, ticket string) (Run, error)
137
+ ListRuns(ctx context.Context, filter Filter) ([]Run, error)
138
+ HasActiveWorkflow(ctx context.Context, workflow string) (bool, error)
139
+ HasActiveRepo(ctx context.Context, repo string) (bool, error)
140
+ }
@@ -0,0 +1,52 @@
1
+ package run_test
2
+
3
+ import (
4
+ "testing"
5
+
6
+ "github.com/rajpopat27/relay-flow/internal/identity"
7
+ "github.com/rajpopat27/relay-flow/internal/run"
8
+ )
9
+
10
+ // 3.14: run identity per specs/durable-run-execution "Each parent ticket
11
+ // has one durable run" and "Every node entry has a distinct visit identity".
12
+
13
+ func TestRunIDDeterministic(t *testing.T) {
14
+ a := identity.NewRunID("payments", "basicFlow", "PAY-101")
15
+ b := identity.NewRunID("payments", "basicFlow", "PAY-101")
16
+ if a != b {
17
+ t.Fatalf("run ID not deterministic: %q vs %q", a, b)
18
+ }
19
+ c := identity.NewRunID("payments", "basicFlow", "PAY-102")
20
+ if a == c {
21
+ t.Fatal("different tickets produced the same run ID")
22
+ }
23
+ d := identity.NewRunID("other", "basicFlow", "PAY-101")
24
+ if a == d {
25
+ t.Fatal("different repos produced the same run ID")
26
+ }
27
+ }
28
+
29
+ func TestRunIDDelimiterSafe(t *testing.T) {
30
+ // Components containing delimiters must not collide.
31
+ a := identity.NewRunID("pay/ments", "basicFlow", "PAY-101")
32
+ b := identity.NewRunID("pay", "ments/basicFlow", "PAY-101")
33
+ if a == b {
34
+ t.Fatalf("delimiter collision: %q == %q", a, b)
35
+ }
36
+ }
37
+
38
+ func TestNodeVisitIDsUniquePerEntry(t *testing.T) {
39
+ first := identity.NewNodeVisitID()
40
+ second := identity.NewNodeVisitID()
41
+ if first == second {
42
+ t.Fatal("two node entries generated the same nodeVisitID")
43
+ }
44
+ }
45
+
46
+ // EnsureRun idempotence is covered with the RunManager tests (3.12) using a
47
+ // fake executor: a repeated EnsureRun with the same deterministic ID
48
+ // returns the existing run without restarting. The durable side-effect
49
+ // stability of nodeVisitID across replay is an engine-level behavior tested
50
+ // in internal/execution/goworkflows.
51
+
52
+ var _ = run.ID("")