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
@@ -1,81 +1,71 @@
1
- // Package runner defines the execution-backend plug point. Orca ships
2
- // built in (internal/runner/orca); tmux or others register the same way.
3
- // A Runner knows how to spawn agent sessions, re-find them (bounce),
4
- // nudge them, and tear them down — nothing about trackers.
1
+ // Package runner defines the runner contract: workspaces/environments,
2
+ // terminals, liveness, and process handles. The runner does not know
3
+ // task-system fields, workflow routes, report contents, or agent command
4
+ // syntax.
5
5
  package runner
6
6
 
7
7
  import (
8
- "fmt"
9
- "sort"
10
- "sync"
8
+ "context"
9
+ "errors"
11
10
 
12
- "github.com/rajpopat27/relay-flow/internal/tasks"
11
+ "github.com/rajpopat27/relay-flow/internal/identity"
13
12
  )
14
13
 
15
- // Session is a live agent terminal/process handle.
16
- type Session struct {
17
- ID string
18
- Title string
19
- }
14
+ var ErrSessionUnavailable = errors.New("stored session unavailable")
20
15
 
21
- // Runner is the execution-backend interface.
22
- type Runner interface {
23
- // Spawn creates (or ensures) the ticket's worktree/session titled
24
- // "<key>:<agent>:<node>", injects env, and sends the initial prompt.
25
- Spawn(t tasks.Ticket, node, agent, prompt string, env map[string]string) error
26
- // Find locates the existing session for this ticket+node (bounce).
27
- Find(t tasks.Ticket, node string) (Session, bool, error)
28
- // Nudge sends a prompt into an existing session.
29
- Nudge(s Session, prompt string) error
30
- // Close tears down all of the ticket's sessions (terminal node).
31
- Close(t tasks.Ticket) error
16
+ const (
17
+ WorkspaceStatusInProgress = "in-progress"
18
+ WorkspaceStatusInReview = "in-review"
19
+ WorkspaceStatusCompleted = "completed"
20
+ )
21
+
22
+ type RepoCandidate struct {
23
+ Name string `json:"name"`
24
+ Path string `json:"path"`
32
25
  }
33
26
 
34
- // Factory builds a runner instance. runner.config is decoded by
35
- // UnmarshalConfig (strict), then passed to New.
36
- type Factory struct {
37
- UnmarshalConfig func(map[string]any) (any, error)
38
- New func(cfg any) (Runner, error)
27
+ type Environment struct {
28
+ ID string `json:"id"`
29
+ Path string `json:"path"`
39
30
  }
40
31
 
41
- var (
42
- mu sync.RWMutex
43
- factories = map[string]Factory{}
44
- )
32
+ type Terminal struct {
33
+ ID string `json:"id"`
34
+ Title string `json:"title"`
35
+ }
45
36
 
46
- // Register makes a runner available under `type: <name>`. Panics on
47
- // duplicate registration (programmer error).
48
- func Register(name string, f Factory) {
49
- mu.Lock()
50
- defer mu.Unlock()
51
- if _, dup := factories[name]; dup {
52
- panic("runner: duplicate registration " + name)
53
- }
54
- factories[name] = f
37
+ type Command struct {
38
+ Executable string `json:"executable"`
39
+ Args []string `json:"args,omitempty"`
40
+ Env map[string]string `json:"env,omitempty"`
55
41
  }
56
42
 
57
- // New resolves a runner by type name and builds an instance.
58
- func New(typeName string, rawCfg map[string]any) (Runner, error) {
59
- mu.RLock()
60
- f, ok := factories[typeName]
61
- mu.RUnlock()
62
- if !ok {
63
- return nil, fmt.Errorf("unknown runner type %q (registered: %v)", typeName, registered())
64
- }
65
- cfg, err := f.UnmarshalConfig(rawCfg)
66
- if err != nil {
67
- return nil, fmt.Errorf("runner type %q config: %w", typeName, err)
68
- }
69
- return f.New(cfg)
43
+ type RunSpec struct {
44
+ RunID identity.RunID
45
+ RepoName string
46
+ RepoPath string
47
+ TicketKey string
70
48
  }
71
49
 
72
- func registered() []string {
73
- mu.RLock()
74
- defer mu.RUnlock()
75
- names := make([]string, 0, len(factories))
76
- for n := range factories {
77
- names = append(names, n)
78
- }
79
- sort.Strings(names)
80
- return names
50
+ // Runner owns ticket-scoped environments, terminals, and liveness.
51
+ // FindTerminal checks a persisted terminal handle against the external runner
52
+ // and returns only a live usable terminal. CloseTerminals closes agent terminals
53
+ // while preserving the environment/workspace; CleanupRun removes all
54
+ // runner-owned run resources at end. Both reconstruct identity from RunSpec
55
+ // without SQLite IDs.
56
+ //
57
+ // Terminal titles are stable and minimal: only "<ticket>:<node>" — never
58
+ // nodeVisitID, workflow name, agent name, or other changing metadata.
59
+ type Runner interface {
60
+ DiscoverRepos(ctx context.Context) ([]RepoCandidate, error)
61
+ ValidateRepo(ctx context.Context, name, path string) error
62
+ EnsureEnvironment(ctx context.Context, spec RunSpec) (Environment, error)
63
+ SetEnvironmentStatus(ctx context.Context, env Environment, status string) error
64
+ FindTerminal(ctx context.Context, terminal Terminal) (Terminal, bool, error)
65
+ CreateTerminal(ctx context.Context, env Environment, title string, command Command) (Terminal, error)
66
+ EnsureTerminal(ctx context.Context, env Environment, terminal Terminal, title string, command Command) (Terminal, error)
67
+ SendTerminal(ctx context.Context, terminal Terminal, text string) error
68
+ CloseTerminal(ctx context.Context, terminal Terminal) error
69
+ CloseTerminals(ctx context.Context, spec RunSpec) error
70
+ CleanupRun(ctx context.Context, spec RunSpec) error
81
71
  }
@@ -0,0 +1,300 @@
1
+ package server_test
2
+
3
+ import (
4
+ "bytes"
5
+ "encoding/json"
6
+ "io"
7
+ "net/http"
8
+ "testing"
9
+ "time"
10
+
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
+ // 3.35: server API per specs/workflow-repo-management "API responses and
17
+ // status codes are stable". Drives the real http.Handler (server.New) over
18
+ // in-process HTTP with fake services.
19
+
20
+ type envelope struct {
21
+ OK bool `json:"ok"`
22
+ Data json.RawMessage `json:"data"`
23
+ Error *struct {
24
+ Code string `json:"code"`
25
+ Message string `json:"message"`
26
+ } `json:"error"`
27
+ }
28
+
29
+ func do(t *testing.T, c *http.Client, method, url string, body []byte) (int, envelope) {
30
+ t.Helper()
31
+ var rdr io.Reader
32
+ if body != nil {
33
+ rdr = bytes.NewReader(body)
34
+ }
35
+ req, err := http.NewRequest(method, url, rdr)
36
+ if err != nil {
37
+ t.Fatal(err)
38
+ }
39
+ if body != nil {
40
+ req.Header.Set("Content-Type", "application/json")
41
+ }
42
+ resp, err := c.Do(req)
43
+ if err != nil {
44
+ t.Fatalf("%s %s failed: %v", method, url, err)
45
+ }
46
+ defer resp.Body.Close()
47
+ raw, _ := io.ReadAll(resp.Body)
48
+ var env envelope
49
+ if err := json.Unmarshal(raw, &env); err != nil {
50
+ t.Fatalf("response not a JSON envelope: %q", raw)
51
+ }
52
+ return resp.StatusCode, env
53
+ }
54
+
55
+ func TestSuccessEnvelope(t *testing.T) {
56
+ c, cleanup := startHandler(t, &fakeServices{})
57
+ defer cleanup()
58
+ code, env := do(t, c, http.MethodGet, "http://relay/workflows", nil)
59
+ if code != http.StatusOK || !env.OK {
60
+ t.Fatalf("GET /workflows: code=%d env=%+v, want 200 ok", code, env)
61
+ }
62
+ }
63
+
64
+ func TestErrorEnvelopeAndStatusMapping(t *testing.T) {
65
+ c, cleanup := startHandler(t, &fakeServices{})
66
+ defer cleanup()
67
+
68
+ // 400 malformed JSON: drive a JSON endpoint (POST /repos) with malformed
69
+ // input. POST /workflows takes raw YAML by design (docs routes).
70
+ code, env := do(t, c, http.MethodPost, "http://relay/repos", []byte("{not json"))
71
+ if code != http.StatusBadRequest || env.OK || env.Error == nil || env.Error.Code == "" || env.Error.Message == "" {
72
+ t.Fatalf("malformed input: code=%d env=%+v, want 400 + lowerCamel error envelope", code, env)
73
+ }
74
+ if !isLowerCamel(env.Error.Code) {
75
+ t.Fatalf("error code %q not lowerCamel", env.Error.Code)
76
+ }
77
+
78
+ // 404 missing resource.
79
+ code, env = do(t, c, http.MethodGet, "http://relay/workflows/ghost", nil)
80
+ if code != http.StatusNotFound || env.OK || env.Error == nil {
81
+ t.Fatalf("missing resource: code=%d env=%+v, want 404", code, env)
82
+ }
83
+
84
+ // 405 wrong method.
85
+ code, env = do(t, c, http.MethodPatch, "http://relay/workflows", []byte("{}"))
86
+ if code != http.StatusMethodNotAllowed || env.OK {
87
+ t.Fatalf("wrong method: code=%d env=%+v, want 405", code, env)
88
+ }
89
+ }
90
+
91
+ func TestWorkflowConflictMapsTo409(t *testing.T) {
92
+ // basicFlow is seeded with an active run, so replacement conflicts -> 409.
93
+ c, cleanup := startHandler(t, &fakeServices{activeWorkflows: map[string]bool{"basicFlow": true}})
94
+ defer cleanup()
95
+
96
+ yamlBody := "name: basicFlow\nrepos: [payments]\nnodes:\n start: {onSuccess: [{target: end}]}\n end: {}\n"
97
+ // POST /workflows body IS the raw YAML (docs routes; client sends raw).
98
+ code, env := do(t, c, http.MethodPost, "http://relay/workflows", []byte(yamlBody))
99
+ if code != http.StatusConflict {
100
+ t.Fatalf("replacement during active run: code=%d, want 409", code)
101
+ }
102
+ if env.OK || env.Error == nil || !isLowerCamel(env.Error.Code) || env.Error.Message == "" {
103
+ t.Fatalf("409 without standard error envelope: %+v", env)
104
+ }
105
+ }
106
+
107
+ func TestUnexpectedFailureMapsTo500(t *testing.T) {
108
+ c, cleanup := startHandler(t, &fakeServices{failRepos: true})
109
+ defer cleanup()
110
+ code, env := do(t, c, http.MethodGet, "http://relay/repos/any", nil)
111
+ if code != http.StatusInternalServerError || env.OK || env.Error == nil {
112
+ t.Fatalf("unexpected failure: code=%d env=%+v, want 500 + error envelope", code, env)
113
+ }
114
+ }
115
+
116
+ func TestReportEndpointAcceptsJSON(t *testing.T) {
117
+ c, cleanup := startHandler(t, &fakeServices{})
118
+ defer cleanup()
119
+ report := `{"runId":"payments/basicFlow/PAY-101","node":"coding","reportId":"session-1:message-1","report":{"status":"success","nextStep":"end","summary":{"completed":"x","commits":"abc123","notCompleted":"None","issuesDiscovered":"None","verification":"x","notes":"None"},"feedback":{"reasonForNextStep":"None","requiredActions":"None","relevantContext":"None","expectedResult":"None"}}}`
120
+ code, env := do(t, c, http.MethodPost, "http://relay/reports", []byte(report))
121
+ if code != http.StatusOK || !env.OK {
122
+ t.Fatalf("valid report: code=%d env=%+v, want 200 ok", code, env)
123
+ }
124
+ var ack struct {
125
+ Accepted bool `json:"accepted"`
126
+ Duplicate bool `json:"duplicate"`
127
+ }
128
+ if err := json.Unmarshal(env.Data, &ack); err != nil {
129
+ t.Fatalf("report ack data not the documented shape: %v", err)
130
+ }
131
+ }
132
+
133
+ func TestProcessedReportIDBypassesReportBodyValidation(t *testing.T) {
134
+ runID := "payments/basicFlow/PAY-101"
135
+ reportID := "session-1:message-1"
136
+ fake := &fakeServices{processedReports: map[string]bool{runID + ":" + reportID: true}}
137
+ c, cleanup := startHandler(t, fake)
138
+ defer cleanup()
139
+ body := []byte(`{"runId":"payments/basicFlow/PAY-101","node":"coding","reportId":"session-1:message-1","report":{"unknown":"ignored"}}`)
140
+ code, env := do(t, c, http.MethodPost, "http://relay/reports", body)
141
+ if code != http.StatusOK || !env.OK || !bytes.Contains(env.Data, []byte(`"duplicate":true`)) {
142
+ t.Fatalf("processed report: code=%d env=%+v, want duplicate ack", code, env)
143
+ }
144
+ if fake.submittedReports != 0 {
145
+ t.Fatalf("processed report reached SubmitReport %d times", fake.submittedReports)
146
+ }
147
+ }
148
+
149
+ func TestReportRejectsWrongWireKeyCasing(t *testing.T) {
150
+ c, cleanup := startHandler(t, &fakeServices{})
151
+ defer cleanup()
152
+ // runID/reportID (wrong casing) must be rejected by strict decoding.
153
+ bad := `{"runID":"payments/basicFlow/PAY-101","node":"coding","reportID":"session-1:message-1","report":{"status":"success","nextStep":"end","summary":{"completed":"x","commits":"abc123","notCompleted":"None","issuesDiscovered":"None","verification":"x","notes":"None"},"feedback":{"reasonForNextStep":"None","requiredActions":"None","relevantContext":"None","expectedResult":"None"}}}`
154
+ code, env := do(t, c, http.MethodPost, "http://relay/reports", []byte(bad))
155
+ if code != http.StatusBadRequest || env.OK {
156
+ t.Fatalf("wrong-cased wire keys: code=%d env=%+v, want 400 not ok", code, env)
157
+ }
158
+ }
159
+
160
+ func TestReportMultilineFieldsPreserved(t *testing.T) {
161
+ c, cleanup := startHandler(t, &fakeServices{})
162
+ defer cleanup()
163
+ // Multiline summary/feedback arrive as one JSON object, never as flags.
164
+ report := `{"runId":"payments/basicFlow/PAY-101","node":"coding","reportId":"session-1:message-1","report":{"status":"success","nextStep":"end","summary":{"completed":"line1\nline2\n- bullet","commits":"abc123","notCompleted":"None","issuesDiscovered":"None","verification":"ran ` + "`go test ./...`" + `","notes":"None"},"feedback":{"reasonForNextStep":"None","requiredActions":"None","relevantContext":"None","expectedResult":"None"}}}`
165
+ code, env := do(t, c, http.MethodPost, "http://relay/reports", []byte(report))
166
+ if code != http.StatusOK || !env.OK {
167
+ t.Fatalf("multiline report: code=%d env=%+v, want 200 ok", code, env)
168
+ }
169
+ }
170
+
171
+ func TestRuntimeSessionRegistrationEndpoint(t *testing.T) {
172
+ fake := &fakeServices{runtimeAck: run.NodeRuntimeRegistrationAck{Accepted: true}}
173
+ c, cleanup := startHandler(t, fake)
174
+ defer cleanup()
175
+ body := []byte(`{"runId":"payments/basic/PAY-101","node":"implement","sessionId":"session-1"}`)
176
+ code, env := do(t, c, http.MethodPost, "http://relay/runtime/session", body)
177
+ if code != http.StatusOK || !env.OK {
178
+ t.Fatalf("runtime registration: code=%d env=%+v", code, env)
179
+ }
180
+ if len(fake.registrations) != 1 || fake.registrations[0].SessionID != "session-1" {
181
+ t.Fatalf("registrations = %+v", fake.registrations)
182
+ }
183
+ if !bytes.Contains(env.Data, []byte(`"accepted":true`)) {
184
+ t.Fatalf("accepted ack missing: %s", env.Data)
185
+ }
186
+ }
187
+
188
+ func TestRepoAndRunEndpoints(t *testing.T) {
189
+ c, cleanup := startHandler(t, &fakeServices{})
190
+ defer cleanup()
191
+
192
+ // 200 repo list.
193
+ code, env := do(t, c, http.MethodGet, "http://relay/repos", nil)
194
+ if code != http.StatusOK || !env.OK {
195
+ t.Fatalf("GET /repos: code=%d env=%+v, want 200 ok", code, env)
196
+ }
197
+ // 404 missing repo.
198
+ code, env = do(t, c, http.MethodGet, "http://relay/repos/ghost", nil)
199
+ if code != http.StatusNotFound || env.OK {
200
+ t.Fatalf("GET /repos/ghost: code=%d, want 404", code)
201
+ }
202
+ // 200 run list.
203
+ code, env = do(t, c, http.MethodGet, "http://relay/runs", nil)
204
+ if code != http.StatusOK || !env.OK {
205
+ t.Fatalf("GET /runs: code=%d env=%+v, want 200 ok", code, env)
206
+ }
207
+ // 404 run by ticket.
208
+ code, env = do(t, c, http.MethodGet, "http://relay/runs/by-ticket/NOPE-1", nil)
209
+ if code != http.StatusNotFound || env.OK {
210
+ t.Fatalf("GET /runs/by-ticket/NOPE-1: code=%d, want 404", code)
211
+ }
212
+ }
213
+
214
+ func TestRunEndpointsExposeRetryDetails(t *testing.T) {
215
+ next := time.Now().UTC().Add(time.Minute)
216
+ retrying := run.Run{
217
+ ID: "payments/basicFlow/PAY-101", State: run.StateStarting,
218
+ Ticket: task.TicketRef{Key: "PAY-101"},
219
+ Retry: &run.RetryStatus{Attempt: 2, LastError: "jira unavailable", NextRetryAt: next},
220
+ }
221
+ c, cleanup := startHandler(t, &fakeServices{runs: []run.Run{retrying}})
222
+ defer cleanup()
223
+
224
+ for _, url := range []string{"http://relay/runs", "http://relay/runs/by-ticket/PAY-101"} {
225
+ code, env := do(t, c, http.MethodGet, url, nil)
226
+ if code != http.StatusOK || !env.OK {
227
+ t.Fatalf("GET %s: code=%d env=%+v", url, code, env)
228
+ }
229
+ if !bytes.Contains(env.Data, []byte(`"state":"starting"`)) ||
230
+ !bytes.Contains(env.Data, []byte(`"retry":{"attempt":2,"lastError":"jira unavailable","nextRetryAt":`)) {
231
+ t.Fatalf("GET %s omitted lifecycle/retry details: %s", url, env.Data)
232
+ }
233
+ }
234
+ }
235
+
236
+ func TestRepoOperations(t *testing.T) {
237
+ c, cleanup := startHandler(t, &fakeServices{})
238
+ defer cleanup()
239
+
240
+ // Discover returns candidates (200). Route is GET per docs.
241
+ code, env := do(t, c, http.MethodGet, "http://relay/repos/discover", nil)
242
+ if code != http.StatusOK || !env.OK {
243
+ t.Fatalf("POST /repos/discover: code=%d env=%+v, want 200 ok", code, env)
244
+ }
245
+ // Register a repo (200), then get it (200).
246
+ code, env = do(t, c, http.MethodPost, "http://relay/repos", []byte(`{"name":"payments","path":"/srv/payments"}`))
247
+ if code != http.StatusOK && code != http.StatusCreated {
248
+ t.Fatalf("POST /repos: code=%d env=%+v, want 200/201", code, env)
249
+ }
250
+ code, env = do(t, c, http.MethodGet, "http://relay/repos/payments", nil)
251
+ if code != http.StatusOK || !env.OK {
252
+ t.Fatalf("GET /repos/payments: code=%d env=%+v, want 200 ok", code, env)
253
+ }
254
+ // Remove it (200).
255
+ code, env = do(t, c, http.MethodDelete, "http://relay/repos/payments", nil)
256
+ if code != http.StatusOK || !env.OK {
257
+ t.Fatalf("DELETE /repos/payments: code=%d env=%+v, want 200 ok", code, env)
258
+ }
259
+ }
260
+
261
+ func TestWorkflowGetRemoveAndRunCancel(t *testing.T) {
262
+ fake := &fakeServices{workflows: map[string]*workflow.Workflow{}, activeWorkflows: map[string]bool{}, runs: []run.Run{
263
+ {ID: "payments/basicFlow/PAY-101", State: run.StateRunning, Ticket: task.TicketRef{Key: "PAY-101"}},
264
+ }}
265
+ c, cleanup := startHandler(t, fake)
266
+ defer cleanup()
267
+
268
+ // Submit then GET a workflow (200).
269
+ wfYAML := "name: basicFlow\nrepos: [payments]\nnodes:\n start: {onSuccess: [{target: coding}]}\n coding: {type: agent, agent: build, description: work, onSuccess: [{target: end}], onFailure: [{target: coding}]}\n end: {}\n"
270
+ code, _ := do(t, c, http.MethodPost, "http://relay/workflows", []byte(wfYAML))
271
+ if code != http.StatusOK && code != http.StatusCreated {
272
+ t.Fatalf("POST /workflows: code=%d, want 200/201", code)
273
+ }
274
+ code, env := do(t, c, http.MethodGet, "http://relay/workflows/basicFlow", nil)
275
+ if code != http.StatusOK || !env.OK {
276
+ t.Fatalf("GET /workflows/basicFlow: code=%d env=%+v, want 200 ok", code, env)
277
+ }
278
+ // Cancel the run by ticket (200), then remove the workflow (200).
279
+ // Route is /runs/by-ticket/{key}/cancel per docs.
280
+ code, env = do(t, c, http.MethodPost, "http://relay/runs/by-ticket/PAY-101/cancel", []byte(`{"reason":"done"}`))
281
+ if code != http.StatusOK || !env.OK {
282
+ t.Fatalf("POST /runs/PAY-101/cancel: code=%d env=%+v, want 200 ok", code, env)
283
+ }
284
+ code, env = do(t, c, http.MethodDelete, "http://relay/workflows/basicFlow", nil)
285
+ if code != http.StatusOK || !env.OK {
286
+ t.Fatalf("DELETE /workflows/basicFlow: code=%d env=%+v, want 200 ok", code, env)
287
+ }
288
+ }
289
+
290
+ func isLowerCamel(s string) bool {
291
+ if s == "" || s[0] < 'a' || s[0] > 'z' {
292
+ return false
293
+ }
294
+ for _, r := range s {
295
+ if r == '_' || r == '-' || r == ' ' {
296
+ return false
297
+ }
298
+ }
299
+ return true
300
+ }