lastlight-core 0.25.9 → 0.27.0

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 (234) hide show
  1. package/config/default.yaml +317 -1
  2. package/dist/admin/chat-session-reader.d.ts +3 -3
  3. package/dist/admin/chat-session-reader.js +8 -8
  4. package/dist/admin/chat-session-reader.js.map +1 -1
  5. package/dist/admin/docker.js.map +1 -1
  6. package/dist/admin/routes.js +97 -99
  7. package/dist/admin/routes.js.map +1 -1
  8. package/dist/admin/sessions.d.ts +7 -7
  9. package/dist/admin/sessions.js +6 -4
  10. package/dist/admin/sessions.js.map +1 -1
  11. package/dist/admin/tail.js.map +1 -1
  12. package/dist/config/config.d.ts +29 -0
  13. package/dist/config/config.js +141 -0
  14. package/dist/config/config.js.map +1 -1
  15. package/dist/config/repo-config.js +6 -7
  16. package/dist/config/repo-config.js.map +1 -1
  17. package/dist/connectors/messaging/base.js +2 -2
  18. package/dist/connectors/messaging/base.js.map +1 -1
  19. package/dist/connectors/messaging/session-manager.d.ts +29 -31
  20. package/dist/connectors/messaging/session-manager.js +156 -189
  21. package/dist/connectors/messaging/session-manager.js.map +1 -1
  22. package/dist/connectors/messaging/thread-transcript.d.ts +2 -2
  23. package/dist/connectors/messaging/thread-transcript.js +14 -8
  24. package/dist/connectors/messaging/thread-transcript.js.map +1 -1
  25. package/dist/connectors/slack/connector.js +5 -5
  26. package/dist/connectors/slack/connector.js.map +1 -1
  27. package/dist/cron/dependabot-discovery.js.map +1 -1
  28. package/dist/cron/feedback-poll.js +6 -6
  29. package/dist/cron/feedback-poll.js.map +1 -1
  30. package/dist/cron/handlers.js +3 -3
  31. package/dist/cron/handlers.js.map +1 -1
  32. package/dist/cron/jobs.d.ts +1 -1
  33. package/dist/cron/jobs.js +2 -2
  34. package/dist/cron/jobs.js.map +1 -1
  35. package/dist/cron/repo-digest.js +4 -4
  36. package/dist/cron/repo-digest.js.map +1 -1
  37. package/dist/cron/review-discovery.js.map +1 -1
  38. package/dist/cron/runner.js +2 -2
  39. package/dist/cron/runner.js.map +1 -1
  40. package/dist/cron/scheduler.js +1 -1
  41. package/dist/cron/scheduler.js.map +1 -1
  42. package/dist/engine/agent-executor.d.ts +25 -1
  43. package/dist/engine/agent-executor.js +41 -1
  44. package/dist/engine/agent-executor.js.map +1 -1
  45. package/dist/engine/chat/chat-prompt.d.ts +11 -4
  46. package/dist/engine/chat/chat-prompt.js.map +1 -1
  47. package/dist/engine/chat/chat-runner.d.ts +3 -2
  48. package/dist/engine/chat/chat-runner.js +9 -7
  49. package/dist/engine/chat/chat-runner.js.map +1 -1
  50. package/dist/engine/dispatcher.js +29 -25
  51. package/dist/engine/dispatcher.js.map +1 -1
  52. package/dist/engine/event-shim.d.ts +18 -0
  53. package/dist/engine/event-shim.js +2 -0
  54. package/dist/engine/event-shim.js.map +1 -1
  55. package/dist/engine/executors/orchestrator.d.ts +120 -1
  56. package/dist/engine/executors/orchestrator.js +214 -47
  57. package/dist/engine/executors/orchestrator.js.map +1 -1
  58. package/dist/engine/executors/shared.js.map +1 -1
  59. package/dist/engine/feedback/ingest.d.ts +4 -4
  60. package/dist/engine/feedback/ingest.js +13 -13
  61. package/dist/engine/feedback/ingest.js.map +1 -1
  62. package/dist/engine/feedback/slack.d.ts +2 -2
  63. package/dist/engine/feedback/slack.js +6 -6
  64. package/dist/engine/feedback/slack.js.map +1 -1
  65. package/dist/engine/fix-harvest.d.ts +1 -1
  66. package/dist/engine/fix-harvest.js +3 -3
  67. package/dist/engine/fix-harvest.js.map +1 -1
  68. package/dist/engine/github/github.d.ts +59 -0
  69. package/dist/engine/github/github.js +72 -0
  70. package/dist/engine/github/github.js.map +1 -1
  71. package/dist/engine/github/installations.js.map +1 -1
  72. package/dist/engine/github/review-poster.d.ts +388 -9
  73. package/dist/engine/github/review-poster.js +550 -50
  74. package/dist/engine/github/review-poster.js.map +1 -1
  75. package/dist/engine/github/team-visibility.js +7 -7
  76. package/dist/engine/github/team-visibility.js.map +1 -1
  77. package/dist/engine/llm.js.map +1 -1
  78. package/dist/engine/pr-decisions.d.ts +13 -5
  79. package/dist/engine/pr-decisions.js +204 -5
  80. package/dist/engine/pr-decisions.js.map +1 -1
  81. package/dist/engine/pr-escalation.js +7 -7
  82. package/dist/engine/pr-escalation.js.map +1 -1
  83. package/dist/engine/pr-state.d.ts +59 -1
  84. package/dist/engine/pr-state.js +76 -10
  85. package/dist/engine/pr-state.js.map +1 -1
  86. package/dist/engine/review-check.d.ts +1 -1
  87. package/dist/engine/review-check.js +5 -5
  88. package/dist/engine/review-check.js.map +1 -1
  89. package/dist/engine/review-spec.d.ts +264 -0
  90. package/dist/engine/review-spec.js +723 -0
  91. package/dist/engine/review-spec.js.map +1 -0
  92. package/dist/engine/router.js +3 -3
  93. package/dist/engine/router.js.map +1 -1
  94. package/dist/engine/screen/classifier.js.map +1 -1
  95. package/dist/engine/screen/screen.js.map +1 -1
  96. package/dist/evals-api.d.ts +3 -0
  97. package/dist/evals-api.js +20 -0
  98. package/dist/evals-api.js.map +1 -1
  99. package/dist/index.js +145 -67
  100. package/dist/index.js.map +1 -1
  101. package/dist/notify/digest-blocks.js.map +1 -1
  102. package/dist/notify/model.js.map +1 -1
  103. package/dist/notify/transports/github.js.map +1 -1
  104. package/dist/notify/transports/slack.js.map +1 -1
  105. package/dist/sandbox/artifact-backend.js.map +1 -1
  106. package/dist/sandbox/artifact-store.js.map +1 -1
  107. package/dist/sandbox/docker.d.ts +56 -5
  108. package/dist/sandbox/docker.js +96 -2
  109. package/dist/sandbox/docker.js.map +1 -1
  110. package/dist/sandbox/egress-allowlist.js.map +1 -1
  111. package/dist/sandbox/k8s/agent-context-registry.js.map +1 -1
  112. package/dist/sandbox/k8s/client.js.map +1 -1
  113. package/dist/sandbox/k8s/kubernetes-sandbox.d.ts +3 -0
  114. package/dist/sandbox/k8s/kubernetes-sandbox.js +9 -0
  115. package/dist/sandbox/k8s/kubernetes-sandbox.js.map +1 -1
  116. package/dist/sandbox/k8s/pod.d.ts +11 -0
  117. package/dist/sandbox/k8s/pod.js +11 -6
  118. package/dist/sandbox/k8s/pod.js.map +1 -1
  119. package/dist/sandbox/k8s/resource-name.js.map +1 -1
  120. package/dist/sandbox/k8s/run-id.js.map +1 -1
  121. package/dist/sandbox/k8s/run-secrets.js.map +1 -1
  122. package/dist/sandbox/k8s/service-containers.d.ts +43 -0
  123. package/dist/sandbox/k8s/service-containers.js +87 -0
  124. package/dist/sandbox/k8s/service-containers.js.map +1 -0
  125. package/dist/sandbox/k8s/skill-bundle.js.map +1 -1
  126. package/dist/sandbox/k8s/workspace-provisioner.js +10 -2
  127. package/dist/sandbox/k8s/workspace-provisioner.js.map +1 -1
  128. package/dist/sandbox/reap.d.ts +9 -0
  129. package/dist/sandbox/reap.js +36 -0
  130. package/dist/sandbox/reap.js.map +1 -1
  131. package/dist/sandbox/sandbox.d.ts +34 -0
  132. package/dist/sandbox/sandbox.js +36 -6
  133. package/dist/sandbox/sandbox.js.map +1 -1
  134. package/dist/sandbox/service-containers-docker.d.ts +45 -0
  135. package/dist/sandbox/service-containers-docker.js +78 -0
  136. package/dist/sandbox/service-containers-docker.js.map +1 -0
  137. package/dist/session-log.js.map +1 -1
  138. package/dist/state/approval-store.d.ts +23 -14
  139. package/dist/state/approval-store.js +137 -86
  140. package/dist/state/approval-store.js.map +1 -1
  141. package/dist/state/build-assets.js.map +1 -1
  142. package/dist/state/client.d.ts +105 -0
  143. package/dist/state/client.js +68 -0
  144. package/dist/state/client.js.map +1 -0
  145. package/dist/state/cron-run-store.d.ts +32 -12
  146. package/dist/state/cron-run-store.js +105 -39
  147. package/dist/state/cron-run-store.js.map +1 -1
  148. package/dist/state/data-migrate.d.ts +135 -0
  149. package/dist/state/data-migrate.js +309 -0
  150. package/dist/state/data-migrate.js.map +1 -0
  151. package/dist/state/db.d.ts +82 -23
  152. package/dist/state/db.js +201 -105
  153. package/dist/state/db.js.map +1 -1
  154. package/dist/state/dialect.d.ts +77 -0
  155. package/dist/state/dialect.js +129 -0
  156. package/dist/state/dialect.js.map +1 -0
  157. package/dist/state/execution-store.d.ts +124 -103
  158. package/dist/state/execution-store.js +569 -374
  159. package/dist/state/execution-store.js.map +1 -1
  160. package/dist/state/feedback-store.d.ts +20 -20
  161. package/dist/state/feedback-store.js +241 -187
  162. package/dist/state/feedback-store.js.map +1 -1
  163. package/dist/state/legacy-sqlite.d.ts +15 -0
  164. package/dist/state/legacy-sqlite.js +131 -0
  165. package/dist/state/legacy-sqlite.js.map +1 -0
  166. package/dist/state/pg-client.d.ts +44 -0
  167. package/dist/state/pg-client.js +81 -0
  168. package/dist/state/pg-client.js.map +1 -0
  169. package/dist/state/repo-ref.d.ts +9 -4
  170. package/dist/state/repo-ref.js +12 -6
  171. package/dist/state/repo-ref.js.map +1 -1
  172. package/dist/state/schema/pg.d.ts +2788 -0
  173. package/dist/state/schema/pg.js +301 -0
  174. package/dist/state/schema/pg.js.map +1 -0
  175. package/dist/state/schema/sqlite.d.ts +3063 -0
  176. package/dist/state/schema/sqlite.js +391 -0
  177. package/dist/state/schema/sqlite.js.map +1 -0
  178. package/dist/state/state-cli.d.ts +8 -0
  179. package/dist/state/state-cli.js +247 -0
  180. package/dist/state/state-cli.js.map +1 -0
  181. package/dist/state/team-store.d.ts +26 -13
  182. package/dist/state/team-store.js +140 -93
  183. package/dist/state/team-store.js.map +1 -1
  184. package/dist/state/user-store.d.ts +31 -13
  185. package/dist/state/user-store.js +180 -80
  186. package/dist/state/user-store.js.map +1 -1
  187. package/dist/state/workflow-run-store.d.ts +95 -56
  188. package/dist/state/workflow-run-store.js +419 -314
  189. package/dist/state/workflow-run-store.js.map +1 -1
  190. package/dist/telemetry/index.js.map +1 -1
  191. package/dist/workflows/admission.d.ts +4 -3
  192. package/dist/workflows/admission.js +34 -10
  193. package/dist/workflows/admission.js.map +1 -1
  194. package/dist/workflows/handlers/fanout.d.ts +157 -0
  195. package/dist/workflows/handlers/fanout.js +663 -0
  196. package/dist/workflows/handlers/fanout.js.map +1 -0
  197. package/dist/workflows/handlers/post-review.d.ts +98 -8
  198. package/dist/workflows/handlers/post-review.js +394 -23
  199. package/dist/workflows/handlers/post-review.js.map +1 -1
  200. package/dist/workflows/resume.js +22 -15
  201. package/dist/workflows/resume.js.map +1 -1
  202. package/dist/workflows/runner.js +60 -12
  203. package/dist/workflows/runner.js.map +1 -1
  204. package/dist/workflows/simple.d.ts +23 -0
  205. package/dist/workflows/simple.js +40 -16
  206. package/dist/workflows/simple.js.map +1 -1
  207. package/docker-compose.yml +50 -0
  208. package/drizzle/pg/0000_init.sql +235 -0
  209. package/drizzle/pg/meta/0000_snapshot.json +1751 -0
  210. package/drizzle/pg/meta/_journal.json +13 -0
  211. package/drizzle/sqlite/0000_baseline.sql +257 -0
  212. package/drizzle/sqlite/0001_backfill_repo_refs.sql +74 -0
  213. package/drizzle/sqlite/meta/0000_snapshot.json +1593 -0
  214. package/drizzle/sqlite/meta/0001_snapshot.json +1593 -0
  215. package/drizzle/sqlite/meta/_journal.json +20 -0
  216. package/package.json +31 -15
  217. package/sandbox.Dockerfile +54 -0
  218. package/skills/code-review/SKILL.md +98 -13
  219. package/skills/pr-review/SKILL.md +97 -21
  220. package/skills/pr-review/references/findings-schema.md +37 -6
  221. package/workflows/pr-review.yaml +567 -0
  222. package/workflows/prompts/dependabot-pr-merge.md +22 -2
  223. package/workflows/prompts/review-adjudicate.md +323 -0
  224. package/workflows/prompts/review-falsify.md +149 -0
  225. package/workflows/prompts/review.md +80 -0
  226. package/workflows/prompts/survey-contract.md +109 -0
  227. package/workflows/prompts/survey-enforcement.md +126 -0
  228. package/workflows/prompts/survey-security.md +118 -0
  229. package/workflows/prompts/survey-spec.md +110 -0
  230. package/workflows/prompts/survey-state.md +143 -0
  231. package/workflows/prompts/survey-tests.md +99 -0
  232. package/dist/state/migrate.d.ts +0 -15
  233. package/dist/state/migrate.js +0 -518
  234. package/dist/state/migrate.js.map +0 -1
