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
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Portability seam.
3
+ *
4
+ * Raw-SQL execution, rows-affected shape, unique-violation detection and a
5
+ * handful of SQL functions are the only surfaces that differ between
6
+ * `drizzle-orm/libsql` and a Postgres driver. Everything else the stores do
7
+ * goes through the shared query-builder API, which is identical.
8
+ *
9
+ * IMPORTANT — `rows()` results are NOT column-mapped by Drizzle. No boolean
10
+ * conversion, no JSON parsing, no camelCase renaming: a raw query must alias
11
+ * its own columns and treat booleans as 0/1 integers. Only builder queries
12
+ * (`client.select()…`) return mapped rows. Mixing the two up is the #1
13
+ * regression class in this migration.
14
+ */
15
+ import { sql } from "drizzle-orm";
16
+ /** Run a raw query and return all rows. libsql: `.all(sql)`. pg: `.execute(sql)` → `{rows}`. */
17
+ export async function rows(dbc, query) {
18
+ const d = dbc;
19
+ if (typeof d.all === "function")
20
+ return (await d.all(query));
21
+ const res = (await d.execute(query));
22
+ return (Array.isArray(res) ? res : (res.rows ?? []));
23
+ }
24
+ /** Run a raw statement for its side effect. Feed the result to {@link changes}. */
25
+ export async function run(dbc, query) {
26
+ const d = dbc;
27
+ if (typeof d.run === "function")
28
+ return d.run(query);
29
+ return d.execute(query);
30
+ }
31
+ /**
32
+ * Rows-affected from an awaited builder mutation (or {@link run}).
33
+ *
34
+ * libsql `ResultSet` → `.rowsAffected`; node-postgres `QueryResult` →
35
+ * `.rowCount`; PGlite → `.affectedRows`; better-sqlite3 → `.changes`. Replaces
36
+ * every `result.changes` read in the old code — the compare-and-set guards
37
+ * behind the approval/reply-gate lifecycle depend on this being exact.
38
+ */
39
+ export function changes(result) {
40
+ const r = result;
41
+ return Number(r?.rowsAffected ?? r?.rowCount ?? r?.affectedRows ?? r?.changes ?? 0);
42
+ }
43
+ /**
44
+ * UNIQUE-violation detection across drivers: Postgres reports SQLSTATE 23505 on
45
+ * a `code` property somewhere down the cause chain (Drizzle wraps driver errors
46
+ * in `DrizzleQueryError`), SQLite says so in the message.
47
+ */
48
+ export function isUniqueViolation(error) {
49
+ for (let e = error, depth = 0; e != null && depth < 6; e = e.cause, depth++) {
50
+ if (e.code === "23505")
51
+ return true;
52
+ if (e instanceof Error && /UNIQUE|unique constraint/i.test(e.message))
53
+ return true;
54
+ }
55
+ return false;
56
+ }
57
+ /** Escape `%`, `_` and `\` for a `LIKE … ESCAPE '\'` pattern. */
58
+ export function likeEscape(input) {
59
+ return input.replace(/[\\%_]/g, (ch) => `\\${ch}`);
60
+ }
61
+ /**
62
+ * UTC day bucket over an ISO-8601 TEXT column — replaces sqlite `date(col)`.
63
+ * Timestamps are ISO text in both dialects, so `substr` yields identical
64
+ * `YYYY-MM-DD` keys and the JS side's bucket keys keep matching.
65
+ */
66
+ export function dayBucket(col) {
67
+ return sql `substr(${col}, 1, 10)`;
68
+ }
69
+ /** UTC hour bucket (`YYYY-MM-DDTHH`) — replaces `strftime('%Y-%m-%dT%H', col)`. */
70
+ export function hourBucket(col) {
71
+ return sql `substr(${col}, 1, 13)`;
72
+ }
73
+ /**
74
+ * "Does `haystack` contain the literal `needle`" — a BOOLEAN predicate.
75
+ *
76
+ * This replaces what was `strposExpr()`, a 1-based position: sqlite spells that
77
+ * `instr(h, n)`, Postgres has no `instr` at all and spells it `strpos(h, n)`,
78
+ * so it looked like the widest-reaching dialect branch in the codebase
79
+ * (`repo-ref.ts`'s qualified-repo split fans out to 13 call sites across the
80
+ * execution and run stores). But every one of those call sites only ever asked
81
+ * `> 0`, and `LIKE` answers that identically in both dialects — so the seam
82
+ * disappears instead of being plumbed. `ESCAPE` keeps a needle containing `%`
83
+ * or `_` literal; SQLite's case-insensitive ASCII LIKE is immaterial for the
84
+ * one caller (a `/`).
85
+ */
86
+ export function containsExpr(haystack, needle) {
87
+ // The pattern is INLINED as a SQL literal rather than bound as a parameter,
88
+ // and that is load-bearing rather than a shortcut. Postgres matches a GROUP BY
89
+ // expression to its SELECT twin STRUCTURALLY, and two occurrences of the same
90
+ // bound parameter are two different placeholders ($1 and $3) — so
91
+ // `distinctRepos`, which selects and groups by the same `qualifiedRepoSql`
92
+ // fragment, failed with "column workflow_runs.repo must appear in the GROUP BY
93
+ // clause". (SQLite is lax about this and never noticed.) Inlining makes the
94
+ // two spellings textually identical.
95
+ //
96
+ // Safe only because every needle is a code-owned literal, so the charset guard
97
+ // below is the actual contract — assert it rather than trusting callers, since
98
+ // the failure mode of a hostile needle here would be injection.
99
+ if (!/^[A-Za-z0-9/.:@-]+$/.test(needle)) {
100
+ throw new Error(`containsExpr: needle must be a plain code literal (got ${JSON.stringify(needle)}). ` +
101
+ "For user input, bind a parameter and accept that it cannot appear in a GROUP BY.");
102
+ }
103
+ // No ESCAPE clause: the charset above excludes `%`, `_` and `\` outright, so
104
+ // there is nothing for `likeEscape` to escape.
105
+ return sql `${haystack} LIKE ${sql.raw(`'%${needle}%'`)}`;
106
+ }
107
+ /**
108
+ * `SUM(CASE WHEN <col> THEN 1 ELSE 0 END)` — count of TRUE.
109
+ *
110
+ * Truthiness works on both sqlite 0/1 and pg boolean, and NULL falls to ELSE,
111
+ * which is what keeps a still-running execution (`success IS NULL`) out of both
112
+ * the success and the failure tally.
113
+ */
114
+ export function sumTrue(col) {
115
+ return sql `SUM(CASE WHEN ${col} THEN 1 ELSE 0 END)`;
116
+ }
117
+ /**
118
+ * `SUM(CASE WHEN <col> = false THEN 1 ELSE 0 END)` — count of FALSE.
119
+ *
120
+ * Deliberately an explicit comparison against a BOUND `false` param, not
121
+ * `WHEN NOT <col>`: `NOT NULL` is NULL, which would be correct here by
122
+ * accident, but the bound parameter is also what keeps this portable — libsql
123
+ * binds `false` as 0 and pg as a real boolean. A literal `= 0` makes Postgres
124
+ * throw `operator does not exist: boolean = integer`.
125
+ */
126
+ export function sumFalse(col) {
127
+ return sql `SUM(CASE WHEN ${col} = ${false} THEN 1 ELSE 0 END)`;
128
+ }
129
+ //# sourceMappingURL=dialect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dialect.js","sourceRoot":"","sources":["../../src/state/dialect.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAa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,CAAC;AAC3D,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,OAAO,CAAC,GAAe;IACrC,OAAO,GAAG,CAAA,iBAAiB,GAAG,qBAAqB,CAAC;AACtD,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,QAAQ,CAAC,GAAe;IACtC,OAAO,GAAG,CAAA,iBAAiB,GAAG,MAAM,KAAK,qBAAqB,CAAC;AACjE,CAAC"}
@@ -1,4 +1,6 @@
1
- import type Database from "better-sqlite3";
1
+ import { type SQL } from "drizzle-orm";
2
+ import type { ExtensionStatusMap, SkillsStatus } from "lastlight-workflow-engine";
3
+ import { type StateClient, type StateTables } from "./client.js";
2
4
  import type { TriggerActorType } from "./user-store.js";
