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,520 @@
1
+ // Package goworkflows is the durable execution engine: one generic
2
+ // TicketWorkflow interpreter over go-workflows with a SQLite backend, the
3
+ // relay_runs projection, typed activity retry loops, and signal-based report
4
+ // handling. All go-workflows types stay inside this package.
5
+ package goworkflows
6
+
7
+ import (
8
+ "context"
9
+ "database/sql"
10
+ "errors"
11
+ "fmt"
12
+ "log/slog"
13
+ "os"
14
+ "sync"
15
+ "time"
16
+
17
+ "github.com/cschleiden/go-workflows/backend"
18
+ "github.com/cschleiden/go-workflows/backend/converter"
19
+ "github.com/cschleiden/go-workflows/backend/history"
20
+ "github.com/cschleiden/go-workflows/backend/sqlite"
21
+ "github.com/cschleiden/go-workflows/client"
22
+ "github.com/cschleiden/go-workflows/worker"
23
+ goworkflow "github.com/cschleiden/go-workflows/workflow"
24
+ "github.com/google/uuid"
25
+
26
+ "github.com/rajpopat27/relay-flow/internal/harness"
27
+ "github.com/rajpopat27/relay-flow/internal/repo"
28
+ "github.com/rajpopat27/relay-flow/internal/run"
29
+ "github.com/rajpopat27/relay-flow/internal/runner"
30
+ "github.com/rajpopat27/relay-flow/internal/workflow"
31
+ )
32
+
33
+ // Dependencies carries the replaceable boundaries used by activities.
34
+ type Dependencies struct {
35
+ Repos *repo.Registry
36
+ Runner runner.Runner
37
+ Harness harness.Harness
38
+ TaskSystem string
39
+
40
+ // RetentionDays bounds completed/canceled run retention; zero uses the
41
+ // machine default of 30 days.
42
+ RetentionDays int
43
+ // Runtime is copied into every new run's immutable durable snapshot. Nil
44
+ // applies machine defaults (terminals true, sessions true).
45
+ Runtime *run.RuntimePolicy
46
+ }
47
+
48
+ // Engine is the durable executor. It implements run.Executor and
49
+ // run.RunQueries.
50
+ type Engine struct {
51
+ backend backend.Backend
52
+ db *sql.DB
53
+ client *client.Client
54
+ wfWorker *worker.Worker
55
+ actWorker *worker.Worker
56
+ activities *Activities
57
+ runs *RunProjection
58
+ retention time.Duration
59
+ runtime run.RuntimePolicy
60
+
61
+ mu sync.RWMutex
62
+ snapshots map[run.ID]*workflow.Workflow // in-memory cache; history is authoritative
63
+
64
+ workerCtx context.Context
65
+ workerCancel context.CancelFunc
66
+ shutdownOnce sync.Once
67
+ workerName string
68
+ }
69
+
70
+ // InitDatabase creates the SQLite database at path (mode 0600) with the
71
+ // relay_runs projection schema and closes it. Used by `relay-flow init`;
72
+ // serve uses New to open the full engine.
73
+ func InitDatabase(path string) error {
74
+ db, err := sql.Open("sqlite", fmt.Sprintf("file:%s?_txlock=immediate", path))
75
+ if err != nil {
76
+ return fmt.Errorf("open %s: %w", path, err)
77
+ }
78
+ defer db.Close()
79
+ if _, err := db.Exec(`PRAGMA schema_version`); err != nil {
80
+ return fmt.Errorf("open %s: %w", path, err)
81
+ }
82
+ if _, err := db.Exec("PRAGMA journal_mode=WAL;"); err != nil {
83
+ return fmt.Errorf("open %s: %w", path, err)
84
+ }
85
+ if err := os.Chmod(path, 0o600); err != nil && !os.IsNotExist(err) {
86
+ return fmt.Errorf("chmod %s: %w", path, err)
87
+ }
88
+ proj := &RunProjection{DB: db}
89
+ if err := proj.migrate(); err != nil {
90
+ return fmt.Errorf("migrate relay_runs: %w", err)
91
+ }
92
+ return nil
93
+ }
94
+
95
+ // HasNonterminalRuns inspects an existing database without migrating or
96
+ // otherwise modifying it. It is used by init --force before config changes.
97
+ func HasNonterminalRuns(path string) (bool, error) {
98
+ db, err := sql.Open("sqlite", fmt.Sprintf("file:%s?mode=ro", path))
99
+ if err != nil {
100
+ return false, fmt.Errorf("open %s: %w", path, err)
101
+ }
102
+ defer db.Close()
103
+ var active bool
104
+ if err := db.QueryRow(`SELECT EXISTS(
105
+ SELECT 1 FROM relay_runs WHERE state NOT IN ('completed', 'canceled')
106
+ )`).Scan(&active); err != nil {
107
+ return false, fmt.Errorf("inspect %s: %w", path, err)
108
+ }
109
+ return active, nil
110
+ }
111
+
112
+ // New opens the SQLite database at path (created with mode 0600 when
113
+ // missing), migrates the relay_runs projection, and constructs the engine.
114
+ // A corrupt database file fails here.
115
+ func New(path string, deps Dependencies) (*Engine, error) {
116
+ if deps.Repos == nil || deps.Runner == nil || deps.Harness == nil {
117
+ return nil, fmt.Errorf("goworkflows: Repos, Runner, and Harness dependencies are required")
118
+ }
119
+ if deps.Runtime != nil && deps.Runtime.KeepTerminalsAlive && !deps.Runtime.KeepSessionsAlive {
120
+ return nil, fmt.Errorf("goworkflows: keepTerminalsAlive requires keepSessionsAlive")
121
+ }
122
+ db, err := sql.Open("sqlite", fmt.Sprintf("file:%s?_txlock=immediate", path))
123
+ if err != nil {
124
+ return nil, fmt.Errorf("open %s: %w", path, err)
125
+ }
126
+ // Fail fast on an unusable/corrupt database file.
127
+ if _, err := db.Exec(`PRAGMA schema_version`); err != nil {
128
+ db.Close()
129
+ return nil, fmt.Errorf("open %s: %w", path, err)
130
+ }
131
+ // SQLite allows one writer; a single connection acts as the mutex.
132
+ if _, err := db.Exec("PRAGMA journal_mode=WAL;"); err != nil {
133
+ db.Close()
134
+ return nil, fmt.Errorf("open %s: %w", path, err)
135
+ }
136
+ if _, err := db.Exec("PRAGMA busy_timeout = 5000;"); err != nil {
137
+ db.Close()
138
+ return nil, fmt.Errorf("open %s: %w", path, err)
139
+ }
140
+ db.SetMaxOpenConns(1)
141
+ if err := os.Chmod(path, 0o600); err != nil && !os.IsNotExist(err) {
142
+ db.Close()
143
+ return nil, fmt.Errorf("chmod %s: %w", path, err)
144
+ }
145
+ proj := &RunProjection{DB: db}
146
+ if err := proj.migrate(); err != nil {
147
+ db.Close()
148
+ return nil, fmt.Errorf("migrate relay_runs: %w", err)
149
+ }
150
+ activities := &Activities{
151
+ Repos: deps.Repos,
152
+ Runner: deps.Runner,
153
+ Harness: deps.Harness,
154
+ TaskSystem: deps.TaskSystem,
155
+ Runs: proj,
156
+ }
157
+ retention := 30 * 24 * time.Hour
158
+ if deps.RetentionDays > 0 {
159
+ retention = time.Duration(deps.RetentionDays) * 24 * time.Hour
160
+ }
161
+ runtimePolicy := run.RuntimePolicy{KeepTerminalsAlive: true, KeepSessionsAlive: true}
162
+ if deps.Runtime != nil {
163
+ runtimePolicy = *deps.Runtime
164
+ }
165
+ return &Engine{
166
+ db: db,
167
+ activities: activities,
168
+ runs: proj,
169
+ retention: retention,
170
+ runtime: runtimePolicy,
171
+ snapshots: map[run.ID]*workflow.Workflow{},
172
+ }, nil
173
+ }
174
+
175
+ // Start opens the go-workflows SQLite backend on the same database, starts
176
+ // one workflow worker (max 10 parallel workflow tasks) and one activity
177
+ // worker (max 20 parallel activities), runs the startup retention sweep, and
178
+ // resumes pending engine tasks automatically.
179
+ func (e *Engine) Start(ctx context.Context) error {
180
+ e.workerName = "relay-flow-" + uuid.NewString()
181
+ e.backend = sqlite.NewSqliteBackendWithDB(e.db, sqlite.WithApplyMigrations(true),
182
+ sqlite.WithBackendOptions(backend.WithWorkerName(e.workerName)))
183
+ e.client = client.New(e.backend)
184
+
185
+ wfOpts := worker.DefaultOptions.WorkflowWorkerOptions
186
+ wfOpts.MaxParallelWorkflowTasks = 10
187
+ e.wfWorker = worker.NewWorkflowWorker(e.backend, &wfOpts)
188
+ actOpts := worker.DefaultOptions.ActivityWorkerOptions
189
+ actOpts.MaxParallelActivityTasks = 20
190
+ e.actWorker = worker.NewActivityWorker(e.backend, &actOpts)
191
+ if err := e.wfWorker.RegisterWorkflow(e.activities.TicketWorkflow); err != nil {
192
+ return fmt.Errorf("register TicketWorkflow: %w", err)
193
+ }
194
+ if err := e.registerActivities(); err != nil {
195
+ return err
196
+ }
197
+ e.workerCtx, e.workerCancel = context.WithCancel(context.Background())
198
+ if err := e.wfWorker.Start(e.workerCtx); err != nil {
199
+ return fmt.Errorf("start workflow worker: %w", err)
200
+ }
201
+ if err := e.actWorker.Start(e.workerCtx); err != nil {
202
+ return fmt.Errorf("start activity worker: %w", err)
203
+ }
204
+ // Startup retention sweep (pre-poller window): remove old terminal
205
+ // projection rows and their engine histories; nonterminal runs stay.
206
+ cutoff := time.Now().Add(-e.retention)
207
+ ids, err := e.runs.sweepRetention(ctx, cutoff)
208
+ if err != nil {
209
+ return fmt.Errorf("retention sweep: %w", err)
210
+ }
211
+ if len(ids) > 0 {
212
+ if err := e.client.RemoveWorkflowInstances(ctx, backend.RemoveFinishedBefore(cutoff)); err != nil {
213
+ return fmt.Errorf("remove finished engine histories: %w", err)
214
+ }
215
+ }
216
+ return nil
217
+ }
218
+
219
+ func (e *Engine) registerActivities() error {
220
+ a := e.activities
221
+ for _, act := range []goworkflow.Activity{
222
+ a.EnsureMailboxes,
223
+ a.ValidateAgents,
224
+ a.ApplyTaskConfig,
225
+ a.EnsureEnvironment,
226
+ a.SetEnvironmentStatus,
227
+ a.LoadNodeRuntime,
228
+ a.EnsureNodeRuntime,
229
+ a.CloseTerminals,
230
+ a.CleanupRun,
231
+ a.CheckpointNodeRuntime,
232
+ a.FinalizeNodeRuntimes,
233
+ a.Comment,
234
+ a.CompleteMailbox,
235
+ a.ProjectionUpdateNodeRuntimeVisit,
236
+ a.ProjectionRecordProcessedReport,
237
+ a.ProjectionUpdateNode,
238
+ a.ProjectionUpdateState,
239
+ a.ProjectionUpdateRetry,
240
+ } {
241
+ if err := e.actWorker.RegisterActivity(act); err != nil {
242
+ return fmt.Errorf("register activity: %w", err)
243
+ }
244
+ }
245
+ return nil
246
+ }
247
+
248
+ // Shutdown cancels worker polling, waits a bounded time for active tasks,
249
+ // and closes SQLite. It is safe to call more than once.
250
+ func (e *Engine) Shutdown(ctx context.Context) error {
251
+ var err error
252
+ e.shutdownOnce.Do(func() {
253
+ if e.workerCancel != nil {
254
+ e.workerCancel()
255
+ }
256
+ // wfWorker/actWorker are nil until Start; tolerate Shutdown before
257
+ // Start so fail-fast startup validation can release the database.
258
+ if e.wfWorker != nil && e.actWorker != nil {
259
+ done := make(chan struct{}, 2)
260
+ go func() { _ = e.wfWorker.WaitForCompletion(); done <- struct{}{} }()
261
+ go func() { _ = e.actWorker.WaitForCompletion(); done <- struct{}{} }()
262
+ for i := 0; i < 2; i++ {
263
+ select {
264
+ case <-ctx.Done():
265
+ i = 2
266
+ case <-done:
267
+ }
268
+ }
269
+ }
270
+ // Release this worker's workflow-task leases: a stopped worker must
271
+ // not hold instances hostage until the lock timeout. Leases are
272
+ // crash-recovery primitives; the next engine re-locks on pickup.
273
+ if e.workerName != "" {
274
+ _, _ = e.db.Exec(`UPDATE instances SET locked_until = NULL, sticky_until = NULL, worker = NULL WHERE worker = ?`, e.workerName)
275
+ }
276
+ err = e.db.Close()
277
+ })
278
+ return err
279
+ }
280
+
281
+ // EnsureRun creates the durable run when missing (created=true). For an
282
+ // existing active run it reconciles the current node terminal by stable
283
+ // title and sends the reconcile signal only when that terminal is missing
284
+ // or unusable. Repeated polls are harmless.
285
+ func (e *Engine) EnsureRun(ctx context.Context, start run.Start) (bool, error) {
286
+ r, err := e.runs.get(ctx, start.ID)
287
+ if errors.Is(err, errRunNotFound) {
288
+ start.Runtime = e.runtime
289
+ if err := e.runs.insertStart(ctx, start, time.Now().UTC()); err != nil {
290
+ return false, fmt.Errorf("insert run %s: %w", start.ID, err)
291
+ }
292
+ _, err = e.client.CreateWorkflowInstance(ctx,
293
+ client.WorkflowInstanceOptions{InstanceID: string(start.ID)},
294
+ e.activities.TicketWorkflow, start)
295
+ if err != nil {
296
+ if errors.Is(err, backend.ErrInstanceAlreadyExists) {
297
+ return false, nil
298
+ }
299
+ return false, fmt.Errorf("create workflow instance %s: %w", start.ID, err)
300
+ }
301
+ e.mu.Lock()
302
+ wf := start.Workflow
303
+ e.snapshots[start.ID] = &wf
304
+ e.mu.Unlock()
305
+ // 9.3 run-lifecycle logging: one info line on run creation.
306
+ slog.Info("run created",
307
+ "ticket", start.Ticket.Key, "runID", string(start.ID),
308
+ "repo", start.Repo, "workflow", wf.Name)
309
+ return true, nil
310
+ }
311
+ if err != nil {
312
+ return false, err
313
+ }
314
+ if r.State != run.StateCompleted && r.State != run.StateCanceled && r.State != run.StateCanceling {
315
+ if _, err := e.instance(ctx, start.ID); errors.Is(err, sql.ErrNoRows) {
316
+ start.Runtime = e.runtime
317
+ if _, err := e.client.CreateWorkflowInstance(ctx,
318
+ client.WorkflowInstanceOptions{InstanceID: string(start.ID)},
319
+ e.activities.TicketWorkflow, start); err != nil && !errors.Is(err, backend.ErrInstanceAlreadyExists) {
320
+ return false, fmt.Errorf("create missing workflow instance %s: %w", start.ID, err)
321
+ }
322
+ return true, nil
323
+ } else if err != nil {
324
+ return false, err
325
+ }
326
+ }
327
+ // Existing run: reconcile only an active run at a work node.
328
+ if r.State == run.StateCompleted || r.State == run.StateCanceled || r.State == run.StateCanceling {
329
+ return false, nil
330
+ }
331
+ if r.CurrentNode == "" || r.CurrentNodeVisitID == "" {
332
+ return false, nil
333
+ }
334
+ runtime, err := e.runs.getNodeRuntime(ctx, r.ID, r.CurrentNode)
335
+ if err != nil && !errors.Is(err, errNodeRuntimeNotFound) {
336
+ return false, fmt.Errorf("load runtime for %s/%s: %w", r.ID, r.CurrentNode, err)
337
+ }
338
+ ok := false
339
+ if runtime.TerminalID != "" {
340
+ _, ok, _ = e.activities.Runner.FindTerminal(ctx, runner.Terminal{
341
+ ID: runtime.TerminalID, Title: r.Ticket.Key + ":" + r.CurrentNode,
342
+ })
343
+ }
344
+ if ok {
345
+ return false, nil // live usable terminal: no reconcile, no relaunch
346
+ }
347
+ if err := e.client.SignalWorkflow(ctx, string(r.ID), reconcileSignal, struct{}{}); err != nil {
348
+ return false, fmt.Errorf("signal reconcile for %s: %w", r.ID, err)
349
+ }
350
+ return false, nil
351
+ }
352
+
353
+ // SubmitReport drops processed report IDs immediately. New reports are
354
+ // validated and acknowledged only after their workflow signal is durable.
355
+ //
356
+ // 9.4 report-path logging: one info line per event on the report path —
357
+ // received, duplicate ack, validation failure, signal persisted, ack sent.
358
+ // Attrs always carry ticket/runID/node/nodeVisitID when known.
359
+ func (e *Engine) SubmitReport(ctx context.Context, req run.ReportRequest) (run.ReportAck, error) {
360
+ r, err := e.runs.get(ctx, req.RunID)
361
+ if err != nil {
362
+ return run.ReportAck{}, fmt.Errorf("resolve run %s: %w", req.RunID, err)
363
+ }
364
+ attrs := []any{
365
+ "ticket", r.Ticket.Key, "runID", string(req.RunID),
366
+ "repo", r.Repo, "workflow", r.Workflow,
367
+ "node", req.Node, "reportID", req.ReportID,
368
+ }
369
+ processed, err := e.runs.hasProcessedReport(ctx, req.RunID, req.ReportID)
370
+ if err != nil {
371
+ return run.ReportAck{}, fmt.Errorf("check report %s: %w", req.ReportID, err)
372
+ }
373
+ if processed {
374
+ slog.Info("report duplicate ack", append(attrs, "state", string(r.State))...)
375
+ return run.ReportAck{Accepted: true, Duplicate: true}, nil
376
+ }
377
+ slog.Info("report received", append(attrs,
378
+ "status", string(req.Report.Status), "nextStep", req.Report.NextStep)...)
379
+
380
+ current := r.CurrentNodeVisitID != "" && req.Node == r.CurrentNode &&
381
+ r.State != run.StateCompleted && r.State != run.StateCanceled
382
+ if !current {
383
+ slog.Info("report duplicate ack", append(attrs, "state", string(r.State))...)
384
+ return run.ReportAck{Accepted: true, Duplicate: true}, nil
385
+ }
386
+ wf, err := e.workflowOf(ctx, req.RunID)
387
+ if err != nil {
388
+ return run.ReportAck{}, err
389
+ }
390
+ if err := wf.ValidateReport(req.Node, req.Report); err != nil {
391
+ slog.Info("report validation failed", append(attrs, "reason", err.Error())...)
392
+ return run.ReportAck{Accepted: false}, err
393
+ }
394
+ signal := reportSignal{
395
+ ReportID: req.ReportID, Node: req.Node,
396
+ NodeVisitID: r.CurrentNodeVisitID, Report: req.Report,
397
+ }
398
+ if err := e.client.SignalWorkflow(ctx, string(req.RunID), reportSignalName, signal); err != nil {
399
+ return run.ReportAck{}, fmt.Errorf("signal report %s for %s: %w", req.ReportID, req.RunID, err)
400
+ }
401
+ attrs = append(attrs, "nodeVisitID", string(r.CurrentNodeVisitID))
402
+ // 9.3 transition effect + 9.4 report path: durable signal persisted
403
+ // (ack only after persistence per the report contract). One info line
404
+ // on the first accepted signal; duplicate/stale acks above skip this.
405
+ slog.Info("report persisted", append(attrs, "node", r.CurrentNode)...)
406
+ slog.Info("report ack sent", append(attrs, "node", r.CurrentNode)...)
407
+ return run.ReportAck{Accepted: true}, nil
408
+ }
409
+
410
+ // HasProcessedReport supports the server's payload-independent duplicate
411
+ // short circuit.
412
+ func (e *Engine) HasProcessedReport(ctx context.Context, id run.ID, reportID string) (bool, error) {
413
+ return e.runs.hasProcessedReport(ctx, id, reportID)
414
+ }
415
+
416
+ // RegisterNodeSession persists the OpenCode session for its stable run/node.
417
+ func (e *Engine) RegisterNodeSession(ctx context.Context, registration run.NodeRuntimeRegistration) (run.NodeRuntimeRegistrationAck, error) {
418
+ accepted, err := e.runs.registerNodeSession(ctx, registration)
419
+ if err != nil {
420
+ return run.NodeRuntimeRegistrationAck{}, err
421
+ }
422
+ return run.NodeRuntimeRegistrationAck{Accepted: accepted}, nil
423
+ }
424
+
425
+ // GetNodeRuntime returns one persisted per-node runtime binding.
426
+ func (e *Engine) GetNodeRuntime(ctx context.Context, id run.ID, node string) (NodeRuntime, error) {
427
+ return e.runs.getNodeRuntime(ctx, id, node)
428
+ }
429
+
430
+ // workflowOf returns the run's immutable workflow snapshot: the in-memory
431
+ // cache when present, otherwise decoded from the instance's started-event
432
+ // inputs in durable history.
433
+ func (e *Engine) workflowOf(ctx context.Context, id run.ID) (*workflow.Workflow, error) {
434
+ e.mu.RLock()
435
+ wf, ok := e.snapshots[id]
436
+ e.mu.RUnlock()
437
+ if ok {
438
+ return wf, nil
439
+ }
440
+ inst, err := e.instance(ctx, id)
441
+ if err != nil {
442
+ return nil, err
443
+ }
444
+ events, err := e.backend.GetWorkflowInstanceHistory(ctx, inst, nil)
445
+ if err != nil {
446
+ return nil, fmt.Errorf("load history for %s: %w", id, err)
447
+ }
448
+ for _, ev := range events {
449
+ if ev.Type != history.EventType_WorkflowExecutionStarted {
450
+ continue
451
+ }
452
+ attr, ok := ev.Attributes.(*history.ExecutionStartedAttributes)
453
+ if !ok || len(attr.Inputs) == 0 {
454
+ continue
455
+ }
456
+ var start run.Start
457
+ if err := converter.DefaultConverter.From(attr.Inputs[0], &start); err != nil {
458
+ return nil, fmt.Errorf("decode snapshot for %s: %w", id, err)
459
+ }
460
+ w := start.Workflow
461
+ e.mu.Lock()
462
+ e.snapshots[id] = &w
463
+ e.mu.Unlock()
464
+ return &w, nil
465
+ }
466
+ return nil, fmt.Errorf("no workflow snapshot in history for run %s", id)
467
+ }
468
+
469
+ // CancelRun cancels the workflow instance; cleanup runs on a disconnected
470
+ // workflow context and cannot interrupt an already-running activity.
471
+ func (e *Engine) CancelRun(ctx context.Context, id run.ID, reason string) error {
472
+ if _, err := e.runs.get(ctx, id); err != nil {
473
+ return fmt.Errorf("resolve run %s: %w", id, err)
474
+ }
475
+ if err := e.runs.updateState(ctx, id, run.StateCanceling, reason, nil); err != nil {
476
+ return err
477
+ }
478
+ inst, err := e.instance(ctx, id)
479
+ if err != nil {
480
+ return fmt.Errorf("cancel %s: %w", id, err)
481
+ }
482
+ if err := e.client.CancelWorkflowInstance(ctx, inst); err != nil {
483
+ return fmt.Errorf("cancel %s: %w", id, err)
484
+ }
485
+ return nil
486
+ }
487
+
488
+ // instance resolves the current execution for the durable run ID.
489
+ func (e *Engine) instance(ctx context.Context, id run.ID) (*goworkflow.Instance, error) {
490
+ var execID string
491
+ err := e.db.QueryRowContext(ctx,
492
+ `SELECT execution_id FROM instances WHERE id = ? AND state = ? ORDER BY rowid DESC LIMIT 1`,
493
+ string(id), 0).Scan(&execID)
494
+ if err != nil {
495
+ return nil, fmt.Errorf("workflow instance %s not found: %w", id, err)
496
+ }
497
+ return &goworkflow.Instance{InstanceID: string(id), ExecutionID: execID}, nil
498
+ }
499
+
500
+ // --- run.RunQueries ---
501
+
502
+ func (e *Engine) GetRun(ctx context.Context, id run.ID) (run.Run, error) {
503
+ return e.runs.get(ctx, id)
504
+ }
505
+
506
+ func (e *Engine) FindRunByTicket(ctx context.Context, ticket string) (run.Run, error) {
507
+ return e.runs.findByTicket(ctx, ticket)
508
+ }
509
+
510
+ func (e *Engine) ListRuns(ctx context.Context, filter run.Filter) ([]run.Run, error) {
511
+ return e.runs.list(ctx, filter)
512
+ }
513
+
514
+ func (e *Engine) HasActiveWorkflow(ctx context.Context, wf string) (bool, error) {
515
+ return e.runs.hasActive(ctx, "workflow", wf)
516
+ }
517
+
518
+ func (e *Engine) HasActiveRepo(ctx context.Context, repo string) (bool, error) {
519
+ return e.runs.hasActive(ctx, "repo", repo)
520
+ }