@@ -1,3 +1,6 @@
1
+ import { and, asc, count, desc, eq, gte, inArray, isNotNull, ne, or, sql } from "drizzle-orm";
2
+ import { nullsToUndefined, tablesOf, } from "./client.js";
3
+ import { changes } from "./dialect.js";
1
4
  import { normalizeRepoRef, qualifiedRepoSql } from "./repo-ref.js";
2
5
  import { logger } from "../logging/logger.js";
3
6
  const log = logger("runs");
@@ -18,7 +21,7 @@ const log = logger("runs");
18
21
  * actually moving. Everything terminal shares the last bucket and stays purely
19
22
  * chronological among itself, which is what the day/week ranges want.
20
23
  */
21
- const ACTIVE_FIRST = `CASE status
24
+ const ACTIVE_FIRST = ({ workflowRuns }) => sql `CASE ${workflowRuns.status}
22
25
  WHEN 'running' THEN 0
23
26
  WHEN 'paused' THEN 1
24
27
  WHEN 'queued' THEN 2
@@ -40,23 +43,29 @@ const ACTIVE_FIRST = `CASE status
40
43
  * and because dropping a row from a filter is the failure mode that hides
41
44
  * things silently.
42
45
  */
43
- function repoMatchClause(repo) {
46
+ function repoMatchClause({ workflowRuns }, repo) {
44
47
  const slash = repo.indexOf("/");
45
48
  if (slash > 0) {
46
- return {
47
- sql: "((owner = ? AND repo = ?) OR repo = ?)",
48
- values: [repo.slice(0, slash), repo.slice(slash + 1), repo],
49
- };
49
+ return or(and(eq(workflowRuns.owner, repo.slice(0, slash)), eq(workflowRuns.repo, repo.slice(slash + 1))), eq(workflowRuns.repo, repo));
50
50
  }
51
- return { sql: "repo = ?", values: [repo] };
51
+ return eq(workflowRuns.repo, repo);
52
52
  }
53
53
  export class WorkflowRunStore {
54
- db;
54
+ client;
55
55
  approvals;
56
+ serialize;
56
57
  terminalObservers = [];
57
- constructor(db, deps) {
58
- this.db = db;
58
+ /**
59
+ * Table objects for THIS client's dialect. Every method destructures what it
60
+ * needs off this instead of importing from `schema/sqlite.js` — see
61
+ * `client.ts` → {@link tablesOf} for why the cast alone cannot do it.
62
+ */
63
+ t;
64
+ constructor(client, deps) {
65
+ this.client = client;
59
66
  this.approvals = deps.approvals;
67
+ this.serialize = deps.serialize;
68
+ this.t = tablesOf(client);
60
69
  }
61
70
  /** Add a {@link TerminalRunObserver}. Wired at boot; order is registration order. */
62
71
  addTerminalObserver(fn) {
@@ -68,12 +77,12 @@ export class WorkflowRunStore {
68
77
  * time we get here, no projection of it may undo that, and one projection
69
78
  * failing must not cost the others their notification.
70
79
  */
71
- notifyTerminal(id, status) {
80
+ async notifyTerminal(id, status) {
72
81
  if (this.terminalObservers.length === 0)
73
82
  return;
74
83
  let run = null;
75
84
  try {
76
- run = this.getRun(id);
85
+ run = await this.getRun(id);
77
86
  }
78
87
  catch (err) {
79
88
  log.warn("Could not read a terminal run for its observers", { runId: id, err });
@@ -90,6 +99,26 @@ export class WorkflowRunStore {
90
99
  }
91
100
  }
92
101
  }
102
+ /**
103
+ * Read a run's `context` object for an app-side read-modify-write.
104
+ *
105
+ * The three context mutations in this store — the error annotation in
106
+ * {@link expireQueued} and {@link flipFinished}, the error clear in
107
+ * {@link restartRun} — used to be `json_patch` / `json_remove` SQL, which
108
+ * Postgres has no equivalent for. `context` is a json-mode column, so the
109
+ * builder hands the object over and takes one back and the merge is plain JS.
110
+ * A missing row (or a NULL column) reads as `{}`, exactly what the
111
+ * `COALESCE(context, '{}')` those statements opened with produced.
112
+ */
113
+ async readContext(id, dbc = this.client) {
114
+ const { workflowRuns } = this.t;
115
+ const [row] = await dbc
116
+ .select({ context: workflowRuns.context })
117
+ .from(workflowRuns)
118
+ .where(eq(workflowRuns.id, id))
119
+ .limit(1);
120
+ return { ...(row?.context ?? {}) };
121
+ }
93
122
  // ── Plain single-mutation operations ───────────────────────────
94
123
  /**
95
124
  * Create a new workflow run record.
@@ -99,13 +128,29 @@ export class WorkflowRunStore {
99
128
  * passing `"owner/repo"` is split rather than stored as a third shape. See
100
129
  * `state/repo-ref.ts`.
101
130
  */
102
- createRun(run) {
131
+ async createRun(run) {
132
+ const { workflowRuns } = this.t;
103
133
  const now = new Date().toISOString();
104
134
  const ref = normalizeRepoRef(run.owner, run.repo);
105
- this.db.prepare(`
106
- INSERT INTO workflow_runs (id, workflow_name, trigger_id, owner, repo, issue_number, current_phase, phase_history, status, context, scratch, started_at, updated_at, triggered_by, trigger_actor_type)
107
- VALUES (?, ?, ?, ?, ?, ?, ?, '[]', ?, ?, ?, ?, ?, ?, ?)
108
- `).run(run.id, run.workflowName, run.triggerId, ref.owner ?? null, ref.repo ?? null, run.issueNumber ?? null, run.currentPhase, run.status, run.context ? JSON.stringify(run.context) : null, run.scratch ? JSON.stringify(run.scratch) : null, run.startedAt, now, run.triggeredBy ?? null, run.triggerActorType ?? null);
135
+ // `context` / `scratch` / `phase_history` are json-mode columns: hand them
136
+ // the OBJECT. Pre-stringifying would double-encode, silently.
137
+ await this.client.insert(workflowRuns).values({
138
+ id: run.id,
139
+ workflowName: run.workflowName,
140
+ triggerId: run.triggerId,
141
+ owner: ref.owner ?? null,
142
+ repo: ref.repo ?? null,
143
+ issueNumber: run.issueNumber ?? null,
144
+ currentPhase: run.currentPhase,
145
+ phaseHistory: [],
146
+ status: run.status,
147
+ context: run.context ?? null,
148
+ scratch: run.scratch ?? null,
149
+ startedAt: run.startedAt,
150
+ updatedAt: now,
151
+ triggeredBy: run.triggeredBy ?? null,
152
+ triggerActorType: run.triggerActorType ?? null,
153
+ });
109
154
  }
110
155
  /**
111
156
  * Top-level merge of `patch` into the workflow run's scratch state.
@@ -113,24 +158,25 @@ export class WorkflowRunStore {
113
158
  * other keys.
114
159
  *
115
160
  * Throws if `patch` is not JSON-serializable (e.g. it contains a BigInt) —
116
- * which is exactly how the atomic ops prove their rollback: a poison patch
117
- * makes `JSON.stringify` throw mid-transaction.
161
+ * which is exactly how the atomic ops prove their rollback: Drizzle
162
+ * serializes the json-mode column when it executes the UPDATE, so a poison
163
+ * patch throws from the statement itself, before it has mutated anything.
118
164
  */
119
- mergeScratch(id, patch) {
165
+ async mergeScratch(id, patch, dbc = this.client) {
166
+ const { workflowRuns } = this.t;
120
167
  const now = new Date().toISOString();
121
- const row = this.db
122
- .prepare(`SELECT scratch FROM workflow_runs WHERE id = ?`)
123
- .get(id);
168
+ const [row] = await dbc
169
+ .select({ scratch: workflowRuns.scratch })
170
+ .from(workflowRuns)
171
+ .where(eq(workflowRuns.id, id))
172
+ .limit(1);
124
173
  if (!row)
125
174
  return;
126
- const current = row.scratch ? JSON.parse(row.scratch) : {};
127
- const merged = { ...current, ...patch };
128
- // Stringify BEFORE the UPDATE so a non-serializable patch throws without
129
- // having mutated the row — keeps the op all-or-nothing even outside a txn.
130
- const serialized = JSON.stringify(merged);
131
- this.db
132
- .prepare(`UPDATE workflow_runs SET scratch = ?, updated_at = ? WHERE id = ?`)
133
- .run(serialized, now, id);
175
+ const merged = { ...(row.scratch ?? {}), ...patch };
176
+ await dbc
177
+ .update(workflowRuns)
178
+ .set({ scratch: merged, updatedAt: now })
179
+ .where(eq(workflowRuns.id, id));
134
180
  }
135
181
  /**
136
182
  * Remember which OTel trace this run is being exported under (issue #255).
@@ -143,10 +189,12 @@ export class WorkflowRunStore {
143
189
  * repeated — a resume re-opens a span under a new trace, and the newest trace
144
190
  * is the right one for a signal arriving now.
145
191
  */
146
- setTraceContext(id, traceId, spanId) {
147
- this.db
148
- .prepare(`UPDATE workflow_runs SET trace_id = ?, span_id = ? WHERE id = ?`)
149
- .run(traceId, spanId, id);
192
+ async setTraceContext(id, traceId, spanId) {
193
+ const { workflowRuns } = this.t;
194
+ await this.client
195
+ .update(workflowRuns)
196
+ .set({ traceId, spanId })
197
+ .where(eq(workflowRuns.id, id));
150
198
  }
151
199
  /**
152
200
  * Update the current phase and append to phase history. This is the single
@@ -155,30 +203,41 @@ export class WorkflowRunStore {
155
203
  * routes every write through here so that future change touches one method
156
204
  * instead of ~10 call sites).
157
205
  */
158
- appendPhase(id, phase, entry) {
206
+ async appendPhase(id, phase, entry, dbc = this.client) {
207
+ const { workflowRuns } = this.t;
159
208
  const now = new Date().toISOString();
160
- const row = this.db.prepare(`SELECT phase_history FROM workflow_runs WHERE id = ?`).get(id);
209
+ const [row] = await dbc
210
+ .select({ phaseHistory: workflowRuns.phaseHistory })
211
+ .from(workflowRuns)
212
+ .where(eq(workflowRuns.id, id))
213
+ .limit(1);
161
214
  if (!row)
162
215
  return;
163
- const history = JSON.parse(row.phase_history);
164
- history.push(entry);
165
- this.db.prepare(`
166
- UPDATE workflow_runs SET current_phase = ?, phase_history = ?, updated_at = ? WHERE id = ?
167
- `).run(phase, JSON.stringify(history), now, id);
216
+ const history = [...row.phaseHistory, entry];
217
+ await dbc
218
+ .update(workflowRuns)
219
+ .set({ currentPhase: phase, phaseHistory: history, updatedAt: now })
220
+ .where(eq(workflowRuns.id, id));
168
221
  }
169
222
  /** Get a single workflow run by ID */
170
- getRun(id) {
171
- const row = this.db.prepare(`SELECT * FROM workflow_runs WHERE id = ?`).get(id);
223
+ async getRun(id, dbc = this.client) {
224
+ const { workflowRuns } = this.t;
225
+ const [row] = await dbc
226
+ .select()
227
+ .from(workflowRuns)
228
+ .where(eq(workflowRuns.id, id))
229
+ .limit(1);
172
230
  return row ? this.deserialize(row) : null;
173
231
  }
174
232
  /** Find the most recent active (running, paused, or queued) workflow run for a trigger */
175
- getByTrigger(triggerId) {
176
- const row = this.db.prepare(`
177
- SELECT * FROM workflow_runs
178
- WHERE trigger_id = ? AND status IN ('queued', 'running', 'paused')
179
- ORDER BY started_at DESC
180
- LIMIT 1
181
- `).get(triggerId);
233
+ async getByTrigger(triggerId) {
234
+ const { workflowRuns } = this.t;
235
+ const [row] = await this.client
236
+ .select()
237
+ .from(workflowRuns)
238
+ .where(and(eq(workflowRuns.triggerId, triggerId), inArray(workflowRuns.status, ["queued", "running", "paused"])))
239
+ .orderBy(desc(workflowRuns.startedAt))
240
+ .limit(1);
182
241
  return row ? this.deserialize(row) : null;
183
242
  }
184
243
  /**
@@ -187,12 +246,13 @@ export class WorkflowRunStore {
187
246
  * already succeeded/failed/cancelled — the signal the router uses to gate
188
247
  * reporter-driven re-triage to the pre-build window.
189
248
  */
190
- hasRunForTrigger(triggerId, workflowName) {
191
- const row = this.db.prepare(`
192
- SELECT 1 FROM workflow_runs
193
- WHERE trigger_id = ? AND workflow_name = ?
194
- LIMIT 1
195
- `).get(triggerId, workflowName);
249
+ async hasRunForTrigger(triggerId, workflowName) {
250
+ const { workflowRuns } = this.t;
251
+ const [row] = await this.client
252
+ .select({ id: workflowRuns.id })
253
+ .from(workflowRuns)
254
+ .where(and(eq(workflowRuns.triggerId, triggerId), eq(workflowRuns.workflowName, workflowName)))
255
+ .limit(1);
196
256
  return !!row;
197
257
  }
198
258
  /**
@@ -201,13 +261,14 @@ export class WorkflowRunStore {
201
261
  * dependency-workflow dedup guard reads the winner's stored `context.headSha`
202
262
  * to skip re-assessing a PR at a head SHA it already handled.
203
263
  */
204
- latestSucceededForTrigger(workflowName, triggerId) {
205
- const row = this.db.prepare(`
206
- SELECT * FROM workflow_runs
207
- WHERE trigger_id = ? AND workflow_name = ? AND status = 'succeeded'
208
- ORDER BY started_at DESC
209
- LIMIT 1
210
- `).get(triggerId, workflowName);
264
+ async latestSucceededForTrigger(workflowName, triggerId) {
265
+ const { workflowRuns } = this.t;
266
+ const [row] = await this.client
267
+ .select()
268
+ .from(workflowRuns)
269
+ .where(and(eq(workflowRuns.triggerId, triggerId), eq(workflowRuns.workflowName, workflowName), eq(workflowRuns.status, "succeeded")))
270
+ .orderBy(desc(workflowRuns.startedAt))
271
+ .limit(1);
211
272
  return row ? this.deserialize(row) : null;
212
273
  }
213
274
  /**
@@ -230,16 +291,16 @@ export class WorkflowRunStore {
230
291
  * would make a crash look like "no prior attempt" and re-arm the loop
231
292
  * from zero.
232
293
  */
233
- latestForTrigger(workflowNames, triggerId) {
294
+ async latestForTrigger(workflowNames, triggerId) {
295
+ const { workflowRuns } = this.t;
234
296
  if (workflowNames.length === 0)
235
297
  return null;
236
- const placeholders = workflowNames.map(() => "?").join(", ");
237
- const row = this.db.prepare(`
238
- SELECT * FROM workflow_runs
239
- WHERE trigger_id = ? AND workflow_name IN (${placeholders})
240
- ORDER BY started_at DESC
241
- LIMIT 1
242
- `).get(triggerId, ...workflowNames);
298
+ const [row] = await this.client
299
+ .select()
300
+ .from(workflowRuns)
301
+ .where(and(eq(workflowRuns.triggerId, triggerId), inArray(workflowRuns.workflowName, workflowNames)))
302
+ .orderBy(desc(workflowRuns.startedAt))
303
+ .limit(1);
243
304
  return row ? this.deserialize(row) : null;
244
305
  }
245
306
  /**
@@ -254,17 +315,16 @@ export class WorkflowRunStore {
254
315
  * would have two agents fetch/reset/push the same branch through the same
255
316
  * directory.
256
317
  */
257
- activeForTrigger(workflowNames, triggerId) {
318
+ async activeForTrigger(workflowNames, triggerId) {
319
+ const { workflowRuns } = this.t;
258
320
  if (workflowNames.length === 0)
259
321
  return null;
260
- const placeholders = workflowNames.map(() => "?").join(", ");
261
- const row = this.db.prepare(`
262
- SELECT * FROM workflow_runs
263
- WHERE trigger_id = ? AND workflow_name IN (${placeholders})
264
- AND status IN ('queued', 'running', 'paused')
265
- ORDER BY started_at ASC
266
- LIMIT 1
267
- `).get(triggerId, ...workflowNames);
322
+ const [row] = await this.client
323
+ .select()
324
+ .from(workflowRuns)
325
+ .where(and(eq(workflowRuns.triggerId, triggerId), inArray(workflowRuns.workflowName, workflowNames), inArray(workflowRuns.status, ["queued", "running", "paused"])))
326
+ .orderBy(asc(workflowRuns.startedAt))
327
+ .limit(1);
268
328
  return row ? this.deserialize(row) : null;
269
329
  }
270
330
  /**
@@ -276,27 +336,33 @@ export class WorkflowRunStore {
276
336
  * having succeeded at a SHA says nothing about whether `dependabot-pr-merge`
277
337
  * has assessed it. One small indexed lookup per name — the set is four.
278
338
  */
279
- latestSucceededForTriggers(workflowNames, triggerId) {
339
+ async latestSucceededForTriggers(workflowNames, triggerId) {
280
340
  const out = {};
281
341
  for (const name of workflowNames) {
282
- const run = this.latestSucceededForTrigger(name, triggerId);
342
+ const run = await this.latestSucceededForTrigger(name, triggerId);
283
343
  if (run)
284
344
  out[name] = run;
285
345
  }
286
346
  return out;
287
347
  }
288
348
  /** List all active (queued, running, or paused) workflow runs */
289
- listActive() {
290
- const rows = this.db.prepare(`
291
- SELECT * FROM workflow_runs WHERE status IN ('queued', 'running', 'paused') ORDER BY started_at DESC
292
- `).all();
349
+ async listActive() {
350
+ const { workflowRuns } = this.t;
351
+ const rows = await this.client
352
+ .select()
353
+ .from(workflowRuns)
354
+ .where(inArray(workflowRuns.status, ["queued", "running", "paused"]))
355
+ .orderBy(desc(workflowRuns.startedAt));
293
356
  return rows.map((r) => this.deserialize(r));
294
357
  }
295
358
  /** List recent workflow runs, ordered by start time descending */
296
- listRecent(limit = 20) {
297
- const rows = this.db.prepare(`
298
- SELECT * FROM workflow_runs ORDER BY started_at DESC LIMIT ?
299
- `).all(limit);
359
+ async listRecent(limit = 20) {
360
+ const { workflowRuns } = this.t;
361
+ const rows = await this.client
362
+ .select()
363
+ .from(workflowRuns)
364
+ .orderBy(desc(workflowRuns.startedAt))
365
+ .limit(limit);
300
366
  return rows.map((r) => this.deserialize(r));
301
367
  }
302
368
  /**
@@ -309,73 +375,79 @@ export class WorkflowRunStore {
309
375
  * `succeeded`, `failed`, `cancelled`). Used for the dashboard's "live"
310
376
  * filter, which maps to ['running','paused'].
311
377
  */
312
- list(opts = {}) {
378
+ async list(opts = {}) {
379
+ const { workflowRuns, executions } = this.t;
313
380
  const limit = opts.limit ?? 20;
314
381
  const offset = opts.offset ?? 0;
315
382
  const where = [];
316
- const params = [];
317
- if (opts.sinceIso) {
318
- where.push("started_at >= ?");
319
- params.push(opts.sinceIso);
320
- }
321
- if (opts.workflowName) {
322
- where.push("workflow_name = ?");
323
- params.push(opts.workflowName);
324
- }
383
+ if (opts.sinceIso)
384
+ where.push(gte(workflowRuns.startedAt, opts.sinceIso));
385
+ if (opts.workflowName)
386
+ where.push(eq(workflowRuns.workflowName, opts.workflowName));
325
387
  if (opts.repo) {
326
- const { sql, values } = repoMatchClause(opts.repo);
327
- where.push(sql);
328
- params.push(...values);
388
+ where.push(repoMatchClause(this.t, opts.repo));
329
389
  }
330
390
  else if (opts.repos && opts.repos.length > 0) {
331
391
  // OR the per-repo clauses. Not an `IN (...)`, because the column doesn't
332
392
  // hold the value being matched — see `repoMatchClause`.
333
- const parts = opts.repos.map((r) => repoMatchClause(r));
334
- where.push(`(${parts.map((p) => p.sql).join(" OR ")})`);
335
- for (const p of parts)
336
- params.push(...p.values);
393
+ where.push(or(...opts.repos.map((r) => repoMatchClause(this.t, r))));
337
394
  }
338
395
  if (opts.statuses && opts.statuses.length > 0) {
339
- where.push(`status IN (${opts.statuses.map(() => "?").join(",")})`);
340
- params.push(...opts.statuses);
396
+ where.push(inArray(workflowRuns.status, opts.statuses));
341
397
  }
342
- const whereClause = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
343
- const total = this.db
344
- .prepare(`SELECT COUNT(*) as c FROM workflow_runs ${whereClause}`)
345
- .get(...params).c;
398
+ const whereClause = where.length > 0 ? and(...where) : undefined;
399
+ const [counted] = await this.client
400
+ .select({ c: count() })
401
+ .from(workflowRuns)
402
+ .where(whereClause);
403
+ const total = counted?.c ?? 0;
404
+ // A per-run token/cost roll-up, LEFT JOINed (indexed by
405
+ // `idx_executions_workflow_run`). `agg` only exposes `workflow_run_id` +
406
+ // the two sums, so nothing here collides with `workflow_runs`.
407
+ const agg = this.client
408
+ .select({
409
+ workflowRunId: executions.workflowRunId,
410
+ totalCostUsd: sql `SUM(COALESCE(${executions.costUsd}, 0))`.as("total_cost_usd"),
411
+ totalTokens: sql `SUM(COALESCE(${executions.inputTokens}, 0)
412
+ + COALESCE(${executions.outputTokens}, 0)
413
+ + COALESCE(${executions.cacheReadInputTokens}, 0))`.as("total_tokens"),
414
+ })
415
+ .from(executions)
416
+ .where(isNotNull(executions.workflowRunId))
417
+ .groupBy(executions.workflowRunId)
418
+ .as("agg");
346
419
  // Explicit column list — the heavy JSON blobs (`context`, `scratch`)
347
420
  // can each be many MB on long-running build runs and
348
421
  // the dashboard list view doesn't read them. Returning them turned a
349
422
  // 20-row page into a 14MB payload. The single-row endpoint
350
- // (`getRun`) still uses `SELECT *` so the detail panel keeps
351
- // the full row when the user picks one.
352
- // LEFT JOIN a per-run token/cost roll-up (indexed by
353
- // `idx_executions_workflow_run`). `agg` only exposes `workflow_run_id` +
354
- // the two sums, so the outer unqualified column names (and `whereClause`)
355
- // still bind unambiguously to `workflow_runs`.
356
- const rows = this.db
357
- .prepare(`SELECT
358
- id, workflow_name, trigger_id, owner, repo, issue_number,
359
- current_phase, phase_history, status,
360
- restart_count, started_at, updated_at, finished_at,
361
- triggered_by, trigger_actor_type,
362
- COALESCE(agg.total_cost_usd, 0) AS total_cost_usd,
363
- COALESCE(agg.total_tokens, 0) AS total_tokens
364
- FROM workflow_runs
365
- LEFT JOIN (
366
- SELECT workflow_run_id,
367
- SUM(COALESCE(cost_usd, 0)) AS total_cost_usd,
368
- SUM(COALESCE(input_tokens, 0)
369
- + COALESCE(output_tokens, 0)
370
- + COALESCE(cache_read_input_tokens, 0)) AS total_tokens
371
- FROM executions
372
- WHERE workflow_run_id IS NOT NULL
373
- GROUP BY workflow_run_id
374
- ) agg ON agg.workflow_run_id = workflow_runs.id
375
- ${whereClause}
376
- ORDER BY ${ACTIVE_FIRST}, started_at DESC
377
- LIMIT ? OFFSET ?`)
378
- .all(...params, limit, offset);
423
+ // (`getRun`) still selects the whole row so the detail panel keeps
424
+ // it when the user picks one.
425
+ const rows = await this.client
426
+ .select({
427
+ id: workflowRuns.id,
428
+ workflowName: workflowRuns.workflowName,
429
+ triggerId: workflowRuns.triggerId,
430
+ owner: workflowRuns.owner,
431
+ repo: workflowRuns.repo,
432
+ issueNumber: workflowRuns.issueNumber,
433
+ currentPhase: workflowRuns.currentPhase,
434
+ phaseHistory: workflowRuns.phaseHistory,
435
+ status: workflowRuns.status,
436
+ restartCount: workflowRuns.restartCount,
437
+ startedAt: workflowRuns.startedAt,
438
+ updatedAt: workflowRuns.updatedAt,
439
+ finishedAt: workflowRuns.finishedAt,
440
+ triggeredBy: workflowRuns.triggeredBy,
441
+ triggerActorType: workflowRuns.triggerActorType,
442
+ totalCostUsd: sql `COALESCE(${agg.totalCostUsd}, 0)`,
443
+ totalTokens: sql `COALESCE(${agg.totalTokens}, 0)`,
444
+ })
445
+ .from(workflowRuns)
446
+ .leftJoin(agg, eq(agg.workflowRunId, workflowRuns.id))
447
+ .where(whereClause)
448
+ .orderBy(ACTIVE_FIRST(this.t), desc(workflowRuns.startedAt))
449
+ .limit(limit)
450
+ .offset(offset);
379
451
  return {
380
452
  runs: rows.map((r) => this.deserialize(r)),
381
453
  total,
@@ -386,21 +458,26 @@ export class WorkflowRunStore {
386
458
  * since those are not holding a sandbox slot. Used by the concurrency cap
387
459
  * (issue #172) to decide whether to queue a fresh run.
388
460
  */
389
- countRunning() {
390
- const row = this.db
391
- .prepare(`SELECT COUNT(*) AS c FROM workflow_runs WHERE status = 'running'`)
392
- .get();
393
- return row.c;
461
+ async countRunning() {
462
+ const { workflowRuns } = this.t;
463
+ const [row] = await this.client
464
+ .select({ c: count() })
465
+ .from(workflowRuns)
466
+ .where(eq(workflowRuns.status, "running"));
467
+ return row?.c ?? 0;
394
468
  }
395
469
  /**
396
470
  * List all queued runs ordered by started_at ascending (FIFO enqueue order).
397
471
  * Used by the admission controller to pick the next run to promote and to
398
472
  * perform TTL expiry.
399
473
  */
400
- listQueued() {
401
- const rows = this.db
402
- .prepare(`SELECT * FROM workflow_runs WHERE status = 'queued' ORDER BY started_at ASC`)
403
- .all();
474
+ async listQueued() {
475
+ const { workflowRuns } = this.t;
476
+ const rows = await this.client
477
+ .select()
478
+ .from(workflowRuns)
479
+ .where(eq(workflowRuns.status, "queued"))
480
+ .orderBy(asc(workflowRuns.startedAt));
404
481
  return rows.map((r) => this.deserialize(r));
405
482
  }
406
483
  /**
@@ -412,44 +489,51 @@ export class WorkflowRunStore {
412
489
  * Does NOT touch started_at or restart_count — those stay at their enqueue
413
490
  * values so TTL sweep can detect staleness and dashboards show enqueue time.
414
491
  */
415
- admitRun(id) {
492
+ async admitRun(id) {
493
+ const { workflowRuns } = this.t;
416
494
  const now = new Date().toISOString();
417
- const info = this.db
418
- .prepare(`UPDATE workflow_runs
419
- SET status = 'running', updated_at = ?
420
- WHERE id = ? AND status = 'queued'`)
421
- .run(now, id);
422
- return info.changes;
495
+ const result = await this.client
496
+ .update(workflowRuns)
497
+ .set({ status: "running", updatedAt: now })
498
+ .where(and(eq(workflowRuns.id, id), eq(workflowRuns.status, "queued")));
499
+ return changes(result);
423
500
  }
424
501
  /**
425
502
  * CAS: transition a queued run to cancelled, recording the reason in
426
503
  * context.error. Returns the number of rows changed (1 on success, 0 if the
427
504
  * run was no longer queued). Used by the TTL sweep in the admission
428
505
  * controller to drop stale queued runs.
506
+ *
507
+ * The context annotation is an app-side read-modify-write (see
508
+ * {@link readContext}), but the write still carries the whole compare-and-set
509
+ * in its own `WHERE`, so the rows-affected count keeps its exact meaning. The
510
+ * read cannot go stale underneath it either: nothing else writes the context
511
+ * of a run that is still `queued`, and a run that stopped being queued loses
512
+ * the CAS.
429
513
  */
430
- expireQueued(id, reason) {
514
+ async expireQueued(id, reason) {
515
+ const { workflowRuns } = this.t;
431
516
  const now = new Date().toISOString();
432
- const info = this.db
433
- .prepare(`UPDATE workflow_runs
434
- SET status = 'cancelled',
435
- finished_at = ?,
436
- updated_at = ?,
437
- context = json_patch(COALESCE(context, '{}'), json_object('error', ?))
438
- WHERE id = ? AND status = 'queued'`)
439
- .run(now, now, reason, id);
517
+ const context = { ...(await this.readContext(id)), error: reason };
518
+ const changed = changes(await this.client
519
+ .update(workflowRuns)
520
+ .set({ status: "cancelled", finishedAt: now, updatedAt: now, context })
521
+ .where(and(eq(workflowRuns.id, id), eq(workflowRuns.status, "queued"))));
440
522
  // A queued run that expires never ran a phase, but it may already own a
441
523
  // `last-light/review` check — the whole point of hanging the projection off
442
524
  // the terminal transition is that this path resolves it for free.
443
- if (info.changes === 1)
444
- this.notifyTerminal(id, "cancelled");
445
- return info.changes;
525
+ if (changed === 1)
526
+ await this.notifyTerminal(id, "cancelled");
527
+ return changed;
446
528
  }
447
529
  /** Distinct workflow_name values, sorted alphabetically. */
448
- distinctNames() {
449
- const rows = this.db
450
- .prepare(`SELECT DISTINCT workflow_name FROM workflow_runs ORDER BY workflow_name ASC`)
451
- .all();
452
- return rows.map((r) => r.workflow_name);
530
+ async distinctNames() {
531
+ const { workflowRuns } = this.t;
532
+ const rows = await this.client
533
+ .selectDistinct({ workflowName: workflowRuns.workflowName })
534
+ .from(workflowRuns)
535
+ .orderBy(asc(workflowRuns.workflowName));
536
+ return rows.map((r) => r.workflowName);
453
537
  }
454
538
  /**
455
539
  * Per-repo run activity — one row per distinct `owner/repo`, with the run
@@ -466,15 +550,16 @@ export class WorkflowRunStore {
466
550
  * correctly: two rows for the same repo that disagree about shape collapse
467
551
  * into one bucket here rather than after the fact.
468
552
  */
469
- distinctRepos() {
470
- const qualified = qualifiedRepoSql("owner", "repo", "bare");
471
- return this.db
472
- .prepare(`SELECT ${qualified} AS repo, COUNT(*) AS runCount, MAX(started_at) AS lastRunAt
473
- FROM workflow_runs
474
- WHERE repo IS NOT NULL AND repo != ''
475
- GROUP BY ${qualified}
476
- ORDER BY lastRunAt DESC`)
477
- .all();
553
+ async distinctRepos() {
554
+ const { workflowRuns } = this.t;
555
+ const qualified = qualifiedRepoSql(workflowRuns.owner, workflowRuns.repo, "bare");
556
+ const lastRunAt = sql `MAX(${workflowRuns.startedAt})`;
557
+ return this.client
558
+ .select({ repo: sql `${qualified}`, runCount: count(), lastRunAt })
559
+ .from(workflowRuns)
560
+ .where(and(isNotNull(workflowRuns.repo), ne(workflowRuns.repo, "")))
561
+ .groupBy(qualified)
562
+ .orderBy(desc(lastRunAt));
478
563
  }
479
564
  /**
480
565
  * What Last Light did for ONE repo since `sinceIso` — a count per
@@ -486,74 +571,90 @@ export class WorkflowRunStore {
486
571
  * written before the owner/repo backfill carry `owner/repo` in the repo
487
572
  * column, and a bare-name filter silently misses every one of them.
488
573
  */
489
- summarizeRepoActivity(owner, repo, sinceIso) {
490
- const qualified = qualifiedRepoSql("owner", "repo", "bare");
491
- return this.db
492
- .prepare(`SELECT workflow_name AS workflowName, status, COUNT(*) AS count
493
- FROM workflow_runs
494
- WHERE ${qualified} = ?
495
- AND started_at >= ?
496
- GROUP BY workflow_name, status`)
497
- .all(`${owner}/${repo}`, sinceIso);
574
+ async summarizeRepoActivity(owner, repo, sinceIso) {
575
+ const { workflowRuns } = this.t;
576
+ const qualified = qualifiedRepoSql(workflowRuns.owner, workflowRuns.repo, "bare");
577
+ return this.client
578
+ .select({
579
+ workflowName: workflowRuns.workflowName,
580
+ status: workflowRuns.status,
581
+ count: count(),
582
+ })
583
+ .from(workflowRuns)
584
+ .where(and(eq(qualified, `${owner}/${repo}`), gte(workflowRuns.startedAt, sinceIso)))
585
+ .groupBy(workflowRuns.workflowName, workflowRuns.status);
498
586
  }
499
587
  /**
500
- * Mark a workflow run as finished. Plain status flip when called with just
501
- * `{ error }`; when a `terminalMarker` is supplied (the runner's
502
- * `on_success.set_phase`), the phase-history append and the status flip
503
- * happen in ONE transaction so the dashboard never sees the terminal phase
504
- * without the finished status, or vice versa.
588
+ * Mark a workflow run as finished. Plain status flip when called with
589
+ * neither an `error` nor a `terminalMarker`; with either, the work spans two
590
+ * statements — the phase-history append and/or the `context.error`
591
+ * read-modify-write, plus the status flip — so it runs in ONE transaction
592
+ * and the dashboard never sees the terminal phase without the finished
593
+ * status, or vice versa.
505
594
  */
506
- finishRun(id, status, opts = {}) {
507
- const apply = () => {
595
+ async finishRun(id, status, opts = {}) {
596
+ const apply = async (dbc) => {
508
597
  if (opts.terminalMarker) {
509
- this.appendPhase(id, opts.terminalMarker.phase, {
598
+ await this.appendPhase(id, opts.terminalMarker.phase, {
510
599
  phase: opts.terminalMarker.phase,
511
600
  timestamp: new Date().toISOString(),
512
601
  success: true,
513
602
  summary: opts.terminalMarker.summary,
514
- });
603
+ }, dbc);
515
604
  }
516
- this.flipFinished(id, status, opts.error);
605
+ await this.flipFinished(id, status, opts.error, dbc);
517
606
  };
518
- if (opts.terminalMarker) {
519
- this.db.transaction(apply)();
607
+ if (opts.terminalMarker || opts.error !== undefined) {
608
+ await this.serialize(() => this.client.transaction(async (tx) => apply(tx)));
520
609
  }
521
610
  else {
522
- apply();
611
+ await apply(this.client);
523
612
  }
524
613
  // AFTER the transaction commits — the observer reads the row back.
525
- this.notifyTerminal(id, status);
614
+ await this.notifyTerminal(id, status);
526
615
  }
527
- flipFinished(id, status, error) {
616
+ async flipFinished(id, status, error, dbc = this.client) {
617
+ const { workflowRuns } = this.t;
528
618
  const now = new Date().toISOString();
529
- this.db.prepare(`
530
- UPDATE workflow_runs SET status = ?, finished_at = ?, updated_at = ?, context = CASE
531
- WHEN ? IS NOT NULL THEN json_patch(COALESCE(context, '{}'), json_object('error', ?))
532
- ELSE context
533
- END WHERE id = ?
534
- `).run(status, now, now, error ?? null, error ?? null, id);
619
+ const patch = {
620
+ status,
621
+ finishedAt: now,
622
+ updatedAt: now,
623
+ };
624
+ // Only annotate the context when there is an error to record — the SQL this
625
+ // replaces expressed that as `CASE WHEN ? IS NOT NULL`, leaving the column
626
+ // untouched otherwise.
627
+ if (error !== undefined)
628
+ patch.context = { ...(await this.readContext(id, dbc)), error };
629
+ await dbc.update(workflowRuns).set(patch).where(eq(workflowRuns.id, id));
535
630
  }
536
631
  /** Cancel a workflow run */
537
- cancelRun(id) {
632
+ async cancelRun(id) {
633
+ const { workflowRuns } = this.t;
538
634
  const now = new Date().toISOString();
539
- this.db.prepare(`
540
- UPDATE workflow_runs SET status = 'cancelled', updated_at = ?, finished_at = ? WHERE id = ?
541
- `).run(now, now, id);
542
- this.notifyTerminal(id, "cancelled");
635
+ await this.client
636
+ .update(workflowRuns)
637
+ .set({ status: "cancelled", updatedAt: now, finishedAt: now })
638
+ .where(eq(workflowRuns.id, id));
639
+ await this.notifyTerminal(id, "cancelled");
543
640
  }
544
641
  /** Pause a workflow run (waiting for approval) */
545
- setPaused(id) {
642
+ async setPaused(id, dbc = this.client) {
643
+ const { workflowRuns } = this.t;
546
644
  const now = new Date().toISOString();
547
- this.db.prepare(`
548
- UPDATE workflow_runs SET status = 'paused', updated_at = ? WHERE id = ?
549
- `).run(now, id);
645
+ await dbc
646
+ .update(workflowRuns)
647
+ .set({ status: "paused", updatedAt: now })
648
+ .where(eq(workflowRuns.id, id));
550
649
  }
551
650
  /** Resume a paused workflow run (set back to running) */
552
- setRunning(id) {
651
+ async setRunning(id, dbc = this.client) {
652
+ const { workflowRuns } = this.t;
553
653
  const now = new Date().toISOString();
554
- this.db.prepare(`
555
- UPDATE workflow_runs SET status = 'running', updated_at = ? WHERE id = ?
556
- `).run(now, id);
654
+ await dbc
655
+ .update(workflowRuns)
656
+ .set({ status: "running", updatedAt: now })
657
+ .where(eq(workflowRuns.id, id));
557
658
  }
558
659
  /**
559
660
  * Restart a FAILED or CANCELLED run so it can be retried from where it
@@ -571,19 +672,27 @@ export class WorkflowRunStore {
571
672
  * `WHERE status IN ('failed','cancelled')` and returns the changed-row count
572
673
  * so the caller can make retry a compare-and-set: a second concurrent retry
573
674
  * click sees 0 rows changed and does NOT dispatch again.
675
+ *
676
+ * Clearing the error is an app-side read-modify-write now (see
677
+ * {@link readContext}); the CAS still rides on this one UPDATE, and a run in a
678
+ * terminal status has no other writer to race the read against.
574
679
  */
575
- restartRun(id) {
680
+ async restartRun(id) {
681
+ const { workflowRuns } = this.t;
576
682
  const now = new Date().toISOString();
577
- const info = this.db.prepare(`
578
- UPDATE workflow_runs
579
- SET status = 'running',
580
- finished_at = NULL,
581
- updated_at = ?,
582
- restart_count = COALESCE(restart_count, 0) + 1,
583
- context = json_remove(COALESCE(context, '{}'), '$.error')
584
- WHERE id = ? AND status IN ('failed', 'cancelled')
585
- `).run(now, id);
586
- return info.changes;
683
+ const context = await this.readContext(id);
684
+ delete context.error;
685
+ const result = await this.client
686
+ .update(workflowRuns)
687
+ .set({
688
+ status: "running",
689
+ finishedAt: null,
690
+ updatedAt: now,
691
+ restartCount: sql `COALESCE(${workflowRuns.restartCount}, 0) + 1`,
692
+ context,
693
+ })
694
+ .where(and(eq(workflowRuns.id, id), inArray(workflowRuns.status, ["failed", "cancelled"])));
695
+ return changes(result);
587
696
  }
588
697
  /**
589
698
  * Refresh a QUEUED run's enqueue clock to now. Used by boot recovery: a run
@@ -593,14 +702,14 @@ export class WorkflowRunStore {
593
702
  * `maxQueueWaitMs` window so the AdmissionController admits it normally as
594
703
  * slots free. CAS-guarded on `status = 'queued'`; returns rows changed.
595
704
  */
596
- requeue(id) {
705
+ async requeue(id) {
706
+ const { workflowRuns } = this.t;
597
707
  const now = new Date().toISOString();
598
- const info = this.db.prepare(`
599
- UPDATE workflow_runs
600
- SET started_at = ?, updated_at = ?
601
- WHERE id = ? AND status = 'queued'
602
- `).run(now, now, id);
603
- return info.changes;
708
+ const result = await this.client
709
+ .update(workflowRuns)
710
+ .set({ startedAt: now, updatedAt: now })
711
+ .where(and(eq(workflowRuns.id, id), eq(workflowRuns.status, "queued")));
712
+ return changes(result);
604
713
  }
605
714
  /**
606
715
  * Backpressure requeue: flip a RUNNING run back to `queued` and re-stamp its
@@ -612,14 +721,14 @@ export class WorkflowRunStore {
612
721
  * CAS-guarded on `status = 'running'`; returns rows changed (0 = safe no-op,
613
722
  * e.g. the run already finished or was cancelled between phases).
614
723
  */
615
- requeueRunning(id) {
724
+ async requeueRunning(id) {
725
+ const { workflowRuns } = this.t;
616
726
  const now = new Date().toISOString();
617
- const info = this.db.prepare(`
618
- UPDATE workflow_runs
619
- SET status = 'queued', started_at = ?, updated_at = ?
620
- WHERE id = ? AND status = 'running'
621
- `).run(now, now, id);
622
- return info.changes;
727
+ const result = await this.client
728
+ .update(workflowRuns)
729
+ .set({ status: "queued", startedAt: now, updatedAt: now })
730
+ .where(and(eq(workflowRuns.id, id), eq(workflowRuns.status, "running")));
731
+ return changes(result);
623
732
  }
624
733
  /**
625
734
  * Increment the restart counter and return the new value. Used by
@@ -627,55 +736,51 @@ export class WorkflowRunStore {
627
736
  * crashes the host (agent OOM, etc.) eventually self-terminates instead
628
737
  * of being re-dispatched on every boot.
629
738
  */
630
- incrementRestartCount(id) {
739
+ async incrementRestartCount(id) {
740
+ const { workflowRuns } = this.t;
631
741
  const now = new Date().toISOString();
632
- this.db.prepare(`
633
- UPDATE workflow_runs
634
- SET restart_count = COALESCE(restart_count, 0) + 1, updated_at = ?
635
- WHERE id = ?
636
- `).run(now, id);
637
- const row = this.db.prepare(`SELECT restart_count FROM workflow_runs WHERE id = ?`)
638
- .get(id);
639
- return row?.restart_count ?? 0;
742
+ // RETURNING collapses the old update-then-select pair into one statement —
743
+ // and one round trip — while keeping the read of the value this call wrote.
744
+ const [row] = await this.client
745
+ .update(workflowRuns)
746
+ .set({
747
+ restartCount: sql `COALESCE(${workflowRuns.restartCount}, 0) + 1`,
748
+ updatedAt: now,
749
+ })
750
+ .where(eq(workflowRuns.id, id))
751
+ .returning({ restartCount: workflowRuns.restartCount });
752
+ return row?.restartCount ?? 0;
640
753
  }
641
754
  deserialize(row) {
755
+ // Builder rows are camelCase, the json-mode columns arrive as real objects
756
+ // and arrays, and `nullsToUndefined` turns the nullable columns into the
757
+ // absent optionals `WorkflowRun` declares.
758
+ const r = nullsToUndefined(row);
642
759
  // The compatibility shim for the (owner, BARE repo) invariant (issue #279).
643
760
  // The backfill converges stored rows and `createRun` keeps new ones honest,
644
761
  // so this only ever fires for a row written by an older process before the
645
762
  // migration ran — but it fires at the ONE boundary every consumer crosses,
646
763
  // which is what lets `admission.ts` and `feedback-poll.ts` hand
647
764
  // `(run.owner, run.repo)` straight to Octokit with no split of their own.
648
- const ref = normalizeRepoRef(row.owner, row.repo);
765
+ const ref = normalizeRepoRef(r.owner, r.repo);
649
766
  return {
650
- id: row.id,
651
- workflowName: row.workflow_name,
652
- triggerId: row.trigger_id,
767
+ ...r,
653
768
  owner: ref.owner,
654
769
  repo: ref.repo,
655
- issueNumber: row.issue_number,
656
- triggeredBy: row.triggered_by ?? undefined,
657
- triggerActorType: row.trigger_actor_type ?? undefined,
658
- currentPhase: row.current_phase,
659
- phaseHistory: JSON.parse(row.phase_history),
660
- status: row.status,
661
- context: row.context ? JSON.parse(row.context) : undefined,
662
- scratch: row.scratch ? JSON.parse(row.scratch) : undefined,
663
- restartCount: typeof row.restart_count === "number" ? row.restart_count : 0,
664
- startedAt: row.started_at,
665
- updatedAt: row.updated_at,
666
- finishedAt: row.finished_at,
667
- traceId: row.trace_id ?? undefined,
668
- spanId: row.span_id ?? undefined,
669
- // Present only on `list()` rows (the executions JOIN); undefined on getRun.
670
- totalCostUsd: typeof row.total_cost_usd === "number" ? row.total_cost_usd : undefined,
671
- totalTokens: typeof row.total_tokens === "number" ? row.total_tokens : undefined,
770
+ status: r.status,
771
+ triggerActorType: r.triggerActorType,
772
+ restartCount: r.restartCount ?? 0,
773
+ // `totalCostUsd` / `totalTokens` are present only on `list()` rows (the
774
+ // executions JOIN) and absent everywhere else — the spread carries both.
672
775
  };
673
776
  }
674
777
  // ── Named atomic lifecycle operations ──────────────────────────
675
778
  //
676
- // Each wraps ONE better-sqlite3 transaction. The long-running re-dispatch
779
+ // Each wraps ONE transaction, taken through the connection-scoped
780
+ // {@link OpSerializer} so two of them (or one of TeamStore's) cannot
781
+ // interleave on the shared client. The long-running re-dispatch
677
782
  // (`dispatchWorkflow`) stays OUT of these — the caller dispatches after the
678
- // transaction commits.
783
+ // op returns.
679
784
  /**
680
785
  * Resolve a socratic reply gate and resume the run, atomically: the reply
681
786
  * gate flips `pending → approved` (recording the reply text), the caller's
@@ -704,19 +809,19 @@ export class WorkflowRunStore {
704
809
  * ApprovalStore participates in the same transaction); ordering is invisible
705
810
  * outside the transaction.
706
811
  */
707
- pauseForApproval(runId, approval, marker, scratchPatch) {
708
- this.db.transaction(() => {
709
- this.appendPhase(runId, marker.phase, {
812
+ async pauseForApproval(runId, approval, marker, scratchPatch) {
813
+ await this.serialize(() => this.client.transaction(async (tx) => {
814
+ await this.appendPhase(runId, marker.phase, {
710
815
  phase: marker.phase,
711
816
  timestamp: new Date().toISOString(),
712
817
  success: true,
713
818
  summary: marker.summary,
714
- });
819
+ }, tx);
715
820
  if (scratchPatch)
716
- this.mergeScratch(runId, scratchPatch);
717
- this.approvals.create(approval);
718
- this.setPaused(runId);
719
- })();
821
+ await this.mergeScratch(runId, scratchPatch, tx);
822
+ await this.approvals.create(approval, tx);
823
+ await this.setPaused(runId, tx);
824
+ }));
720
825
  }
721
826
  /**
722
827
  * Approve a gate and resume its run, atomically. Reads the approval to find
@@ -728,47 +833,47 @@ export class WorkflowRunStore {
728
833
  * will follow before responding, so it records the approval and lets
729
834
  * `resumeWorkflow` flip the run only as part of an actual dispatch.
730
835
  */
731
- resolveGateAndResume(approvalId, responder) {
732
- return this.db.transaction(() => {
733
- const approval = this.approvals.getById(approvalId);
836
+ async resolveGateAndResume(approvalId, responder) {
837
+ return this.serialize(() => this.client.transaction(async (tx) => {
838
+ const approval = await this.approvals.getById(approvalId, tx);
734
839
  if (!approval)
735
840
  throw new Error(`approval ${approvalId} not found`);
736
- const changed = this.approvals.respond(approvalId, "approved", responder);
841
+ const changed = await this.approvals.respond(approvalId, "approved", responder, undefined, tx);
737
842
  if (changed !== 1) {
738
843
  throw new Error(`approval ${approvalId} is not pending (already resolved?)`);
739
844
  }
740
- this.setRunning(approval.workflowRunId);
741
- return this.getRun(approval.workflowRunId);
742
- })();
845
+ await this.setRunning(approval.workflowRunId, tx);
846
+ return this.getRun(approval.workflowRunId, tx);
847
+ }));
743
848
  }
744
849
  /**
745
850
  * Reject a gate and fail its run, atomically: record the `rejected` response
746
851
  * (with reason) and flip the run to `failed` in one transaction. Returns the
747
852
  * run (or null if the approval's run was already gone).
748
853
  */
749
- resolveGateAndFail(approvalId, responder, reason) {
750
- return this.db.transaction(() => {
751
- const approval = this.approvals.getById(approvalId);
854
+ async resolveGateAndFail(approvalId, responder, reason) {
855
+ return this.serialize(() => this.client.transaction(async (tx) => {
856
+ const approval = await this.approvals.getById(approvalId, tx);
752
857
  if (!approval)
753
858
  throw new Error(`approval ${approvalId} not found`);
754
- const changed = this.approvals.respond(approvalId, "rejected", responder, reason);
859
+ const changed = await this.approvals.respond(approvalId, "rejected", responder, reason, tx);
755
860
  if (changed !== 1) {
756
861
  throw new Error(`approval ${approvalId} is not pending (already resolved?)`);
757
862
  }
758
- this.flipFinished(approval.workflowRunId, "failed", `Rejected: ${reason || "no reason given"}`);
759
- return this.getRun(approval.workflowRunId);
760
- })();
863
+ await this.flipFinished(approval.workflowRunId, "failed", `Rejected: ${reason || "no reason given"}`, tx);
864
+ return this.getRun(approval.workflowRunId, tx);
865
+ }));
761
866
  }
762
- resolveReplyGateAndResume(runId, approvalId, replyText, responder, scratchPatch) {
763
- return this.db.transaction(() => {
764
- const changed = this.approvals.resolveReplyGate(approvalId, replyText, responder);
867
+ async resolveReplyGateAndResume(runId, approvalId, replyText, responder, scratchPatch) {
868
+ return this.serialize(() => this.client.transaction(async (tx) => {
869
+ const changed = await this.approvals.resolveReplyGate(approvalId, replyText, responder, tx);
765
870
  if (changed !== 1) {
766
871
  throw new Error(`reply gate ${approvalId} is not pending (already resolved?)`);
767
872
  }
768
- this.mergeScratch(runId, scratchPatch);
769
- this.setRunning(runId);
770
- return this.getRun(runId);
771
- })();
873
+ await this.mergeScratch(runId, scratchPatch, tx);
874
+ await this.setRunning(runId, tx);
875
+ return this.getRun(runId, tx);
876
+ }));
772
877
  }
773
878
  }
774
879
  //# sourceMappingURL=workflow-run-store.js.map