lastlight-core 0.25.9 → 0.26.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 (157) hide show
  1. package/config/default.yaml +20 -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/routes.js +97 -99
  6. package/dist/admin/routes.js.map +1 -1
  7. package/dist/admin/sessions.d.ts +7 -7
  8. package/dist/admin/sessions.js +6 -4
  9. package/dist/admin/sessions.js.map +1 -1
  10. package/dist/config/config.d.ts +15 -0
  11. package/dist/config/config.js +28 -0
  12. package/dist/config/config.js.map +1 -1
  13. package/dist/config/repo-config.js +6 -7
  14. package/dist/config/repo-config.js.map +1 -1
  15. package/dist/connectors/messaging/base.js +2 -2
  16. package/dist/connectors/messaging/base.js.map +1 -1
  17. package/dist/connectors/messaging/session-manager.d.ts +29 -31
  18. package/dist/connectors/messaging/session-manager.js +156 -189
  19. package/dist/connectors/messaging/session-manager.js.map +1 -1
  20. package/dist/connectors/messaging/thread-transcript.d.ts +2 -2
  21. package/dist/connectors/messaging/thread-transcript.js +14 -8
  22. package/dist/connectors/messaging/thread-transcript.js.map +1 -1
  23. package/dist/connectors/slack/connector.js +5 -5
  24. package/dist/connectors/slack/connector.js.map +1 -1
  25. package/dist/cron/feedback-poll.js +6 -6
  26. package/dist/cron/feedback-poll.js.map +1 -1
  27. package/dist/cron/handlers.js +3 -3
  28. package/dist/cron/handlers.js.map +1 -1
  29. package/dist/cron/jobs.d.ts +1 -1
  30. package/dist/cron/jobs.js +2 -2
  31. package/dist/cron/jobs.js.map +1 -1
  32. package/dist/cron/repo-digest.js +4 -4
  33. package/dist/cron/repo-digest.js.map +1 -1
  34. package/dist/cron/runner.js +2 -2
  35. package/dist/cron/runner.js.map +1 -1
  36. package/dist/cron/scheduler.js +1 -1
  37. package/dist/cron/scheduler.js.map +1 -1
  38. package/dist/engine/chat/chat-prompt.d.ts +11 -4
  39. package/dist/engine/chat/chat-prompt.js.map +1 -1
  40. package/dist/engine/chat/chat-runner.d.ts +3 -2
  41. package/dist/engine/chat/chat-runner.js +9 -7
  42. package/dist/engine/chat/chat-runner.js.map +1 -1
  43. package/dist/engine/dispatcher.js +29 -25
  44. package/dist/engine/dispatcher.js.map +1 -1
  45. package/dist/engine/executors/orchestrator.d.ts +28 -0
  46. package/dist/engine/executors/orchestrator.js +70 -1
  47. package/dist/engine/executors/orchestrator.js.map +1 -1
  48. package/dist/engine/feedback/ingest.d.ts +4 -4
  49. package/dist/engine/feedback/ingest.js +13 -13
  50. package/dist/engine/feedback/ingest.js.map +1 -1
  51. package/dist/engine/feedback/slack.d.ts +2 -2
  52. package/dist/engine/feedback/slack.js +6 -6
  53. package/dist/engine/feedback/slack.js.map +1 -1
  54. package/dist/engine/fix-harvest.d.ts +1 -1
  55. package/dist/engine/fix-harvest.js +3 -3
  56. package/dist/engine/fix-harvest.js.map +1 -1
  57. package/dist/engine/github/team-visibility.js +7 -7
  58. package/dist/engine/github/team-visibility.js.map +1 -1
  59. package/dist/engine/pr-escalation.js +7 -7
  60. package/dist/engine/pr-escalation.js.map +1 -1
  61. package/dist/engine/pr-state.d.ts +1 -1
  62. package/dist/engine/pr-state.js +12 -10
  63. package/dist/engine/pr-state.js.map +1 -1
  64. package/dist/engine/review-check.d.ts +1 -1
  65. package/dist/engine/review-check.js +5 -5
  66. package/dist/engine/review-check.js.map +1 -1
  67. package/dist/engine/router.js +3 -3
  68. package/dist/engine/router.js.map +1 -1
  69. package/dist/index.js +108 -65
  70. package/dist/index.js.map +1 -1
  71. package/dist/sandbox/docker.d.ts +33 -1
  72. package/dist/sandbox/docker.js +95 -1
  73. package/dist/sandbox/docker.js.map +1 -1
  74. package/dist/sandbox/k8s/kubernetes-sandbox.d.ts +3 -0
  75. package/dist/sandbox/k8s/kubernetes-sandbox.js +9 -0
  76. package/dist/sandbox/k8s/kubernetes-sandbox.js.map +1 -1
  77. package/dist/sandbox/k8s/pod.d.ts +11 -0
  78. package/dist/sandbox/k8s/pod.js +11 -6
  79. package/dist/sandbox/k8s/pod.js.map +1 -1
  80. package/dist/sandbox/k8s/service-containers.d.ts +43 -0
  81. package/dist/sandbox/k8s/service-containers.js +87 -0
  82. package/dist/sandbox/k8s/service-containers.js.map +1 -0
  83. package/dist/sandbox/reap.d.ts +9 -0
  84. package/dist/sandbox/reap.js +36 -0
  85. package/dist/sandbox/reap.js.map +1 -1
  86. package/dist/sandbox/sandbox.d.ts +14 -0
  87. package/dist/sandbox/sandbox.js +9 -0
  88. package/dist/sandbox/sandbox.js.map +1 -1
  89. package/dist/sandbox/service-containers-docker.d.ts +45 -0
  90. package/dist/sandbox/service-containers-docker.js +78 -0
  91. package/dist/sandbox/service-containers-docker.js.map +1 -0
  92. package/dist/state/approval-store.d.ts +23 -14
  93. package/dist/state/approval-store.js +137 -86
  94. package/dist/state/approval-store.js.map +1 -1
  95. package/dist/state/client.d.ts +105 -0
  96. package/dist/state/client.js +68 -0
  97. package/dist/state/client.js.map +1 -0
  98. package/dist/state/cron-run-store.d.ts +32 -12
  99. package/dist/state/cron-run-store.js +105 -39
  100. package/dist/state/cron-run-store.js.map +1 -1
  101. package/dist/state/db.d.ts +61 -23
  102. package/dist/state/db.js +171 -105
  103. package/dist/state/db.js.map +1 -1
  104. package/dist/state/dialect.d.ts +77 -0
  105. package/dist/state/dialect.js +129 -0
  106. package/dist/state/dialect.js.map +1 -0
  107. package/dist/state/execution-store.d.ts +124 -103
  108. package/dist/state/execution-store.js +569 -374
  109. package/dist/state/execution-store.js.map +1 -1
  110. package/dist/state/feedback-store.d.ts +20 -20
  111. package/dist/state/feedback-store.js +241 -187
  112. package/dist/state/feedback-store.js.map +1 -1
  113. package/dist/state/legacy-sqlite.d.ts +15 -0
  114. package/dist/state/legacy-sqlite.js +131 -0
  115. package/dist/state/legacy-sqlite.js.map +1 -0
  116. package/dist/state/repo-ref.d.ts +9 -4
  117. package/dist/state/repo-ref.js +12 -6
  118. package/dist/state/repo-ref.js.map +1 -1
  119. package/dist/state/schema/pg.d.ts +2788 -0
  120. package/dist/state/schema/pg.js +301 -0
  121. package/dist/state/schema/pg.js.map +1 -0
  122. package/dist/state/schema/sqlite.d.ts +3063 -0
  123. package/dist/state/schema/sqlite.js +391 -0
  124. package/dist/state/schema/sqlite.js.map +1 -0
  125. package/dist/state/team-store.d.ts +26 -13
  126. package/dist/state/team-store.js +140 -93
  127. package/dist/state/team-store.js.map +1 -1
  128. package/dist/state/user-store.d.ts +31 -13
  129. package/dist/state/user-store.js +180 -80
  130. package/dist/state/user-store.js.map +1 -1
  131. package/dist/state/workflow-run-store.d.ts +95 -56
  132. package/dist/state/workflow-run-store.js +419 -314
  133. package/dist/state/workflow-run-store.js.map +1 -1
  134. package/dist/workflows/admission.d.ts +4 -3
  135. package/dist/workflows/admission.js +34 -10
  136. package/dist/workflows/admission.js.map +1 -1
  137. package/dist/workflows/handlers/post-review.js +3 -3
  138. package/dist/workflows/handlers/post-review.js.map +1 -1
  139. package/dist/workflows/resume.js +22 -15
  140. package/dist/workflows/resume.js.map +1 -1
  141. package/dist/workflows/runner.js +27 -12
  142. package/dist/workflows/runner.js.map +1 -1
  143. package/dist/workflows/simple.d.ts +23 -0
  144. package/dist/workflows/simple.js +40 -16
  145. package/dist/workflows/simple.js.map +1 -1
  146. package/drizzle/pg/0000_init.sql +235 -0
  147. package/drizzle/pg/meta/0000_snapshot.json +1751 -0
  148. package/drizzle/pg/meta/_journal.json +13 -0
  149. package/drizzle/sqlite/0000_baseline.sql +257 -0
  150. package/drizzle/sqlite/0001_backfill_repo_refs.sql +74 -0
  151. package/drizzle/sqlite/meta/0000_snapshot.json +1593 -0
  152. package/drizzle/sqlite/meta/0001_snapshot.json +1593 -0
  153. package/drizzle/sqlite/meta/_journal.json +20 -0
  154. package/package.json +12 -6
  155. package/dist/state/migrate.d.ts +0 -15
  156. package/dist/state/migrate.js +0 -518
  157. package/dist/state/migrate.js.map +0 -1