3
5
  export interface ExecutionRecord {
4
6
  id: string;
@@ -48,16 +50,17 @@ export interface ExecutionRecord {
48
50
  /** Result subtype, e.g. "success" or "error_max_turns". */
49
51
  stopReason?: string;
50
52
  /**
51
- * JSON-serialized {@link ExtensionStatusMap} — which agentic-pi extensions
52
- * (file-search / github / web-search) were active for this execution.
53
+ * Which agentic-pi extensions (file-search / github / web-search) were active
54
+ * for this execution. A real JSON column, so this travels as an OBJECT in
55
+ * both directions and nothing on either side stringifies it.
53
56
  */
54
- extensionStatus?: string;
57
+ extensionStatus?: ExtensionStatusMap;
55
58
  /**
56
- * JSON-serialized {@link SkillsStatus} — agentic-pi's skill-loading status
57
- * for this execution (which skills were discovered/available). Null when
58
- * the run reported no skills.
59
+ * agentic-pi's skill-loading status for this execution (which skills were
60
+ * discovered/available). A real JSON column, like {@link extensionStatus}.
61
+ * Absent when the run reported no skills.
59
62
  */
60
- skillsStatus?: string;
63
+ skillsStatus?: SkillsStatus;
61
64
  /**
62
65
  * Workflow run that owns this execution. Scopes dedup: a fresh re-trigger
63
66
  * creates a new workflow_run_id, so `shouldRunPhase` won't find matching
@@ -77,10 +80,10 @@ export interface ExecutionOutcomeCounts {
77
80
  * selects (issue #325).
78
81
  *
79
82
  * `executions.success` is not a health signal and must not be read as one.
80
- * Two paths write `success = 0` deliberately, having failed at nothing:
83
+ * Two paths write `success = false` deliberately, having failed at nothing:
81
84
  *
82
85
  * - **`skipped`** — {@link ExecutionStore.recordSkippedPhase}. Stored
83
- * `success = 0` so {@link ExecutionStore.shouldRunPhase} re-evaluates the
86
+ * `success = false` so {@link ExecutionStore.shouldRunPhase} re-evaluates the
84
87
  * node on resume. The phase never ran.
85
88
  * - **`error_quota`** — the k8s `ResourceQuota` rejected the pod. The runner
86
89
  * treats it as an ordinary phase failure precisely so the run REQUEUES
@@ -98,17 +101,52 @@ export interface ExecutionOutcomeCounts {
98
101
  *
99
102
  * `success IS NULL` (still in flight) matches no bucket on purpose: it counts
100
103
  * toward `COUNT(*)` and toward nothing else, so a stacked bar can legitimately
101
- * be shorter than the execution total.
104
+ * be shorter than the execution total. That is why every arm goes through
105
+ * {@link sumTrue} — a `CASE WHEN <predicate>` where NULL falls to the ELSE in
106
+ * both dialects — and why the three that test for failure compare against a
107
+ * BOUND `${false}` rather than a literal `0`, which Postgres rejects outright
108
+ * (`operator does not exist: boolean = integer`).
102
109
  *
103
110
  * Note `condition_not_met` — a generic-loop `until_bash` check that ran and
104
- * came back red — is stored `success = 1` and therefore lands in `succeeded`.
105
- * It really executed and really cost tokens; only its per-row rendering is
106
- * muted (`execMark`, `packages/cli/src/cli-format.ts`).
111
+ * came back red — is stored `success = true` and therefore lands in
112
+ * `succeeded`. It really executed and really cost tokens; only its per-row
113
+ * rendering is muted (`execMark`, `packages/cli/src/cli-format.ts`).
107
114
  */
108
- export declare const EXECUTION_OUTCOME_COLUMNS = "\n SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) AS succeeded,\n SUM(CASE WHEN success = 0 AND stop_reason = 'skipped' THEN 1 ELSE 0 END) AS skipped,\n SUM(CASE WHEN success = 0 AND stop_reason = 'error_quota' THEN 1 ELSE 0 END) AS deferred,\n SUM(CASE WHEN success = 0\n AND (stop_reason IS NULL OR stop_reason NOT IN ('skipped', 'error_quota'))\n THEN 1 ELSE 0 END) AS failed";
115
+ export declare const executionOutcomeColumns: ({ executions }: StateTables) => SQL;
116
+ /** One aggregated chat thread — the shape both thread reads return. */
117
+ interface ChatThreadSummary {
118
+ triggerId: string;
119
+ agentSessionId: string | null;
120
+ platform: string | null;
121
+ firstStartedAt: string;
122
+ lastActivityAt: string;
123
+ turnCount: number;
124
+ totalCost: number;
125
+ inputTokens: number;
126
+ outputTokens: number;
127
+ cacheReadTokens: number;
128
+ lastAssistantContent: string | null;
129
+ repo: string | null;
130
+ }
131
+ /** The per-bucket shape {@link ExecutionStore.dailyStats} / `hourlyStats` return. */
132
+ type BucketStats = ExecutionOutcomeCounts & {
133
+ date: string;
134
+ executions: number;
135
+ totalTokens: number;
136
+ inputTokens: number;
137
+ outputTokens: number;
138
+ cacheReadTokens: number;
139
+ costUsd: number;
140
+ };
109
141
  export declare class ExecutionStore {
110
- private db;
111
- constructor(db: Database.Database);
142
+ private client;
143
+ /**
144
+ * Table objects for THIS client's dialect. Every method destructures what it
145
+ * needs off this instead of importing from `schema/sqlite.js` — see
146
+ * `client.ts` → {@link tablesOf} for why the cast alone cannot do it.
147
+ */
148
+ private readonly t;
149
+ constructor(client: StateClient);
112
150
  /**
113
151
  * Append a started phase to the ledger.
114
152
  *
@@ -118,13 +156,13 @@ export declare class ExecutionStore {
118
156
  * qualified value from anywhere else is normalized rather than stored as a
119
157
  * second shape.
120
158
  */
121
- recordStart(record: Omit<ExecutionRecord, "finishedAt" | "success" | "error" | "turns" | "durationMs">): void;
159
+ recordStart(record: Omit<ExecutionRecord, "finishedAt" | "success" | "error" | "turns" | "durationMs">): Promise<void>;
122
160
  /**
123
161
  * Mid-run update: persist the agent session id as soon as the executor sees
124
162
  * the stream-json `system/init` line. Lets the dashboard surface the live
125
163
  * session log for an in-flight phase, not just for completed ones.
126
164
  */
127
- recordSessionId(id: string, sessionId: string): void;
165
+ recordSessionId(id: string, sessionId: string): Promise<void>;
128
166
  /**
129
167
  * Persist the final assistant text for a loop-iteration execution.
130
168
  * Used by the runner when a scratch slot would otherwise inline the
@@ -132,16 +170,16 @@ export declare class ExecutionStore {
132
170
  * stores `lastOutputExecutionId` and resolves the text through
133
171
  * `getExecutionOutput` on read.
134
172
  */
135
- recordOutputText(id: string, output: string): void;
173
+ recordOutputText(id: string, output: string): Promise<void>;
136
174
  /** Read the persisted output text for an execution, or null if none. */
137
- getExecutionOutput(id: string): string | null;
175
+ getExecutionOutput(id: string): Promise<string | null>;
138
176
  /**
139
177
  * Most recent finished execution's `output_text` for a phase (`skill`), or
140
178
  * null. Used by the reviewer loop on resume to re-derive a completed review's
141
179
  * verdict from its persisted output (a dedup-`done` review must not be
142
180
  * assumed APPROVED — it may have requested changes).
143
181
  */
144
- getPhaseOutput(skill: string, triggerId: string, workflowRunId?: string): string | null;
182
+ getPhaseOutput(skill: string, triggerId: string, workflowRunId?: string): Promise<string | null>;
145
183
  recordFinish(id: string, result: {
146
184
  success: boolean;
147
185
  error?: string;
@@ -155,21 +193,21 @@ export declare class ExecutionStore {
155
193
  outputTokens?: number;
156
194
  apiDurationMs?: number;
157
195
  stopReason?: string;
158
- /** JSON-serialized ExtensionStatusMap (extensions active this run). */
159
- extensionStatus?: string;
160
- /** JSON-serialized SkillsStatus (skills available this run). */
161
- skillsStatus?: string;
162
- }): void;
196
+ /** Extensions active this run. An OBJECT — the column is real JSON. */
197
+ extensionStatus?: ExtensionStatusMap;
198
+ /** Skills available this run. An OBJECT — the column is real JSON. */
199
+ skillsStatus?: SkillsStatus;
200
+ }): Promise<void>;
163
201
  /**
164
202
  * Record a phase that the scheduler skipped because its trigger rule was
165
203
  * not satisfied (a failed/skipped upstream cascaded down a chain). The
166
204
  * executions ledger is the single source of truth the dashboard derives
167
205
  * phase status from, so skips are written here too — as a finished,
168
- * non-successful row (`success = 0`, `stop_reason = 'skipped'`). Because it
169
- * is not `success = 1`, `shouldRunPhase` re-evaluates it on resume (the node
170
- * will simply be re-skipped if the upstream is still failed).
206
+ * non-successful row (`success = false`, `stop_reason = 'skipped'`). Because
207
+ * it is not `success = true`, `shouldRunPhase` re-evaluates it on resume (the
208
+ * node will simply be re-skipped if the upstream is still failed).
171
209
  */
172
- recordSkippedPhase(skill: string, triggerId: string, workflowRunId?: string, repo?: string, owner?: string): void;
210
+ recordSkippedPhase(skill: string, triggerId: string, workflowRunId?: string, repo?: string, owner?: string): Promise<void>;
173
211
  /**
174
212
  * List chat threads aggregated from the executions table.
175
213
  *
@@ -180,35 +218,9 @@ export declare class ExecutionStore {
180
218
  * the on-disk jsonl when streaming messages) and with `messaging_messages`
181
219
  * for the most recent assistant text (preview snippet).
182
220
  */
183
- listChatThreads(limit: number): {
184
- triggerId: string;
185
- agentSessionId: string | null;
186
- platform: string | null;
187
- firstStartedAt: string;
188
- lastActivityAt: string;
189
- turnCount: number;
190
- totalCost: number;
191
- inputTokens: number;
192
- outputTokens: number;
193
- cacheReadTokens: number;
194
- lastAssistantContent: string | null;
195
- repo: string | null;
196
- }[];
221
+ listChatThreads(limit: number): Promise<ChatThreadSummary[]>;
197
222
  /** Look up a single chat thread by its messaging session id (= trigger_id). */
198
- getChatThread(triggerId: string): {
199
- triggerId: string;
200
- agentSessionId: string | null;
201
- platform: string | null;
202
- firstStartedAt: string;
203
- lastActivityAt: string;
204
- turnCount: number;
205
- totalCost: number;
206
- inputTokens: number;
207
- outputTokens: number;
208
- cacheReadTokens: number;
209
- lastAssistantContent: string | null;
210
- repo: string | null;
211
- } | null;
223
+ getChatThread(triggerId: string): Promise<ChatThreadSummary | null>;
212
224
  /**
213
225
  * The repo a sandbox session ran against, resolved from the `executions`
214
226
  * ledger by its `session_id` (issue #169).
@@ -218,9 +230,9 @@ export declare class ExecutionStore {
218
230
  * session list by the same allowed-repo set as everything else. Returns null
219
231
  * for a session we have no execution row for — those stay visible.
220
232
  */
221
- repoForSessionId(sessionId: string): string | null;
233
+ repoForSessionId(sessionId: string): Promise<string | null>;
222
234
  /** Check if a skill is currently running for a given trigger */
223
- isRunning(skill: string, triggerId: string): boolean;
235
+ isRunning(skill: string, triggerId: string): Promise<boolean>;
224
236
  /**
225
237
  * Total USD spent by every execution belonging to a run of one of
226
238
  * `workflowNames` for this trigger — the cumulative per-PR cost the
@@ -236,7 +248,7 @@ export declare class ExecutionStore {
236
248
  * OAuth/subscription run) contribute 0 — the brake must never be tripped by
237
249
  * missing data.
238
250
  */
239
- costForTriggerWorkflows(triggerId: string, workflowNames: string[]): number;
251
+ costForTriggerWorkflows(triggerId: string, workflowNames: string[]): Promise<number>;
240
252
  /**
241
253
  * Did `workflowRunId` complete phase `phaseName` successfully?
242
254
  *
@@ -247,9 +259,9 @@ export declare class ExecutionStore {
247
259
  * `on_output.requires_marker: DIAGNOSIS_COMPLETE`, so a succeeded row for it
248
260
  * is equivalent to the marker having been emitted.
249
261
  */
250
- phaseSucceededInRun(workflowRunId: string, phaseName: string): boolean;
262
+ phaseSucceededInRun(workflowRunId: string, phaseName: string): Promise<boolean>;
251
263
  /** Check if a skill has already completed successfully for a given trigger */
252
- isCompleted(skill: string, triggerId: string): boolean;
264
+ isCompleted(skill: string, triggerId: string): Promise<boolean>;
253
265
  /**
254
266
  * Check if a phase should run: not currently running AND not already
255
267
  * succeeded. When `workflowRunId` is provided, scopes the check to that
@@ -258,43 +270,61 @@ export declare class ExecutionStore {
258
270
  * for the same trigger exists. Omit `workflowRunId` for legacy callers
259
271
  * (e.g. chat/status-report dedup) that want the old trigger-wide scope.
260
272
  */
261
- shouldRunPhase(skill: string, triggerId: string, workflowRunId?: string): "run" | "running" | "done";
273
+ shouldRunPhase(skill: string, triggerId: string, workflowRunId?: string): Promise<"run" | "running" | "done">;
262
274
  /** Mark all stale "running" executions for a skill/trigger as failed.
263
275
  * Called when we detect no matching Docker container is alive. */
264
- markStaleAsFailed(skill: string, triggerId: string, workflowRunId?: string): number;
276
+ markStaleAsFailed(skill: string, triggerId: string, workflowRunId?: string): Promise<number>;
265
277
  /**
266
278
  * Mark every unfinished execution row for a trigger as failed, regardless
267
279
  * of skill. Used by the boot-time recovery sweep to clear out phases that
268
280
  * were running when the harness crashed/restarted, so the runner's dedup
269
281
  * logic doesn't think they're still in flight.
270
282
  */
271
- markAllStaleForTrigger(triggerId: string, reason: string): number;
283
+ markAllStaleForTrigger(triggerId: string, reason: string): Promise<number>;
272
284
  /**
273
285
  * Mark the most recent execution for a skill/trigger as failed.
274
286
  * Used when the agent SDK reported success but the orchestrator decided
275
287
  * the business outcome was a failure (e.g. guardrails BLOCKED, reviewer
276
288
  * REQUEST_CHANGES). Without this, runPhase would skip the phase on the
277
- * next run because the DB still says success=1.
289
+ * next run because the DB still says success=true.
290
+ *
291
+ * Raw because of the "newest row wins" correlated subquery. Note the two
292
+ * shapes it needs: the SET column is written UNQUALIFIED (`SET
293
+ * "executions"."success" = …` is not legal SQL in either dialect), and the
294
+ * false is a BOUND param — libsql binds it as 0 and Postgres as a real
295
+ * boolean, where a literal `= 0` would throw `operator does not exist:
296
+ * boolean = integer`.
278
297
  */
279
- markLatestAsFailed(skill: string, triggerId: string, reason: string, workflowRunId?: string): number;
298
+ markLatestAsFailed(skill: string, triggerId: string, reason: string, workflowRunId?: string): Promise<number>;
280
299
  /** Get recent executions for a skill */
281
- recentExecutions(skill: string, limit?: number): ExecutionRecord[];
282
- /** Count consecutive failures for a skill (for cron failure tracking) */
283
- consecutiveFailures(skill: string): number;
300
+ recentExecutions(skill: string, limit?: number): Promise<ExecutionRecord[]>;
301
+ /**
302
+ * Count consecutive failures for a skill (for cron failure tracking).
303
+ *
304
+ * The compare is `=== false`, not `=== 0`: `success` is a boolean-mode
305
+ * column, so an integer compare is never true and this would report a
306
+ * permanent zero — silently disarming the cron failure alert.
307
+ */
308
+ consecutiveFailures(skill: string): Promise<number>;
284
309
  /** Get all executions with pagination */
285
- allExecutions(limit?: number, offset?: number): ExecutionRecord[];
310
+ allExecutions(limit?: number, offset?: number): Promise<ExecutionRecord[]>;
286
311
  /**
287
312
  * Free-text search across the `executions` ledger — matches `error`, `skill`,
288
- * or `repo` against a substring (case-insensitive via SQLite's LIKE). Used by
289
- * the `/admin/api/log-search` endpoint and the `lastlight logs search` CLI to
290
- * find failing/relevant phases without SSHing to the box. Parameterized; the
291
- * pattern is escaped so user input can't smuggle LIKE wildcards.
313
+ * or `repo` against a substring. Used by the `/admin/api/log-search` endpoint
314
+ * and the `lastlight logs search` CLI to find failing/relevant phases without
315
+ * SSHing to the box. Parameterized; the pattern is escaped so user input
316
+ * can't smuggle LIKE wildcards.
317
+ *
318
+ * Raw, because `LIKE … ESCAPE '\'` has no query-builder spelling. Both sides
319
+ * are `lower()`ed rather than leaning on SQLite's case-insensitive LIKE,
320
+ * which Postgres does not share — the case-insensitivity is the feature here,
321
+ * not an accident of the dialect.
292
322
  *
293
323
  * Matches and returns the QUALIFIED repo, because that is what somebody types
294
324
  * (issue #279) — searching `nearform/lastlight` against the bare column found
295
325
  * no phase row at all.
296
326
  */
297
- searchErrors(query: string, limit?: number): Array<{
327
+ searchErrors(query: string, limit?: number): Promise<Array<{
298
328
  id: string;
299
329
  skill: string;
300
330
  repo?: string;
@@ -305,7 +335,7 @@ export declare class ExecutionStore {
305
335
  sessionId?: string;
306
336
  workflowRunId?: string;
307
337
  triggerId: string;
308
- }>;
338
+ }>>;
309
339
  /**
310
340
  * Get every execution recorded for a workflow run, with camelCase fields
311
341
  * ready for the dashboard. Ordered by start time ascending so phases
@@ -314,11 +344,11 @@ export declare class ExecutionStore {
314
344
  * falls back to the legacy trigger-wide scope for rows written before the
315
345
  * workflow_run_id column existed.
316
346
  */
317
- getExecutionsForWorkflowRun(workflowRunId: string, triggerId: string, workflowName?: string): ExecutionRecord[];
347
+ getExecutionsForWorkflowRun(workflowRunId: string, triggerId: string, workflowName?: string): Promise<ExecutionRecord[]>;
318
348
  /** Get currently running executions (no finished_at) */
319
- runningExecutions(): ExecutionRecord[];
349
+ runningExecutions(): Promise<ExecutionRecord[]>;
320
350
  /** Aggregate execution stats */
321
- executionStats(): {
351
+ executionStats(): Promise<{
322
352
  total_executions: number;
323
353
  today_count: number;
324
354
  by_skill: Record<string, ExecutionOutcomeCounts & {
@@ -326,7 +356,7 @@ export declare class ExecutionStore {
326
356
  }>;
327
357
  by_trigger: Record<string, number>;
328
358
  running: number;
329
- };
359
+ }>;
330
360
  /**
331
361
  * What ONE repo's agent work cost since `sinceIso`. The spend line of the
332
362
  * weekly digest.
@@ -335,28 +365,19 @@ export declare class ExecutionStore {
335
365
  * phase, carry no cost — so this sums with a COALESCE and reports the phase
336
366
  * count separately rather than implying the two are the same denominator.
337
367
  */
338
- repoCostSince(owner: string, repo: string, sinceIso: string): {
368
+ repoCostSince(owner: string, repo: string, sinceIso: string): Promise<{
339
369
  costUsd: number;
340
370
  phases: number;
341
- };
371
+ }>;
342
372
  /** Daily aggregated stats for the last N days */
343
- dailyStats(days: number): (ExecutionOutcomeCounts & {
344
- date: string;
345
- executions: number;
346
- totalTokens: number;
347
- inputTokens: number;
348
- outputTokens: number;
349
- cacheReadTokens: number;
350
- costUsd: number;
351
- })[];
373
+ dailyStats(days: number): Promise<BucketStats[]>;
352
374
  /** Hourly aggregated stats for the last N hours (UTC). Bucket key is `YYYY-MM-DDTHH`. */
353
- hourlyStats(hours: number): (ExecutionOutcomeCounts & {
354
- date: string;
355
- executions: number;
356
- totalTokens: number;
357
- inputTokens: number;
358
- outputTokens: number;
359
- cacheReadTokens: number;
360
- costUsd: number;
361
- })[];
375
+ hourlyStats(hours: number): Promise<BucketStats[]>;
376
+ /**
377
+ * The run-vs-trigger scope shared by the five methods that accept an optional
378
+ * `workflowRunId`: prefer the run when the caller knows it, fall back to the
379
+ * trigger-wide scope for legacy callers and pre-`workflow_run_id` rows.
380
+ */
381
+ private scope;
362
382
  }
383
+ export {};