@@ -1,4 +1,7 @@
1
1
  import { randomUUID } from "crypto";
2
+ import { and, count, desc, eq, gte, inArray, isNotNull, isNull, like, sql } from "drizzle-orm";
3
+ import { nullsToUndefined, tablesOf } from "./client.js";
4
+ import { changes, dayBucket, hourBucket, likeEscape, rows, run, sumTrue } from "./dialect.js";
2
5
  import { normalizeRepoRef, qualifiedRepoSql } from "./repo-ref.js";
3
6
  /**
4
7
  * Owns every read/write against the `executions` table — the harness's
@@ -7,8 +10,9 @@ import { normalizeRepoRef, qualifiedRepoSql } from "./repo-ref.js";
7
10
  * runner's resume path skips already-completed phases via {@link shouldRunPhase}.
8
11
  *
9
12
  * Carved out of the old `StateDb` god-class (issue #97). Constructed from the
10
- * single shared `Database` so it sits in the same connection / transaction
11
- * scope as the other stores.
13
+ * single shared Drizzle client so it sits in the same connection scope as the
14
+ * other stores. It is never a transaction participant — no method takes a
15
+ * `dbc` — because nothing else has to move atomically with a ledger append.
12
16
  */
13
17
  /**
14
18
  * `executions.repo`, composed into the qualified `owner/repo` a user-facing
@@ -22,56 +26,135 @@ import { normalizeRepoRef, qualifiedRepoSql } from "./repo-ref.js";
22
26
  * **NULL is the safe answer, and deliberate.** A consumer of this treats null
23
27
  * as "no repo, always visible"; returning a bare name instead would produce a
24
28
  * value that matches nothing in a qualified allow-list and would therefore
25
- * HIDE the row. Requires the alias to be `e` (executions).
29
+ * HIDE the row. It embeds the schema columns, which render fully qualified
30
+ * (`"executions"."owner"`), so any raw query using it must select from
31
+ * `executions` UNALIASED — the old `e` alias is gone.
26
32
  */
27
- const QUALIFIED_REPO_SQL = qualifiedRepoSql("e.owner", "e.repo", "null");
33
+ const qualifiedRepoOrNull = ({ executions }) => qualifiedRepoSql(executions.owner, executions.repo, "null");
28
34
  /**
29
- * The column list every read that returns an {@link ExecutionRecord} selects.
35
+ * The columns every BUILDER read that returns an {@link ExecutionRecord}
36
+ * selects.
30
37
  *
31
- * The table is snake_case and the record is camelCase, so `SELECT *` does not
32
- * produce an `ExecutionRecord` — it produces a row that *looks* like one for
33
- * the handful of single-word columns and silently leaves `issueNumber`,
34
- * `startedAt` and `workflowRunId` `undefined` (issue #285). Three reads did
35
- * exactly that, and the cast to `ExecutionRecord[]` made the compiler agree.
36
- * The Slack status report rendered `(started undefined)` and the admin cancel
37
- * loop filtered on a `workflowRunId` that never matched a row.
38
+ * Named explicitly rather than `.select()`-ing the whole row so `output_text`
39
+ * — which is not part of the record and can hold a full LLM response — never
40
+ * rides along on a list read.
38
41
  *
39
- * So the aliasing lives in ONE place rather than being re-typed per query, and
40
- * {@link mapExecutionRow} is its other half — a new column is added to both or
41
- * to neither. No table alias is used, so this works in any single-table query.
42
+ * Its raw-SQL twin is {@link executionColumnsSql}, and {@link deserialize} /
43
+ * {@link mapExecutionRow} are their respective other halves. A new column is
44
+ * added to all four or to none.
42
45
  */
43
- const EXECUTION_COLUMNS = `
44
- id,
45
- trigger_type AS triggerType,
46
- trigger_id AS triggerId,
47
- triggered_by AS triggeredBy,
48
- trigger_actor_type AS triggerActorType,
49
- skill,
50
- owner,
51
- repo,
52
- issue_number AS issueNumber,
53
- started_at AS startedAt,
54
- finished_at AS finishedAt,
55
- success,
56
- error,
57
- turns,
58
- duration_ms AS durationMs,
59
- session_id AS sessionId,
60
- cost_usd AS costUsd,
61
- input_tokens AS inputTokens,
62
- cache_creation_input_tokens AS cacheCreationInputTokens,
63
- cache_read_input_tokens AS cacheReadInputTokens,
64
- output_tokens AS outputTokens,
65
- api_duration_ms AS apiDurationMs,
66
- stop_reason AS stopReason,
67
- extension_status AS extensionStatus,
68
- skills_status AS skillsStatus,
69
- workflow_run_id AS workflowRunId
46
+ const executionColumns = ({ executions }) => ({
47
+ id: executions.id,
48
+ triggerType: executions.triggerType,
49
+ triggerId: executions.triggerId,
50
+ triggeredBy: executions.triggeredBy,
51
+ triggerActorType: executions.triggerActorType,
52
+ skill: executions.skill,
53
+ owner: executions.owner,
54
+ repo: executions.repo,
55
+ issueNumber: executions.issueNumber,
56
+ startedAt: executions.startedAt,
57
+ finishedAt: executions.finishedAt,
58
+ success: executions.success,
59
+ error: executions.error,
60
+ turns: executions.turns,
61
+ durationMs: executions.durationMs,
62
+ sessionId: executions.sessionId,
63
+ costUsd: executions.costUsd,
64
+ inputTokens: executions.inputTokens,
65
+ cacheCreationInputTokens: executions.cacheCreationInputTokens,
66
+ cacheReadInputTokens: executions.cacheReadInputTokens,
67
+ outputTokens: executions.outputTokens,
68
+ apiDurationMs: executions.apiDurationMs,
69
+ stopReason: executions.stopReason,
70
+ extensionStatus: executions.extensionStatus,
71
+ skillsStatus: executions.skillsStatus,
72
+ workflowRunId: executions.workflowRunId,
73
+ });
74
+ /**
75
+ * Turn a BUILDER row into an {@link ExecutionRecord}.
76
+ *
77
+ * The builder already did the hard parts — camelCase names, a real boolean for
78
+ * `success`, the two status columns parsed into objects — so this is down to
79
+ * turning nulls into absent optionals and narrowing the two free-text columns
80
+ * the schema types as plain `string`.
81
+ */
82
+ function deserialize(row) {
83
+ const r = nullsToUndefined(row);
84
+ return {
85
+ ...r,
86
+ triggerType: r.triggerType,
87
+ triggerActorType: r.triggerActorType,
88
+ };
89
+ }
90
+ /**
91
+ * The column list every RAW read that returns an {@link ExecutionRecord}
92
+ * selects — the `sql` twin of {@link executionColumns}.
93
+ *
94
+ * The table is snake_case and the record is camelCase, so an unaliased raw
95
+ * `SELECT *` does not produce an `ExecutionRecord` — it produces a row that
96
+ * *looks* like one for the handful of single-word columns and silently leaves
97
+ * `issueNumber`, `startedAt` and `workflowRunId` `undefined` (issue #285).
98
+ * Three reads did exactly that, and the cast to `ExecutionRecord[]` made the
99
+ * compiler agree.
100
+ *
101
+ * Every alias is DOUBLE-QUOTED: Postgres folds an unquoted `AS triggerId` to
102
+ * `triggerid`, which would resurrect issue #285 the moment the pg leg runs.
103
+ * The columns render fully qualified, so the query must not alias the table.
104
+ */
105
+ const executionColumnsSql = ({ executions }) => sql `
106
+ ${executions.id} AS "id",
107
+ ${executions.triggerType} AS "triggerType",
108
+ ${executions.triggerId} AS "triggerId",
109
+ ${executions.triggeredBy} AS "triggeredBy",
110
+ ${executions.triggerActorType} AS "triggerActorType",
111
+ ${executions.skill} AS "skill",
112
+ ${executions.owner} AS "owner",
113
+ ${executions.repo} AS "repo",
114
+ ${executions.issueNumber} AS "issueNumber",
115
+ ${executions.startedAt} AS "startedAt",
116
+ ${executions.finishedAt} AS "finishedAt",
117
+ ${executions.success} AS "success",
118
+ ${executions.error} AS "error",
119
+ ${executions.turns} AS "turns",
120
+ ${executions.durationMs} AS "durationMs",
121
+ ${executions.sessionId} AS "sessionId",
122
+ ${executions.costUsd} AS "costUsd",
123
+ ${executions.inputTokens} AS "inputTokens",
124
+ ${executions.cacheCreationInputTokens} AS "cacheCreationInputTokens",
125
+ ${executions.cacheReadInputTokens} AS "cacheReadInputTokens",
126
+ ${executions.outputTokens} AS "outputTokens",
127
+ ${executions.apiDurationMs} AS "apiDurationMs",
128
+ ${executions.stopReason} AS "stopReason",
129
+ ${executions.extensionStatus} AS "extensionStatus",
130
+ ${executions.skillsStatus} AS "skillsStatus",
131
+ ${executions.workflowRunId} AS "workflowRunId"
70
132
  `;
71
133
  /**
72
- * Turn a row selected with {@link EXECUTION_COLUMNS} into an
73
- * {@link ExecutionRecord}: SQLite NULLs become `undefined` (the record's
74
- * optional fields) and the `success` integer becomes a boolean.
134
+ * Parse one of the two JSON status columns off a RAW row.
135
+ *
136
+ * Raw rows bypass Drizzle's column mapping entirely, so a `{ mode: "json" }`
137
+ * column arrives as the TEXT it is stored as and has to be parsed here.
138
+ * Malformed JSON yields `undefined` rather than throwing — one bad row must
139
+ * not take out the whole executions list.
140
+ */
141
+ function parseStatusJson(value) {
142
+ if (value === null || value === undefined)
143
+ return undefined;
144
+ if (typeof value !== "string")
145
+ return value;
146
+ try {
147
+ return JSON.parse(value);
148
+ }
149
+ catch {
150
+ return undefined;
151
+ }
152
+ }
153
+ /**
154
+ * Turn a row selected with {@link executionColumnsSql} into an
155
+ * {@link ExecutionRecord}: NULLs become `undefined` (the record's optional
156
+ * fields), the raw `success` integer becomes a boolean, and the two JSON
157
+ * columns are parsed by hand — none of which a raw query does for you.
75
158
  */
76
159
  function mapExecutionRow(r) {
77
160
  const nul = (v) => (v === null || v === undefined ? undefined : v);
@@ -99,8 +182,8 @@ function mapExecutionRow(r) {
99
182
  outputTokens: nul(r.outputTokens),
100
183
  apiDurationMs: nul(r.apiDurationMs),
101
184
  stopReason: nul(r.stopReason),
102
- extensionStatus: nul(r.extensionStatus),
103
- skillsStatus: nul(r.skillsStatus),
185
+ extensionStatus: parseStatusJson(r.extensionStatus),
186
+ skillsStatus: parseStatusJson(r.skillsStatus),
104
187
  workflowRunId: nul(r.workflowRunId),
105
188
  };
106
189
  }
@@ -109,10 +192,10 @@ function mapExecutionRow(r) {
109
192
  * selects (issue #325).
110
193
  *
111
194
  * `executions.success` is not a health signal and must not be read as one.
112
- * Two paths write `success = 0` deliberately, having failed at nothing:
195
+ * Two paths write `success = false` deliberately, having failed at nothing:
113
196
  *
114
197
  * - **`skipped`** — {@link ExecutionStore.recordSkippedPhase}. Stored
115
- * `success = 0` so {@link ExecutionStore.shouldRunPhase} re-evaluates the
198
+ * `success = false` so {@link ExecutionStore.shouldRunPhase} re-evaluates the
116
199
  * node on resume. The phase never ran.
117
200
  * - **`error_quota`** — the k8s `ResourceQuota` rejected the pod. The runner
118
201
  * treats it as an ordinary phase failure precisely so the run REQUEUES
@@ -130,26 +213,36 @@ function mapExecutionRow(r) {
130
213
  *
131
214
  * `success IS NULL` (still in flight) matches no bucket on purpose: it counts
132
215
  * toward `COUNT(*)` and toward nothing else, so a stacked bar can legitimately
133
- * be shorter than the execution total.
216
+ * be shorter than the execution total. That is why every arm goes through
217
+ * {@link sumTrue} — a `CASE WHEN <predicate>` where NULL falls to the ELSE in
218
+ * both dialects — and why the three that test for failure compare against a
219
+ * BOUND `${false}` rather than a literal `0`, which Postgres rejects outright
220
+ * (`operator does not exist: boolean = integer`).
134
221
  *
135
222
  * Note `condition_not_met` — a generic-loop `until_bash` check that ran and
136
- * came back red — is stored `success = 1` and therefore lands in `succeeded`.
137
- * It really executed and really cost tokens; only its per-row rendering is
138
- * muted (`execMark`, `packages/cli/src/cli-format.ts`).
223
+ * came back red — is stored `success = true` and therefore lands in
224
+ * `succeeded`. It really executed and really cost tokens; only its per-row
225
+ * rendering is muted (`execMark`, `packages/cli/src/cli-format.ts`).
139
226
  */
140
- export const EXECUTION_OUTCOME_COLUMNS = `
141
- SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) AS succeeded,
142
- SUM(CASE WHEN success = 0 AND stop_reason = 'skipped' THEN 1 ELSE 0 END) AS skipped,
143
- SUM(CASE WHEN success = 0 AND stop_reason = 'error_quota' THEN 1 ELSE 0 END) AS deferred,
144
- SUM(CASE WHEN success = 0
145
- AND (stop_reason IS NULL OR stop_reason NOT IN ('skipped', 'error_quota'))
146
- THEN 1 ELSE 0 END) AS failed`;
227
+ export const executionOutcomeColumns = ({ executions }) => sql `
228
+ ${sumTrue(executions.success)} AS "succeeded",
229
+ ${sumTrue(sql `${executions.success} = ${false} AND ${executions.stopReason} = 'skipped'`)} AS "skipped",
230
+ ${sumTrue(sql `${executions.success} = ${false} AND ${executions.stopReason} = 'error_quota'`)} AS "deferred",
231
+ ${sumTrue(sql `${executions.success} = ${false}
232
+ AND (${executions.stopReason} IS NULL OR ${executions.stopReason} NOT IN ('skipped', 'error_quota'))`)} AS "failed"`;
147
233
  /** Zero-fill for a bucket with no executions in it. */
148
234
  const NO_OUTCOMES = { succeeded: 0, skipped: 0, deferred: 0, failed: 0 };
149
235
  export class ExecutionStore {
150
- db;
151
- constructor(db) {
152
- this.db = db;
236
+ client;
237
+ /**
238
+ * Table objects for THIS client's dialect. Every method destructures what it
239
+ * needs off this instead of importing from `schema/sqlite.js` — see
240
+ * `client.ts` → {@link tablesOf} for why the cast alone cannot do it.
241
+ */
242
+ t;
243
+ constructor(client) {
244
+ this.client = client;
245
+ this.t = tablesOf(client);
153
246
  }
154
247
  /**
155
248
  * Append a started phase to the ledger.
@@ -160,20 +253,31 @@ export class ExecutionStore {
160
253
  * qualified value from anywhere else is normalized rather than stored as a
161
254
  * second shape.
162
255
  */
163
- recordStart(record) {
256
+ async recordStart(record) {
257
+ const { executions } = this.t;
164
258
  const ref = normalizeRepoRef(record.owner, record.repo);
165
- this.db.prepare(`
166
- INSERT INTO executions (id, trigger_type, trigger_id, skill, owner, repo, issue_number, started_at, workflow_run_id, triggered_by, trigger_actor_type)
167
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
168
- `).run(record.id, record.triggerType, record.triggerId, record.skill, ref.owner ?? null, ref.repo ?? null, record.issueNumber, record.startedAt, record.workflowRunId ?? null, record.triggeredBy ?? null, record.triggerActorType ?? null);
259
+ await this.client.insert(executions).values({
260
+ id: record.id,
261
+ triggerType: record.triggerType,
262
+ triggerId: record.triggerId,
263
+ skill: record.skill,
264
+ owner: ref.owner ?? null,
265
+ repo: ref.repo ?? null,
266
+ issueNumber: record.issueNumber ?? null,
267
+ startedAt: record.startedAt,
268
+ workflowRunId: record.workflowRunId ?? null,
269
+ triggeredBy: record.triggeredBy ?? null,
270
+ triggerActorType: record.triggerActorType ?? null,
271
+ });
169
272
  }
170
273
  /**
171
274
  * Mid-run update: persist the agent session id as soon as the executor sees
172
275
  * the stream-json `system/init` line. Lets the dashboard surface the live
173
276
  * session log for an in-flight phase, not just for completed ones.
174
277
  */
175
- recordSessionId(id, sessionId) {
176
- this.db.prepare(`UPDATE executions SET session_id = ? WHERE id = ?`).run(sessionId, id);
278
+ async recordSessionId(id, sessionId) {
279
+ const { executions } = this.t;
280
+ await this.client.update(executions).set({ sessionId }).where(eq(executions.id, id));
177
281
  }
178
282
  /**
179
283
  * Persist the final assistant text for a loop-iteration execution.
@@ -182,15 +286,19 @@ export class ExecutionStore {
182
286
  * stores `lastOutputExecutionId` and resolves the text through
183
287
  * `getExecutionOutput` on read.
184
288
  */
185
- recordOutputText(id, output) {
186
- this.db.prepare(`UPDATE executions SET output_text = ? WHERE id = ?`).run(output, id);
289
+ async recordOutputText(id, output) {
290
+ const { executions } = this.t;
291
+ await this.client.update(executions).set({ outputText: output }).where(eq(executions.id, id));
187
292
  }
188
293
  /** Read the persisted output text for an execution, or null if none. */
189
- getExecutionOutput(id) {
190
- const row = this.db
191
- .prepare(`SELECT output_text FROM executions WHERE id = ?`)
192
- .get(id);
193
- return row?.output_text ?? null;
294
+ async getExecutionOutput(id) {
295
+ const { executions } = this.t;
296
+ const [row] = await this.client
297
+ .select({ outputText: executions.outputText })
298
+ .from(executions)
299
+ .where(eq(executions.id, id))
300
+ .limit(1);
301
+ return row?.outputText ?? null;
194
302
  }
195
303
  /**
196
304
  * Most recent finished execution's `output_text` for a phase (`skill`), or
@@ -198,58 +306,78 @@ export class ExecutionStore {
198
306
  * verdict from its persisted output (a dedup-`done` review must not be
199
307
  * assumed APPROVED — it may have requested changes).
200
308
  */
201
- getPhaseOutput(skill, triggerId, workflowRunId) {
202
- const [scopeClause, scopeParam] = workflowRunId
203
- ? ["workflow_run_id = ?", workflowRunId]
204
- : ["trigger_id = ?", triggerId];
205
- const row = this.db.prepare(`
206
- SELECT output_text FROM executions
207
- WHERE skill = ? AND ${scopeClause} AND output_text IS NOT NULL
208
- ORDER BY finished_at DESC
209
- LIMIT 1
210
- `).get(skill, scopeParam);
211
- return row?.output_text ?? null;
212
- }
213
- recordFinish(id, result) {
214
- this.db.prepare(`
215
- UPDATE executions
216
- SET finished_at = ?,
217
- success = ?,
218
- error = ?,
219
- turns = ?,
220
- duration_ms = ?,
221
- session_id = COALESCE(?, session_id),
222
- cost_usd = COALESCE(?, cost_usd),
223
- input_tokens = COALESCE(?, input_tokens),
224
- cache_creation_input_tokens = COALESCE(?, cache_creation_input_tokens),
225
- cache_read_input_tokens = COALESCE(?, cache_read_input_tokens),
226
- output_tokens = COALESCE(?, output_tokens),
227
- api_duration_ms = COALESCE(?, api_duration_ms),
228
- stop_reason = COALESCE(?, stop_reason),
229
- extension_status = COALESCE(?, extension_status),
230
- skills_status = COALESCE(?, skills_status)
231
- WHERE id = ?
232
- `).run(new Date().toISOString(), result.success ? 1 : 0, result.error, result.turns, result.durationMs, result.sessionId ?? null, result.costUsd ?? null, result.inputTokens ?? null, result.cacheCreationInputTokens ?? null, result.cacheReadInputTokens ?? null, result.outputTokens ?? null, result.apiDurationMs ?? null, result.stopReason ?? null, result.extensionStatus ?? null, result.skillsStatus ?? null, id);
309
+ async getPhaseOutput(skill, triggerId, workflowRunId) {
310
+ const { executions } = this.t;
311
+ const [row] = await this.client
312
+ .select({ outputText: executions.outputText })
313
+ .from(executions)
314
+ .where(and(eq(executions.skill, skill), this.scope(triggerId, workflowRunId), isNotNull(executions.outputText)))
315
+ .orderBy(desc(executions.finishedAt))
316
+ .limit(1);
317
+ return row?.outputText ?? null;
318
+ }
319
+ async recordFinish(id, result) {
320
+ const { executions } = this.t;
321
+ // The ten optional columns were `COALESCE(?, col)` under raw SQL — "leave
322
+ // what's there when this finish reports nothing". Omitting the key from the
323
+ // SET entirely says the same thing, and says it without a round trip.
324
+ await this.client
325
+ .update(executions)
326
+ .set({
327
+ finishedAt: new Date().toISOString(),
328
+ success: result.success,
329
+ error: result.error ?? null,
330
+ turns: result.turns ?? null,
331
+ durationMs: result.durationMs ?? null,
332
+ ...(result.sessionId !== undefined ? { sessionId: result.sessionId } : {}),
333
+ ...(result.costUsd !== undefined ? { costUsd: result.costUsd } : {}),
334
+ ...(result.inputTokens !== undefined ? { inputTokens: result.inputTokens } : {}),
335
+ ...(result.cacheCreationInputTokens !== undefined
336
+ ? { cacheCreationInputTokens: result.cacheCreationInputTokens }
337
+ : {}),
338
+ ...(result.cacheReadInputTokens !== undefined
339
+ ? { cacheReadInputTokens: result.cacheReadInputTokens }
340
+ : {}),
341
+ ...(result.outputTokens !== undefined ? { outputTokens: result.outputTokens } : {}),
342
+ ...(result.apiDurationMs !== undefined ? { apiDurationMs: result.apiDurationMs } : {}),
343
+ ...(result.stopReason !== undefined ? { stopReason: result.stopReason } : {}),
344
+ ...(result.extensionStatus !== undefined
345
+ ? { extensionStatus: result.extensionStatus }
346
+ : {}),
347
+ ...(result.skillsStatus !== undefined ? { skillsStatus: result.skillsStatus } : {}),
348
+ })
349
+ .where(eq(executions.id, id));
233
350
  }
234
351
  /**
235
352
  * Record a phase that the scheduler skipped because its trigger rule was
236
353
  * not satisfied (a failed/skipped upstream cascaded down a chain). The
237
354
  * executions ledger is the single source of truth the dashboard derives
238
355
  * phase status from, so skips are written here too — as a finished,
239
- * non-successful row (`success = 0`, `stop_reason = 'skipped'`). Because it
240
- * is not `success = 1`, `shouldRunPhase` re-evaluates it on resume (the node
241
- * will simply be re-skipped if the upstream is still failed).
356
+ * non-successful row (`success = false`, `stop_reason = 'skipped'`). Because
357
+ * it is not `success = true`, `shouldRunPhase` re-evaluates it on resume (the
358
+ * node will simply be re-skipped if the upstream is still failed).
242
359
  */
243
- recordSkippedPhase(skill, triggerId, workflowRunId, repo, owner) {
360
+ async recordSkippedPhase(skill, triggerId, workflowRunId, repo, owner) {
361
+ const { executions } = this.t;
244
362
  const now = new Date().toISOString();
245
363
  const m = triggerId.match(/#(\d+)$/);
246
364
  const issueNumber = m ? Number(m[1]) : null;
247
365
  const ref = normalizeRepoRef(owner, repo);
248
- this.db.prepare(`
249
- INSERT INTO executions
250
- (id, trigger_type, trigger_id, skill, owner, repo, issue_number, started_at, finished_at, success, error, stop_reason, workflow_run_id)
251
- VALUES (?, 'webhook', ?, ?, ?, ?, ?, ?, ?, 0, 'skipped: trigger rule not satisfied', 'skipped', ?)
252
- `).run(randomUUID(), triggerId, skill, ref.owner ?? null, ref.repo ?? null, issueNumber, now, now, workflowRunId ?? null);
366
+ await this.client.insert(executions).values({
367
+ id: randomUUID(),
368
+ triggerType: "webhook",
369
+ triggerId,
370
+ skill,
371
+ owner: ref.owner ?? null,
372
+ repo: ref.repo ?? null,
373
+ issueNumber,
374
+ startedAt: now,
375
+ finishedAt: now,
376
+ success: false,
377
+ error: "skipped: trigger rule not satisfied",
378
+ stopReason: "skipped",
379
+ workflowRunId: workflowRunId ?? null,
380
+ });
253
381
  }
254
382
  /**
255
383
  * List chat threads aggregated from the executions table.
@@ -261,12 +389,13 @@ export class ExecutionStore {
261
389
  * the on-disk jsonl when streaming messages) and with `messaging_messages`
262
390
  * for the most recent assistant text (preview snippet).
263
391
  */
264
- listChatThreads(limit) {
265
- const rows = this.db.prepare(`
392
+ async listChatThreads(limit) {
393
+ const { executions, messagingMessages, messagingSessions } = this.t;
394
+ return rows(this.client, sql `
266
395
  SELECT
267
- e.trigger_id AS triggerId,
268
- ms.agent_session_id AS agentSessionId,
269
- ms.platform AS platform,
396
+ ${executions.triggerId} AS "triggerId",
397
+ ${messagingSessions.agentSessionId} AS "agentSessionId",
398
+ ${messagingSessions.platform} AS "platform",
270
399
  -- The thread's repo, for the dashboard's per-repo visibility filter
271
400
  -- (issue #169), qualified to owner/repo — a bare name would match
272
401
  -- nothing in the allow-list and so HIDE the row. MAX() rather than a
@@ -274,60 +403,65 @@ export class ExecutionStore {
274
403
  -- repo, and one that does should name the whole thread. A thread that
275
404
  -- genuinely spans repos picks one — acceptable, since a repo-less
276
405
  -- thread stays visible either way.
277
- MAX(${QUALIFIED_REPO_SQL}) AS repo,
278
- MIN(e.started_at) AS firstStartedAt,
279
- MAX(COALESCE(e.finished_at, e.started_at)) AS lastActivityAt,
280
- COUNT(*) AS turnCount,
281
- SUM(COALESCE(e.cost_usd, 0)) AS totalCost,
282
- SUM(COALESCE(e.input_tokens, 0)) AS inputTokens,
283
- SUM(COALESCE(e.output_tokens, 0)) AS outputTokens,
284
- SUM(COALESCE(e.cache_read_input_tokens, 0)) AS cacheReadTokens,
406
+ MAX(${qualifiedRepoOrNull(this.t)}) AS "repo",
407
+ MIN(${executions.startedAt}) AS "firstStartedAt",
408
+ MAX(COALESCE(${executions.finishedAt}, ${executions.startedAt})) AS "lastActivityAt",
409
+ COUNT(*) AS "turnCount",
410
+ SUM(COALESCE(${executions.costUsd}, 0)) AS "totalCost",
411
+ SUM(COALESCE(${executions.inputTokens}, 0)) AS "inputTokens",
412
+ SUM(COALESCE(${executions.outputTokens}, 0)) AS "outputTokens",
413
+ SUM(COALESCE(${executions.cacheReadInputTokens}, 0)) AS "cacheReadTokens",
285
414
  (
286
- SELECT mm.content
287
- FROM messaging_messages mm
288
- WHERE mm.session_id = e.trigger_id AND mm.role = 'assistant'
289
- ORDER BY mm.timestamp DESC
415
+ SELECT ${messagingMessages.content}
416
+ FROM ${messagingMessages}
417
+ WHERE ${messagingMessages.sessionId} = ${executions.triggerId}
418
+ AND ${messagingMessages.role} = 'assistant'
419
+ ORDER BY ${messagingMessages.timestamp} DESC
290
420
  LIMIT 1
291
- ) AS lastAssistantContent
292
- FROM executions e
293
- LEFT JOIN messaging_sessions ms ON ms.id = e.trigger_id
294
- WHERE e.skill = 'chat'
295
- GROUP BY e.trigger_id
296
- ORDER BY lastActivityAt DESC
297
- LIMIT ?
298
- `).all(limit);
299
- return rows;
421
+ ) AS "lastAssistantContent"
422
+ FROM ${executions}
423
+ LEFT JOIN ${messagingSessions} ON ${messagingSessions.id} = ${executions.triggerId}
424
+ WHERE ${executions.skill} = 'chat'
425
+ -- The two messaging_sessions columns are grouped rather than bare: the
426
+ -- join is on that table's primary key, so each trigger_id still collapses
427
+ -- to exactly one row, but Postgres rejects a bare non-aggregated column.
428
+ GROUP BY ${executions.triggerId}, ${messagingSessions.agentSessionId}, ${messagingSessions.platform}
429
+ ORDER BY "lastActivityAt" DESC
430
+ LIMIT ${limit}
431
+ `);
300
432
  }
301
433
  /** Look up a single chat thread by its messaging session id (= trigger_id). */
302
- getChatThread(triggerId) {
303
- const row = this.db.prepare(`
434
+ async getChatThread(triggerId) {
435
+ const { executions, messagingMessages, messagingSessions } = this.t;
436
+ const results = await rows(this.client, sql `
304
437
  SELECT
305
- e.trigger_id AS triggerId,
306
- ms.agent_session_id AS agentSessionId,
307
- ms.platform AS platform,
438
+ ${executions.triggerId} AS "triggerId",
439
+ ${messagingSessions.agentSessionId} AS "agentSessionId",
440
+ ${messagingSessions.platform} AS "platform",
308
441
  -- Same qualification rule as the list above; it read the raw column
309
442
  -- here and so disagreed with its own list view for one thread.
310
- MAX(${QUALIFIED_REPO_SQL}) AS repo,
311
- MIN(e.started_at) AS firstStartedAt,
312
- MAX(COALESCE(e.finished_at, e.started_at)) AS lastActivityAt,
313
- COUNT(*) AS turnCount,
314
- SUM(COALESCE(e.cost_usd, 0)) AS totalCost,
315
- SUM(COALESCE(e.input_tokens, 0)) AS inputTokens,
316
- SUM(COALESCE(e.output_tokens, 0)) AS outputTokens,
317
- SUM(COALESCE(e.cache_read_input_tokens, 0)) AS cacheReadTokens,
443
+ MAX(${qualifiedRepoOrNull(this.t)}) AS "repo",
444
+ MIN(${executions.startedAt}) AS "firstStartedAt",
445
+ MAX(COALESCE(${executions.finishedAt}, ${executions.startedAt})) AS "lastActivityAt",
446
+ COUNT(*) AS "turnCount",
447
+ SUM(COALESCE(${executions.costUsd}, 0)) AS "totalCost",
448
+ SUM(COALESCE(${executions.inputTokens}, 0)) AS "inputTokens",
449
+ SUM(COALESCE(${executions.outputTokens}, 0)) AS "outputTokens",
450
+ SUM(COALESCE(${executions.cacheReadInputTokens}, 0)) AS "cacheReadTokens",
318
451
  (
319
- SELECT mm.content
320
- FROM messaging_messages mm
321
- WHERE mm.session_id = e.trigger_id AND mm.role = 'assistant'
322
- ORDER BY mm.timestamp DESC
452
+ SELECT ${messagingMessages.content}
453
+ FROM ${messagingMessages}
454
+ WHERE ${messagingMessages.sessionId} = ${executions.triggerId}
455
+ AND ${messagingMessages.role} = 'assistant'
456
+ ORDER BY ${messagingMessages.timestamp} DESC
323
457
  LIMIT 1
324
- ) AS lastAssistantContent
325
- FROM executions e
326
- LEFT JOIN messaging_sessions ms ON ms.id = e.trigger_id
327
- WHERE e.skill = 'chat' AND e.trigger_id = ?
328
- GROUP BY e.trigger_id
329
- `).get(triggerId);
330
- return row ?? null;
458
+ ) AS "lastAssistantContent"
459
+ FROM ${executions}
460
+ LEFT JOIN ${messagingSessions} ON ${messagingSessions.id} = ${executions.triggerId}
461
+ WHERE ${executions.skill} = 'chat' AND ${executions.triggerId} = ${triggerId}
462
+ GROUP BY ${executions.triggerId}, ${messagingSessions.agentSessionId}, ${messagingSessions.platform}
463
+ `);
464
+ return results[0] ?? null;
331
465
  }
332
466
  /**
333
467
  * The repo a sandbox session ran against, resolved from the `executions`
@@ -338,23 +472,24 @@ export class ExecutionStore {
338
472
  * session list by the same allowed-repo set as everything else. Returns null
339
473
  * for a session we have no execution row for — those stay visible.
340
474
  */
341
- repoForSessionId(sessionId) {
342
- const row = this.db
343
- .prepare(`SELECT ${QUALIFIED_REPO_SQL} AS repo
344
- FROM executions e
345
- WHERE e.session_id = ? AND e.repo IS NOT NULL
346
- ORDER BY e.started_at DESC
347
- LIMIT 1`)
348
- .get(sessionId);
475
+ async repoForSessionId(sessionId) {
476
+ const { executions } = this.t;
477
+ const [row] = await this.client
478
+ .select({ repo: sql `${qualifiedRepoOrNull(this.t)}` })
479
+ .from(executions)
480
+ .where(and(eq(executions.sessionId, sessionId), isNotNull(executions.repo)))
481
+ .orderBy(desc(executions.startedAt))
482
+ .limit(1);
349
483
  return row?.repo ?? null;
350
484
  }
351
485
  /** Check if a skill is currently running for a given trigger */
352
- isRunning(skill, triggerId) {
353
- const row = this.db.prepare(`
354
- SELECT 1 FROM executions
355
- WHERE skill = ? AND trigger_id = ? AND finished_at IS NULL
356
- LIMIT 1
357
- `).get(skill, triggerId);
486
+ async isRunning(skill, triggerId) {
487
+ const { executions } = this.t;
488
+ const [row] = await this.client
489
+ .select({ id: executions.id })
490
+ .from(executions)
491
+ .where(and(eq(executions.skill, skill), eq(executions.triggerId, triggerId), isNull(executions.finishedAt)))
492
+ .limit(1);
358
493
  return !!row;
359
494
  }
360
495
  /**
@@ -372,16 +507,15 @@ export class ExecutionStore {
372
507
  * OAuth/subscription run) contribute 0 — the brake must never be tripped by
373
508
  * missing data.
374
509
  */
375
- costForTriggerWorkflows(triggerId, workflowNames) {
510
+ async costForTriggerWorkflows(triggerId, workflowNames) {
376
511
  if (workflowNames.length === 0)
377
512
  return 0;
378
- const placeholders = workflowNames.map(() => "?").join(", ");
379
- const row = this.db.prepare(`
380
- SELECT COALESCE(SUM(e.cost_usd), 0) AS total
381
- FROM executions e
382
- JOIN workflow_runs r ON r.id = e.workflow_run_id
383
- WHERE r.trigger_id = ? AND r.workflow_name IN (${placeholders})
384
- `).get(triggerId, ...workflowNames);
513
+ const { executions, workflowRuns } = this.t;
514
+ const [row] = await this.client
515
+ .select({ total: sql `COALESCE(SUM(${executions.costUsd}), 0)` })
516
+ .from(executions)
517
+ .innerJoin(workflowRuns, eq(workflowRuns.id, executions.workflowRunId))
518
+ .where(and(eq(workflowRuns.triggerId, triggerId), inArray(workflowRuns.workflowName, workflowNames)));
385
519
  return row?.total ?? 0;
386
520
  }
387
521
  /**
@@ -394,21 +528,23 @@ export class ExecutionStore {
394
528
  * `on_output.requires_marker: DIAGNOSIS_COMPLETE`, so a succeeded row for it
395
529
  * is equivalent to the marker having been emitted.
396
530
  */
397
- phaseSucceededInRun(workflowRunId, phaseName) {
398
- const row = this.db.prepare(`
399
- SELECT 1 FROM executions
400
- WHERE workflow_run_id = ? AND skill LIKE ? AND success = 1
401
- LIMIT 1
402
- `).get(workflowRunId, `%:${phaseName}`);
531
+ async phaseSucceededInRun(workflowRunId, phaseName) {
532
+ const { executions } = this.t;
533
+ const [row] = await this.client
534
+ .select({ id: executions.id })
535
+ .from(executions)
536
+ .where(and(eq(executions.workflowRunId, workflowRunId), like(executions.skill, `%:${phaseName}`), eq(executions.success, true)))
537
+ .limit(1);
403
538
  return !!row;
404
539
  }
405
540
  /** Check if a skill has already completed successfully for a given trigger */
406
- isCompleted(skill, triggerId) {
407
- const row = this.db.prepare(`
408
- SELECT 1 FROM executions
409
- WHERE skill = ? AND trigger_id = ? AND success = 1
410
- LIMIT 1
411
- `).get(skill, triggerId);
541
+ async isCompleted(skill, triggerId) {
542
+ const { executions } = this.t;
543
+ const [row] = await this.client
544
+ .select({ id: executions.id })
545
+ .from(executions)
546
+ .where(and(eq(executions.skill, skill), eq(executions.triggerId, triggerId), eq(executions.success, true)))
547
+ .limit(1);
412
548
  return !!row;
413
549
  }
414
550
  /**
@@ -419,38 +555,38 @@ export class ExecutionStore {
419
555
  * for the same trigger exists. Omit `workflowRunId` for legacy callers
420
556
  * (e.g. chat/status-report dedup) that want the old trigger-wide scope.
421
557
  */
422
- shouldRunPhase(skill, triggerId, workflowRunId) {
423
- const [scopeClause, scopeParam] = workflowRunId
424
- ? ["workflow_run_id = ?", workflowRunId]
425
- : ["trigger_id = ?", triggerId];
426
- const running = this.db.prepare(`
427
- SELECT 1 FROM executions
428
- WHERE skill = ? AND ${scopeClause} AND finished_at IS NULL
429
- LIMIT 1
430
- `).get(skill, scopeParam);
558
+ async shouldRunPhase(skill, triggerId, workflowRunId) {
559
+ const { executions } = this.t;
560
+ const scope = this.scope(triggerId, workflowRunId);
561
+ const [running] = await this.client
562
+ .select({ id: executions.id })
563
+ .from(executions)
564
+ .where(and(eq(executions.skill, skill), scope, isNull(executions.finishedAt)))
565
+ .limit(1);
431
566
  if (running)
432
567
  return "running";
433
- const done = this.db.prepare(`
434
- SELECT 1 FROM executions
435
- WHERE skill = ? AND ${scopeClause} AND success = 1
436
- LIMIT 1
437
- `).get(skill, scopeParam);
568
+ const [done] = await this.client
569
+ .select({ id: executions.id })
570
+ .from(executions)
571
+ .where(and(eq(executions.skill, skill), scope, eq(executions.success, true)))
572
+ .limit(1);
438
573
  if (done)
439
574
  return "done";
440
575
  return "run";
441
576
  }
442
577
  /** Mark all stale "running" executions for a skill/trigger as failed.
443
578
  * Called when we detect no matching Docker container is alive. */
444
- markStaleAsFailed(skill, triggerId, workflowRunId) {
445
- const [scopeClause, scopeParam] = workflowRunId
446
- ? ["workflow_run_id = ?", workflowRunId]
447
- : ["trigger_id = ?", triggerId];
448
- const result = this.db.prepare(`
449
- UPDATE executions
450
- SET finished_at = ?, success = 0, error = 'stale: container no longer running'
451
- WHERE skill = ? AND ${scopeClause} AND finished_at IS NULL
452
- `).run(new Date().toISOString(), skill, scopeParam);
453
- return result.changes;
579
+ async markStaleAsFailed(skill, triggerId, workflowRunId) {
580
+ const { executions } = this.t;
581
+ const result = await this.client
582
+ .update(executions)
583
+ .set({
584
+ finishedAt: new Date().toISOString(),
585
+ success: false,
586
+ error: "stale: container no longer running",
587
+ })
588
+ .where(and(eq(executions.skill, skill), this.scope(triggerId, workflowRunId), isNull(executions.finishedAt)));
589
+ return changes(result);
454
590
  }
455
591
  /**
456
592
  * Mark every unfinished execution row for a trigger as failed, regardless
@@ -458,108 +594,132 @@ export class ExecutionStore {
458
594
  * were running when the harness crashed/restarted, so the runner's dedup
459
595
  * logic doesn't think they're still in flight.
460
596
  */
461
- markAllStaleForTrigger(triggerId, reason) {
462
- const result = this.db.prepare(`
463
- UPDATE executions
464
- SET finished_at = ?, success = 0, error = ?
465
- WHERE trigger_id = ? AND finished_at IS NULL
466
- `).run(new Date().toISOString(), reason, triggerId);
467
- return result.changes;
597
+ async markAllStaleForTrigger(triggerId, reason) {
598
+ const { executions } = this.t;
599
+ const result = await this.client
600
+ .update(executions)
601
+ .set({ finishedAt: new Date().toISOString(), success: false, error: reason })
602
+ .where(and(eq(executions.triggerId, triggerId), isNull(executions.finishedAt)));
603
+ return changes(result);
468
604
  }
469
605
  /**
470
606
  * Mark the most recent execution for a skill/trigger as failed.
471
607
  * Used when the agent SDK reported success but the orchestrator decided
472
608
  * the business outcome was a failure (e.g. guardrails BLOCKED, reviewer
473
609
  * REQUEST_CHANGES). Without this, runPhase would skip the phase on the
474
- * next run because the DB still says success=1.
610
+ * next run because the DB still says success=true.
611
+ *
612
+ * Raw because of the "newest row wins" correlated subquery. Note the two
613
+ * shapes it needs: the SET column is written UNQUALIFIED (`SET
614
+ * "executions"."success" = …` is not legal SQL in either dialect), and the
615
+ * false is a BOUND param — libsql binds it as 0 and Postgres as a real
616
+ * boolean, where a literal `= 0` would throw `operator does not exist:
617
+ * boolean = integer`.
475
618
  */
476
- markLatestAsFailed(skill, triggerId, reason, workflowRunId) {
477
- const [scopeClause, scopeParam] = workflowRunId
478
- ? ["workflow_run_id = ?", workflowRunId]
479
- : ["trigger_id = ?", triggerId];
480
- const result = this.db.prepare(`
481
- UPDATE executions
482
- SET success = 0, error = ?
483
- WHERE id = (
484
- SELECT id FROM executions
485
- WHERE skill = ? AND ${scopeClause}
486
- ORDER BY started_at DESC
619
+ async markLatestAsFailed(skill, triggerId, reason, workflowRunId) {
620
+ const { executions } = this.t;
621
+ const scopeSql = workflowRunId
622
+ ? sql `${executions.workflowRunId} = ${workflowRunId}`
623
+ : sql `${executions.triggerId} = ${triggerId}`;
624
+ const result = await run(this.client, sql `
625
+ UPDATE ${executions}
626
+ SET ${sql.identifier(executions.success.name)} = ${false},
627
+ ${sql.identifier(executions.error.name)} = ${reason}
628
+ WHERE ${executions.id} = (
629
+ SELECT ${executions.id} FROM ${executions}
630
+ WHERE ${executions.skill} = ${skill} AND ${scopeSql}
631
+ ORDER BY ${executions.startedAt} DESC
487
632
  LIMIT 1
488
633
  )
489
- `).run(reason, skill, scopeParam);
490
- return result.changes;
634
+ `);
635
+ return changes(result);
491
636
  }
492
637
  /** Get recent executions for a skill */
493
- recentExecutions(skill, limit = 10) {
494
- const rows = this.db.prepare(`
495
- SELECT ${EXECUTION_COLUMNS} FROM executions
496
- WHERE skill = ?
497
- ORDER BY started_at DESC
498
- LIMIT ?
499
- `).all(skill, limit);
500
- return rows.map(mapExecutionRow);
501
- }
502
- /** Count consecutive failures for a skill (for cron failure tracking) */
503
- consecutiveFailures(skill) {
504
- const rows = this.db.prepare(`
505
- SELECT success FROM executions
506
- WHERE skill = ? AND finished_at IS NOT NULL
507
- ORDER BY started_at DESC
508
- LIMIT 10
509
- `).all(skill);
510
- let count = 0;
511
- for (const row of rows) {
512
- if (row.success === 0)
513
- count++;
638
+ async recentExecutions(skill, limit = 10) {
639
+ const { executions } = this.t;
640
+ const results = await this.client
641
+ .select(executionColumns(this.t))
642
+ .from(executions)
643
+ .where(eq(executions.skill, skill))
644
+ .orderBy(desc(executions.startedAt))
645
+ .limit(limit);
646
+ return results.map(deserialize);
647
+ }
648
+ /**
649
+ * Count consecutive failures for a skill (for cron failure tracking).
650
+ *
651
+ * The compare is `=== false`, not `=== 0`: `success` is a boolean-mode
652
+ * column, so an integer compare is never true and this would report a
653
+ * permanent zero — silently disarming the cron failure alert.
654
+ */
655
+ async consecutiveFailures(skill) {
656
+ const { executions } = this.t;
657
+ const results = await this.client
658
+ .select({ success: executions.success })
659
+ .from(executions)
660
+ .where(and(eq(executions.skill, skill), isNotNull(executions.finishedAt)))
661
+ .orderBy(desc(executions.startedAt))
662
+ .limit(10);
663
+ let streak = 0;
664
+ for (const row of results) {
665
+ if (row.success === false)
666
+ streak++;
514
667
  else
515
668
  break;
516
669
  }
517
- return count;
670
+ return streak;
518
671
  }
519
672
  /** Get all executions with pagination */
520
- allExecutions(limit = 100, offset = 0) {
521
- const rows = this.db.prepare(`
522
- SELECT ${EXECUTION_COLUMNS} FROM executions
523
- ORDER BY started_at DESC
524
- LIMIT ? OFFSET ?
525
- `).all(limit, offset);
526
- return rows.map(mapExecutionRow);
673
+ async allExecutions(limit = 100, offset = 0) {
674
+ const { executions } = this.t;
675
+ const results = await this.client
676
+ .select(executionColumns(this.t))
677
+ .from(executions)
678
+ .orderBy(desc(executions.startedAt))
679
+ .limit(limit)
680
+ .offset(offset);
681
+ return results.map(deserialize);
527
682
  }
528
683
  /**
529
684
  * Free-text search across the `executions` ledger — matches `error`, `skill`,
530
- * or `repo` against a substring (case-insensitive via SQLite's LIKE). Used by
531
- * the `/admin/api/log-search` endpoint and the `lastlight logs search` CLI to
532
- * find failing/relevant phases without SSHing to the box. Parameterized; the
533
- * pattern is escaped so user input can't smuggle LIKE wildcards.
685
+ * or `repo` against a substring. Used by the `/admin/api/log-search` endpoint
686
+ * and the `lastlight logs search` CLI to find failing/relevant phases without
687
+ * SSHing to the box. Parameterized; the pattern is escaped so user input
688
+ * can't smuggle LIKE wildcards.
689
+ *
690
+ * Raw, because `LIKE … ESCAPE '\'` has no query-builder spelling. Both sides
691
+ * are `lower()`ed rather than leaning on SQLite's case-insensitive LIKE,
692
+ * which Postgres does not share — the case-insensitivity is the feature here,
693
+ * not an accident of the dialect.
534
694
  *
535
695
  * Matches and returns the QUALIFIED repo, because that is what somebody types
536
696
  * (issue #279) — searching `nearform/lastlight` against the bare column found
537
697
  * no phase row at all.
538
698
  */
539
- searchErrors(query, limit = 50) {
540
- const escaped = query.replace(/[\\%_]/g, (ch) => `\\${ch}`);
541
- const pattern = `%${escaped}%`;
542
- const qualifiedRepo = qualifiedRepoSql("e.owner", "e.repo", "bare");
543
- const rows = this.db.prepare(`
699
+ async searchErrors(query, limit = 50) {
700
+ const { executions } = this.t;
701
+ const pattern = `%${likeEscape(query).toLowerCase()}%`;
702
+ const qualifiedRepo = qualifiedRepoSql(executions.owner, executions.repo, "bare");
703
+ const results = await rows(this.client, sql `
544
704
  SELECT
545
- e.id,
546
- e.skill,
547
- ${qualifiedRepo} AS repo,
548
- e.error,
549
- e.success,
550
- e.started_at AS startedAt,
551
- e.finished_at AS finishedAt,
552
- e.session_id AS sessionId,
553
- e.workflow_run_id AS workflowRunId,
554
- e.trigger_id AS triggerId
555
- FROM executions e
556
- WHERE e.error LIKE ? ESCAPE '\\'
557
- OR e.skill LIKE ? ESCAPE '\\'
558
- OR ${qualifiedRepo} LIKE ? ESCAPE '\\'
559
- ORDER BY e.started_at DESC
560
- LIMIT ?
561
- `).all(pattern, pattern, pattern, limit);
562
- return rows.map((r) => ({
705
+ ${executions.id} AS "id",
706
+ ${executions.skill} AS "skill",
707
+ ${qualifiedRepo} AS "repo",
708
+ ${executions.error} AS "error",
709
+ ${executions.success} AS "success",
710
+ ${executions.startedAt} AS "startedAt",
711
+ ${executions.finishedAt} AS "finishedAt",
712
+ ${executions.sessionId} AS "sessionId",
713
+ ${executions.workflowRunId} AS "workflowRunId",
714
+ ${executions.triggerId} AS "triggerId"
715
+ FROM ${executions}
716
+ WHERE lower(${executions.error}) LIKE ${pattern} ESCAPE '\\'
717
+ OR lower(${executions.skill}) LIKE ${pattern} ESCAPE '\\'
718
+ OR lower(${qualifiedRepo}) LIKE ${pattern} ESCAPE '\\'
719
+ ORDER BY ${executions.startedAt} DESC
720
+ LIMIT ${limit}
721
+ `);
722
+ return results.map((r) => ({
563
723
  id: r.id,
564
724
  skill: r.skill,
565
725
  repo: r.repo ?? undefined,
@@ -580,39 +740,49 @@ export class ExecutionStore {
580
740
  * falls back to the legacy trigger-wide scope for rows written before the
581
741
  * workflow_run_id column existed.
582
742
  */
583
- getExecutionsForWorkflowRun(workflowRunId, triggerId, workflowName) {
743
+ async getExecutionsForWorkflowRun(workflowRunId, triggerId, workflowName) {
744
+ const { executions } = this.t;
584
745
  const skillPattern = workflowName ? `${workflowName}:%` : "%:%";
585
- const rows = this.db.prepare(`
586
- SELECT ${EXECUTION_COLUMNS}
587
- FROM executions
588
- WHERE (workflow_run_id = ? OR (workflow_run_id IS NULL AND trigger_id = ?))
589
- AND skill LIKE ?
590
- ORDER BY started_at ASC
591
- `).all(workflowRunId, triggerId, skillPattern);
592
- return rows.map(mapExecutionRow);
746
+ const results = await rows(this.client, sql `
747
+ SELECT ${executionColumnsSql(this.t)}
748
+ FROM ${executions}
749
+ WHERE (${executions.workflowRunId} = ${workflowRunId}
750
+ OR (${executions.workflowRunId} IS NULL AND ${executions.triggerId} = ${triggerId}))
751
+ AND ${executions.skill} LIKE ${skillPattern}
752
+ ORDER BY ${executions.startedAt} ASC
753
+ `);
754
+ return results.map(mapExecutionRow);
593
755
  }
594
756
  /** Get currently running executions (no finished_at) */
595
- runningExecutions() {
596
- const rows = this.db.prepare(`
597
- SELECT ${EXECUTION_COLUMNS} FROM executions
598
- WHERE finished_at IS NULL
599
- ORDER BY started_at DESC
600
- `).all();
601
- return rows.map(mapExecutionRow);
757
+ async runningExecutions() {
758
+ const { executions } = this.t;
759
+ const results = await this.client
760
+ .select(executionColumns(this.t))
761
+ .from(executions)
762
+ .where(isNull(executions.finishedAt))
763
+ .orderBy(desc(executions.startedAt));
764
+ return results.map(deserialize);
602
765
  }
603
766
  /** Aggregate execution stats */
604
- executionStats() {
767
+ async executionStats() {
768
+ const { executions } = this.t;
605
769
  const today = new Date();
606
770
  today.setHours(0, 0, 0, 0);
607
771
  const todayIso = today.toISOString();
608
- const total = this.db.prepare(`SELECT COUNT(*) as c FROM executions`).get().c;
609
- const todayCount = this.db.prepare(`SELECT COUNT(*) as c FROM executions WHERE started_at >= ?`).get(todayIso).c;
610
- const running = this.db.prepare(`SELECT COUNT(*) as c FROM executions WHERE finished_at IS NULL`).get().c;
611
- const skillRows = this.db.prepare(`
612
- SELECT skill, COUNT(*) as count,
613
- ${EXECUTION_OUTCOME_COLUMNS}
614
- FROM executions GROUP BY skill
615
- `).all();
772
+ const [totalRow] = await this.client.select({ c: count() }).from(executions);
773
+ const [todayRow] = await this.client
774
+ .select({ c: count() })
775
+ .from(executions)
776
+ .where(gte(executions.startedAt, todayIso));
777
+ const [runningRow] = await this.client
778
+ .select({ c: count() })
779
+ .from(executions)
780
+ .where(isNull(executions.finishedAt));
781
+ const skillRows = await rows(this.client, sql `
782
+ SELECT ${executions.skill} AS "skill", COUNT(*) AS "count",
783
+ ${executionOutcomeColumns(this.t)}
784
+ FROM ${executions} GROUP BY ${executions.skill}
785
+ `);
616
786
  const by_skill = {};
617
787
  for (const r of skillRows) {
618
788
  by_skill[r.skill] = {
@@ -623,14 +793,21 @@ export class ExecutionStore {
623
793
  failed: r.failed,
624
794
  };
625
795
  }
626
- const triggerRows = this.db.prepare(`
627
- SELECT trigger_type, COUNT(*) as count FROM executions GROUP BY trigger_type
628
- `).all();
796
+ const triggerRows = await rows(this.client, sql `
797
+ SELECT ${executions.triggerType} AS "triggerType", COUNT(*) AS "count"
798
+ FROM ${executions} GROUP BY ${executions.triggerType}
799
+ `);
629
800
  const by_trigger = {};
630
801
  for (const r of triggerRows) {
631
- by_trigger[r.trigger_type] = r.count;
802
+ by_trigger[r.triggerType] = r.count;
632
803
  }
633
- return { total_executions: total, today_count: todayCount, by_skill, by_trigger, running };
804
+ return {
805
+ total_executions: totalRow?.c ?? 0,
806
+ today_count: todayRow?.c ?? 0,
807
+ by_skill,
808
+ by_trigger,
809
+ running: runningRow?.c ?? 0,
810
+ };
634
811
  }
635
812
  /**
636
813
  * What ONE repo's agent work cost since `sinceIso`. The spend line of the
@@ -640,21 +817,25 @@ export class ExecutionStore {
640
817
  * phase, carry no cost — so this sums with a COALESCE and reports the phase
641
818
  * count separately rather than implying the two are the same denominator.
642
819
  */
643
- repoCostSince(owner, repo, sinceIso) {
644
- const qualifiedRepo = qualifiedRepoSql("e.owner", "e.repo", "bare");
645
- const row = this.db
646
- .prepare(`SELECT COALESCE(SUM(e.cost_usd), 0) AS costUsd, COUNT(*) AS phases
647
- FROM executions e
648
- WHERE ${qualifiedRepo} = ?
649
- AND e.started_at >= ?`)
650
- .get(`${owner}/${repo}`, sinceIso);
820
+ async repoCostSince(owner, repo, sinceIso) {
821
+ const { executions } = this.t;
822
+ const qualifiedRepo = qualifiedRepoSql(executions.owner, executions.repo, "bare");
823
+ const [row] = await this.client
824
+ .select({
825
+ costUsd: sql `COALESCE(SUM(${executions.costUsd}), 0)`,
826
+ phases: count(),
827
+ })
828
+ .from(executions)
829
+ .where(and(sql `${qualifiedRepo} = ${`${owner}/${repo}`}`, gte(executions.startedAt, sinceIso)));
651
830
  return { costUsd: row?.costUsd ?? 0, phases: row?.phases ?? 0 };
652
831
  }
653
832
  /** Daily aggregated stats for the last N days */
654
- dailyStats(days) {
833
+ async dailyStats(days) {
834
+ const { executions } = this.t;
655
835
  // Build the inclusive UTC date window: [today - (days-1), today].
656
- // SQLite's date(started_at) returns a UTC YYYY-MM-DD string, so we
657
- // generate the same format here to align keys.
836
+ // dayBucket() takes the first 10 chars of the ISO-8601 timestamp, so it
837
+ // yields a UTC YYYY-MM-DD string in either dialect and we generate the same
838
+ // format here to align keys.
658
839
  const today = new Date();
659
840
  const startUtc = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate() - (days - 1)));
660
841
  const dateKeys = [];
@@ -663,21 +844,22 @@ export class ExecutionStore {
663
844
  d.setUTCDate(startUtc.getUTCDate() + i);
664
845
  dateKeys.push(d.toISOString().slice(0, 10));
665
846
  }
666
- const rows = this.db.prepare(`
847
+ const bucket = dayBucket(executions.startedAt);
848
+ const results = await rows(this.client, sql `
667
849
  SELECT
668
- date(started_at) AS date,
669
- COUNT(*) AS executions,
670
- ${EXECUTION_OUTCOME_COLUMNS},
671
- COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0) + COALESCE(SUM(cache_read_input_tokens), 0) AS totalTokens,
672
- COALESCE(SUM(input_tokens), 0) AS inputTokens,
673
- COALESCE(SUM(output_tokens), 0) AS outputTokens,
674
- COALESCE(SUM(cache_read_input_tokens), 0) AS cacheReadTokens,
675
- COALESCE(SUM(cost_usd), 0) AS costUsd
676
- FROM executions
677
- WHERE date(started_at) >= ?
678
- GROUP BY date(started_at)
679
- `).all(dateKeys[0]);
680
- const byDate = new Map(rows.map((r) => [r.date, r]));
850
+ ${bucket} AS "date",
851
+ COUNT(*) AS "executions",
852
+ ${executionOutcomeColumns(this.t)},
853
+ COALESCE(SUM(${executions.inputTokens}), 0) + COALESCE(SUM(${executions.outputTokens}), 0) + COALESCE(SUM(${executions.cacheReadInputTokens}), 0) AS "totalTokens",
854
+ COALESCE(SUM(${executions.inputTokens}), 0) AS "inputTokens",
855
+ COALESCE(SUM(${executions.outputTokens}), 0) AS "outputTokens",
856
+ COALESCE(SUM(${executions.cacheReadInputTokens}), 0) AS "cacheReadTokens",
857
+ COALESCE(SUM(${executions.costUsd}), 0) AS "costUsd"
858
+ FROM ${executions}
859
+ WHERE ${bucket} >= ${dateKeys[0]}
860
+ GROUP BY ${bucket}
861
+ `);
862
+ const byDate = new Map(results.map((r) => [r.date, r]));
681
863
  return dateKeys.map((date) => byDate.get(date) ?? {
682
864
  date,
683
865
  executions: 0,
@@ -690,31 +872,33 @@ export class ExecutionStore {
690
872
  });
691
873
  }
692
874
  /** Hourly aggregated stats for the last N hours (UTC). Bucket key is `YYYY-MM-DDTHH`. */
693
- hourlyStats(hours) {
875
+ async hourlyStats(hours) {
876
+ const { executions } = this.t;
694
877
  const now = new Date();
695
878
  const startUtc = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours() - (hours - 1)));
696
879
  const hourKeys = [];
697
880
  for (let i = 0; i < hours; i++) {
698
881
  const d = new Date(startUtc);
699
882
  d.setUTCHours(startUtc.getUTCHours() + i);
700
- // YYYY-MM-DDTHH (matches strftime('%Y-%m-%dT%H', …))
883
+ // YYYY-MM-DDTHH (matches hourBucket(), the first 13 ISO-8601 chars)
701
884
  hourKeys.push(d.toISOString().slice(0, 13));
702
885
  }
703
- const rows = this.db.prepare(`
886
+ const bucket = hourBucket(executions.startedAt);
887
+ const results = await rows(this.client, sql `
704
888
  SELECT
705
- strftime('%Y-%m-%dT%H', started_at) AS date,
706
- COUNT(*) AS executions,
707
- ${EXECUTION_OUTCOME_COLUMNS},
708
- COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0) + COALESCE(SUM(cache_read_input_tokens), 0) AS totalTokens,
709
- COALESCE(SUM(input_tokens), 0) AS inputTokens,
710
- COALESCE(SUM(output_tokens), 0) AS outputTokens,
711
- COALESCE(SUM(cache_read_input_tokens), 0) AS cacheReadTokens,
712
- COALESCE(SUM(cost_usd), 0) AS costUsd
713
- FROM executions
714
- WHERE strftime('%Y-%m-%dT%H', started_at) >= ?
715
- GROUP BY strftime('%Y-%m-%dT%H', started_at)
716
- `).all(hourKeys[0]);
717
- const byHour = new Map(rows.map((r) => [r.date, r]));
889
+ ${bucket} AS "date",
890
+ COUNT(*) AS "executions",
891
+ ${executionOutcomeColumns(this.t)},
892
+ COALESCE(SUM(${executions.inputTokens}), 0) + COALESCE(SUM(${executions.outputTokens}), 0) + COALESCE(SUM(${executions.cacheReadInputTokens}), 0) AS "totalTokens",
893
+ COALESCE(SUM(${executions.inputTokens}), 0) AS "inputTokens",
894
+ COALESCE(SUM(${executions.outputTokens}), 0) AS "outputTokens",
895
+ COALESCE(SUM(${executions.cacheReadInputTokens}), 0) AS "cacheReadTokens",
896
+ COALESCE(SUM(${executions.costUsd}), 0) AS "costUsd"
897
+ FROM ${executions}
898
+ WHERE ${bucket} >= ${hourKeys[0]}
899
+ GROUP BY ${bucket}
900
+ `);
901
+ const byHour = new Map(results.map((r) => [r.date, r]));
718
902
  return hourKeys.map((date) => byHour.get(date) ?? {
719
903
  date,
720
904
  executions: 0,
@@ -726,5 +910,16 @@ export class ExecutionStore {
726
910
  costUsd: 0,
727
911
  });
728
912
  }
913
+ /**
914
+ * The run-vs-trigger scope shared by the five methods that accept an optional
915
+ * `workflowRunId`: prefer the run when the caller knows it, fall back to the
916
+ * trigger-wide scope for legacy callers and pre-`workflow_run_id` rows.
917
+ */
918
+ scope(triggerId, workflowRunId) {
919
+ const { executions } = this.t;
920
+ return workflowRunId
921
+ ? eq(executions.workflowRunId, workflowRunId)
922
+ : eq(executions.triggerId, triggerId);
923
+ }
729
924
  }
730
925
  //# sourceMappingURL=execution-store.js.map