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,32 @@
1
1
  import { randomUUID } from "crypto";
2
+ import { and, desc, eq, isNotNull, sql } from "drizzle-orm";
3
+ import { tablesOf } from "./client.js";
4
+ import { rows } from "./dialect.js";
5
+ /**
6
+ * A lexicographically-sortable row id: a fixed-width millisecond stamp, a
7
+ * per-process counter, then a uuid.
8
+ *
9
+ * `started_at` has millisecond resolution, so two fires in the same millisecond
10
+ * tie — and both reads below break that tie on `id`. Under sqlite the tiebreak
11
+ * used to be `rowid`, i.e. INSERTION ORDER, which PostgreSQL has no equivalent
12
+ * of; a plain `randomUUID()` is a total order but an ARBITRARY one, and
13
+ * arbitrary is not good enough here. `recentFailures` walks newest-first until
14
+ * it meets an `ok`, so a tie straddling an `ok` and a `failed` yields a
15
+ * different count depending which way it happened to sort — the failure alert
16
+ * flickering on a cron that is fine, or staying quiet on one that is not. This
17
+ * restores insertion order without a schema change and reads identically in
18
+ * both dialects.
19
+ *
20
+ * Rows written before this existed carry a bare uuid, which sorts differently —
21
+ * harmless, because the tiebreak only ever compares rows from the SAME
22
+ * millisecond and no millisecond spans the deploy that introduced it.
23
+ */
24
+ let idSeq = 0;
25
+ function creationOrderedId() {
26
+ const stamp = Date.now().toString(16).padStart(12, "0");
27
+ idSeq = (idSeq + 1) & 0xffffff;
28
+ return `${stamp}-${idSeq.toString(16).padStart(6, "0")}-${randomUUID()}`;
29
+ }
2
30
  /**
3
31
  * Owns the `cron_runs` ledger — one row per cron FIRE, scheduled or manual,
4
32
  * for `workflow:` and `handler:` crons alike.
@@ -16,40 +44,75 @@ import { randomUUID } from "crypto";
16
44
  * and vice versa (issue #327).
17
45
  */
18
46
  export class CronRunStore {
19
- db;
20
- constructor(db) {
21
- this.db = db;
47
+ client;
48
+ /**
49
+ * Table objects for THIS client's dialect. Every method destructures what it
50
+ * needs off this instead of importing from `schema/sqlite.js` — see
51
+ * `client.ts` → {@link tablesOf} for why the cast alone cannot do it.
52
+ */
53
+ t;
54
+ constructor(client) {
55
+ this.client = client;
56
+ this.t = tablesOf(client);
22
57
  }
23
58
  /** Insert a `running` row and return its id. */
24
- start(meta) {
25
- const id = randomUUID();
26
- this.db
27
- .prepare(`INSERT INTO cron_runs (id, cron_name, workflow, handler, source, actor, started_at, status)
28
- VALUES (?, ?, ?, ?, ?, ?, ?, 'running')`)
29
- .run(id, meta.cronName, meta.workflow ?? null, meta.handler ?? null, meta.source, meta.actor, new Date().toISOString());
59
+ async start(meta) {
60
+ const { cronRuns } = this.t;
61
+ const id = creationOrderedId();
62
+ await this.client.insert(cronRuns).values({
63
+ id,
64
+ cronName: meta.cronName,
65
+ workflow: meta.workflow ?? null,
66
+ handler: meta.handler ?? null,
67
+ source: meta.source,
68
+ actor: meta.actor,
69
+ startedAt: new Date().toISOString(),
70
+ status: "running",
71
+ });
30
72
  return id;
31
73
  }
32
74
  /** Stamp `finished_at` and the terminal fields. */
33
- finish(id, result) {
34
- this.db
35
- .prepare(`UPDATE cron_runs
36
- SET finished_at = ?, status = ?, repos_eligible = ?, repos_scanned = ?,
37
- discovered = ?, dispatched = ?, failures = ?, error = ?
38
- WHERE id = ?`)
39
- .run(new Date().toISOString(), result.status, result.reposEligible ?? null, result.reposScanned ?? null, result.discovered ?? null, result.dispatched ?? null, result.failures ?? null, result.error ?? null, id);
75
+ async finish(id, result) {
76
+ const { cronRuns } = this.t;
77
+ await this.client
78
+ .update(cronRuns)
79
+ .set({
80
+ finishedAt: new Date().toISOString(),
81
+ status: result.status,
82
+ reposEligible: result.reposEligible ?? null,
83
+ reposScanned: result.reposScanned ?? null,
84
+ discovered: result.discovered ?? null,
85
+ dispatched: result.dispatched ?? null,
86
+ failures: result.failures ?? null,
87
+ error: result.error ?? null,
88
+ })
89
+ .where(eq(cronRuns.id, id));
40
90
  }
41
- /** Most recent row per cron name — what the dashboard's crons list reads. */
42
- latestByCron() {
43
- const rows = this.db
44
- .prepare(`SELECT * FROM (
45
- SELECT *, ROW_NUMBER() OVER (
46
- PARTITION BY cron_name ORDER BY started_at DESC, rowid DESC
47
- ) AS rn
48
- FROM cron_runs
49
- ) WHERE rn = 1`)
50
- .all();
91
+ /**
92
+ * Most recent row per cron name — what the dashboard's crons list reads.
93
+ *
94
+ * A window function, so it stays raw SQL. Two portability notes: the derived
95
+ * table carries an explicit alias (Postgres rejects a `FROM` subquery without
96
+ * one), and `rn` is a `ROW_NUMBER()` rank — `rn = 1` is an integer compare,
97
+ * not a boolean. The tiebreak is `id DESC` — a real recency order, because
98
+ * the ids are minted in creation order ({@link creationOrderedId}); picking
99
+ * the wrong row of a tie here would show the dashboard the wrong outcome.
100
+ *
101
+ * `rows()` results are NOT column-mapped, so {@link mapCronRunRow} reads the
102
+ * raw snake_case column names.
103
+ */
104
+ async latestByCron() {
105
+ const { cronRuns } = this.t;
106
+ const ranked = await rows(this.client, sql `SELECT * FROM (
107
+ SELECT *, ROW_NUMBER() OVER (
108
+ PARTITION BY ${cronRuns.cronName}
109
+ ORDER BY ${cronRuns.startedAt} DESC, ${cronRuns.id} DESC
110
+ ) AS rn
111
+ FROM ${cronRuns}
112
+ ) AS ranked
113
+ WHERE rn = 1`);
51
114
  const map = new Map();
52
- for (const row of rows) {
115
+ for (const row of ranked) {
53
116
  const record = mapCronRunRow(row);
54
117
  map.set(record.cronName, record);
55
118
  }
@@ -63,20 +126,23 @@ export class CronRunStore {
63
126
  * it. Mirrors `ExecutionStore.consecutiveFailures` in shape so the
64
127
  * scheduler's call site changes key and table but not logic.
65
128
  *
66
- * `rowid DESC` breaks ties on `started_at`. Real crons fire minutes apart so
67
- * ties never arise in production, but without it "newest first" degrades to
68
- * SQLite's insertion order — i.e. OLDEST first — and the count walks the
69
- * sequence backwards, reporting 0 for a cron that has failed every time.
129
+ * `id DESC` breaks ties on `started_at`, and the ids are minted in creation
130
+ * order for exactly that purpose — see {@link creationOrderedId}. A merely
131
+ * DETERMINISTIC tiebreak is not sufficient here, which is the trap: this walk
132
+ * stops at the first `ok`, so a tie holding one `ok` and one `failed` returns
133
+ * a different count depending which sorts first. It has to be the RIGHT
134
+ * order, not just a stable one.
70
135
  */
71
- recentFailures(cronName) {
72
- const rows = this.db
73
- .prepare(`SELECT status FROM cron_runs
74
- WHERE cron_name = ? AND finished_at IS NOT NULL
75
- ORDER BY started_at DESC, rowid DESC
76
- LIMIT 10`)
77
- .all(cronName);
136
+ async recentFailures(cronName) {
137
+ const { cronRuns } = this.t;
138
+ const recent = await this.client
139
+ .select({ status: cronRuns.status })
140
+ .from(cronRuns)
141
+ .where(and(eq(cronRuns.cronName, cronName), isNotNull(cronRuns.finishedAt)))
142
+ .orderBy(desc(cronRuns.startedAt), desc(cronRuns.id))
143
+ .limit(10);
78
144
  let count = 0;
79
- for (const row of rows) {
145
+ for (const row of recent) {
80
146
  if (row.status !== "ok")
81
147
  count++;
82
148
  else
@@ -1 +1 @@
1
- {"version":3,"file":"cron-run-store.js","sourceRoot":"","sources":["../../src/state/cron-run-store.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAsDpC;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,YAAY;IACH;IAApB,YAAoB,EAAqB;QAArB,OAAE,GAAF,EAAE,CAAmB;IAAG,CAAC;IAE7C,gDAAgD;IAChD,KAAK,CAAC,IAAkB;QACtB,MAAM,EAAE,GAAG,UAAU,EAAE,CAAC;QACxB,IAAI,CAAC,EAAE;aACJ,OAAO,CACN;iDACyC,CAC1C;aACA,GAAG,CACF,EAAE,EACF,IAAI,CAAC,QAAQ,EACb,IAAI,CAAC,QAAQ,IAAI,IAAI,EACrB,IAAI,CAAC,OAAO,IAAI,IAAI,EACpB,IAAI,CAAC,MAAM,EACX,IAAI,CAAC,KAAK,EACV,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CACzB,CAAC;QACJ,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,mDAAmD;IACnD,MAAM,CAAC,EAAU,EAAE,MAAqB;QACtC,IAAI,CAA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GAAG,CAAC,QAA0B,IAAI,IAAI;QACjD,KAAK,EAAG,GAAG,CAAC,KAAuB,IAAI,IAAI;KAC5C,CAAC;AACJ,CAAC"}
@@ -1,4 +1,4 @@
1
- import Database from "better-sqlite3";
1
+ import { type Dialect, type StateClient } from "./client.js";
2
2
  import { ExecutionStore } from "./execution-store.js";
3
3
  import { CronRunStore } from "./cron-run-store.js";
4
4
  import { ApprovalStore } from "./approval-store.js";
@@ -44,16 +44,21 @@ export interface WorkflowOverride {
44
44
  * Lightweight SQLite state for operational tracking.
45
45
  * NOT for conversation history — only execution logs and rate limits.
46
46
  *
47
- * Construction root for the three per-table stores (issue #97): it opens the
48
- * single `Database` connection, runs {@link migrate}, and builds
49
- * {@link ExecutionStore} / {@link ApprovalStore} / {@link WorkflowRunStore} on
50
- * top of it (all sharing the one connection so better-sqlite3 transactions
51
- * span every store). Callers reach the stores via `db.runs` / `db.approvals` /
52
- * `db.executions`. StateDb itself retains only the cross-cutting cron-override
53
- * and workflow kill-switch concerns.
47
+ * Construction root for the seven per-table stores (issue #97): it opens the
48
+ * single Drizzle client, runs the compat pre-step + migrations, and builds the
49
+ * stores on top of it (all sharing the one client so transactions span every
50
+ * store). Callers reach the stores via `db.runs` / `db.approvals` /
51
+ * `db.executions` / …. StateDb itself retains only the cross-cutting
52
+ * cron-override and workflow kill-switch concerns.
53
+ *
54
+ * Construction is async — the driver is — so it is a static factory rather
55
+ * than a constructor: {@link StateDb.open} for production, {@link
56
+ * StateDb.fromClient} to adopt an existing Drizzle instance.
54
57
  */
55
58
  export declare class StateDb {
56
- private db;
59
+ private readonly _client;
60
+ private readonly _dialect;
61
+ private readonly closer?;
57
62
  /** Owns the `executions` ledger. */
58
63
  readonly executions: ExecutionStore;
59
64
  /** Owns the `workflow_approvals` table. */
@@ -76,11 +81,44 @@ export declare class StateDb {
76
81
  * `workflow_runs` and no `executions` row.
77
82
  */
78
83
  readonly cronRuns: CronRunStore;
79
- constructor(dbPath?: string);
84
+ /**
85
+ * Table objects for THIS client's dialect. Every method destructures what it
86
+ * needs off this instead of importing from `schema/sqlite.js` — see
87
+ * `client.ts` → {@link tablesOf} for why the cast alone cannot do it.
88
+ */
89
+ private readonly t;
90
+ private constructor();
91
+ /**
92
+ * Production entry: open (or create) the SQLite database, apply the legacy
93
+ * compat pre-step, then run migrations.
94
+ *
95
+ * Normalizes every accepted form HERE so no caller ever builds a `file:` URL:
96
+ * `:memory:` passes through, `file:` URLs pass through, and anything else is
97
+ * treated as a filesystem path.
98
+ *
99
+ * **`:memory:` is only safe for a caller that never opens a transaction.**
100
+ * The libsql client lazily opens a NEW connection after every
101
+ * `client.transaction()`, and for `:memory:` a new connection is a new, EMPTY
102
+ * database — so the first committed transaction silently discards the schema
103
+ * and every subsequent query fails with `no such table`. Verified on
104
+ * @libsql/client 0.17. Nothing in production uses `:memory:`; a test that
105
+ * touches `WorkflowRunStore`'s named ops or any `TeamStore` write must use a
106
+ * temp FILE instead.
107
+ */
108
+ static open(pathOrUrl?: string): Promise<StateDb>;
109
+ /**
110
+ * Test / Phase-4 entry: adopt an existing Drizzle instance. Runs no
111
+ * migrations — the caller owns the schema.
112
+ */
113
+ static fromClient(client: StateClient, dialect: Dialect, opts?: {
114
+ close?: () => void;
115
+ }): StateDb;
116
+ get client(): StateClient;
117
+ get dialect(): Dialect;
80
118
  /** Get the override row for a single cron, or null if none. */
81
- getCronOverride(name: string): CronOverride | null;
119
+ getCronOverride(name: string): Promise<CronOverride | null>;
82
120
  /** All override rows keyed by cron name. */
83
- getAllCronOverrides(): Map<string, CronOverride>;
121
+ getAllCronOverrides(): Promise<Map<string, CronOverride>>;
84
122
  /**
85
123
  * Upsert an override. Pass only the fields you want to change — undefined
86
124
  * fields preserve the existing value (or default to enabled=1, schedule=null
@@ -90,20 +128,20 @@ export declare class StateDb {
90
128
  enabled?: boolean;
91
129
  schedule?: string | null;
92
130
  updatedBy?: string;
93
- }): void;
131
+ }): Promise<void>;
94
132
  /** Remove the override entirely (revert to YAML defaults). */
95
- clearCronOverride(name: string): void;
96
- private deserializeCronOverride;
133
+ clearCronOverride(name: string): Promise<void>;
97
134
  /**
98
135
  * Cheap check used by every dispatch path. Returns true unless an explicit
99
136
  * `workflow_overrides` row says otherwise.
100
137
  */
101
- isWorkflowEnabled(name: string): boolean;
102
- getWorkflowOverride(name: string): WorkflowOverride | null;
103
- getAllWorkflowOverrides(): Map<string, WorkflowOverride>;
104
- setWorkflowEnabled(name: string, enabled: boolean, updatedBy?: string): void;
105
- private deserializeWorkflowOverride;
106
- /** Expose the underlying Database instance (for SessionManager, etc.) */
107
- get database(): Database.Database;
108
- close(): void;
138
+ isWorkflowEnabled(name: string): Promise<boolean>;
139
+ getWorkflowOverride(name: string): Promise<WorkflowOverride | null>;
140
+ getAllWorkflowOverrides(): Promise<Map<string, WorkflowOverride>>;
141
+ setWorkflowEnabled(name: string, enabled: boolean, updatedBy?: string): Promise<void>;
142
+ /**
143
+ * Async by contract: libsql's `close()` is synchronous today, but a Postgres
144
+ * pool's is not, and every caller already awaits this.
145
+ */
146
+ close(): Promise<void>;
109
147
  }
package/dist/state/db.js CHANGED
@@ -1,6 +1,12 @@
1
- import Database from "better-sqlite3";
2
- import { resolve } from "path";
3
- import { migrate } from "./migrate.js";
1
+ import { createClient } from "@libsql/client";
2
+ import { drizzle } from "drizzle-orm/libsql";
3
+ import { migrate } from "drizzle-orm/libsql/migrator";
4
+ import { eq } from "drizzle-orm";
5
+ import { fileURLToPath } from "node:url";
6
+ import { resolve } from "node:path";
7
+ import * as sqliteSchema from "./schema/sqlite.js";
8
+ import { applyLegacySqliteCompat } from "./legacy-sqlite.js";
9
+ import { makeOpSerializer, tablesOf, } from "./client.js";
4
10
  import { ExecutionStore } from "./execution-store.js";
5
11
  import { CronRunStore } from "./cron-run-store.js";
6
12
  import { ApprovalStore } from "./approval-store.js";
@@ -16,20 +22,30 @@ export { TeamStore } from "./team-store.js";
16
22
  export { FeedbackStore } from "./feedback-store.js";
17
23
  export { CronRunStore } from "./cron-run-store.js";
18
24
  const DEFAULT_DB_PATH = "lastlight.db";
25
+ /**
26
+ * The generated migrations live at the `apps/server/` package root, so this
27
+ * must resolve from BOTH `src/state/` (tsx dev) and `dist/state/` (compiled).
28
+ */
29
+ const MIGRATIONS_DIR = fileURLToPath(new URL("../../drizzle/sqlite", import.meta.url));
19
30
  /**
20
31
  * Lightweight SQLite state for operational tracking.
21
32
  * NOT for conversation history — only execution logs and rate limits.
22
33
  *
23
- * Construction root for the three per-table stores (issue #97): it opens the
24
- * single `Database` connection, runs {@link migrate}, and builds
25
- * {@link ExecutionStore} / {@link ApprovalStore} / {@link WorkflowRunStore} on
26
- * top of it (all sharing the one connection so better-sqlite3 transactions
27
- * span every store). Callers reach the stores via `db.runs` / `db.approvals` /
28
- * `db.executions`. StateDb itself retains only the cross-cutting cron-override
29
- * and workflow kill-switch concerns.
34
+ * Construction root for the seven per-table stores (issue #97): it opens the
35
+ * single Drizzle client, runs the compat pre-step + migrations, and builds the
36
+ * stores on top of it (all sharing the one client so transactions span every
37
+ * store). Callers reach the stores via `db.runs` / `db.approvals` /
38
+ * `db.executions` / …. StateDb itself retains only the cross-cutting
39
+ * cron-override and workflow kill-switch concerns.
40
+ *
41
+ * Construction is async — the driver is — so it is a static factory rather
42
+ * than a constructor: {@link StateDb.open} for production, {@link
43
+ * StateDb.fromClient} to adopt an existing Drizzle instance.
30
44
  */
31
45
  export class StateDb {
32
- db;
46
+ _client;
47
+ _dialect;
48
+ closer;
33
49
  /** Owns the `executions` ledger. */
34
50
  executions;
35
51
  /** Owns the `workflow_approvals` table. */
@@ -52,41 +68,101 @@ export class StateDb {
52
68
  * `workflow_runs` and no `executions` row.
53
69
  */
54
70
  cronRuns;
55
- constructor(dbPath) {
56
- // ":memory:" stays a real per-connection in-memory DB (used by tests for
57
- // isolation) — only filesystem paths go through resolve(). Previously
58
- // resolve(":memory:") produced a shared on-disk file named ":memory:",
59
- // which let parallel test files contend on one DB and deadlock once the
60
- // stores started holding write transactions.
61
- const target = dbPath === ":memory:" ? ":memory:" : resolve(dbPath || DEFAULT_DB_PATH);
62
- this.db = new Database(target);
63
- this.db.pragma("journal_mode = WAL");
64
- migrate(this.db);
65
- this.executions = new ExecutionStore(this.db);
66
- this.approvals = new ApprovalStore(this.db);
67
- this.runs = new WorkflowRunStore(this.db, { approvals: this.approvals });
68
- this.users = new UserStore(this.db);
69
- this.teams = new TeamStore(this.db);
70
- this.feedback = new FeedbackStore(this.db);
71
- this.cronRuns = new CronRunStore(this.db);
71
+ /**
72
+ * Table objects for THIS client's dialect. Every method destructures what it
73
+ * needs off this instead of importing from `schema/sqlite.js` — see
74
+ * `client.ts` → {@link tablesOf} for why the cast alone cannot do it.
75
+ */
76
+ t;
77
+ constructor(_client, _dialect, closer) {
78
+ this._client = _client;
79
+ this._dialect = _dialect;
80
+ this.closer = closer;
81
+ this.t = tablesOf(_client);
82
+ // ONE serializer per CONNECTION, handed to every store that opens a
83
+ // transaction. A per-store chain would leave WorkflowRunStore's five named
84
+ // ops racing TeamStore's four on this same client — see makeOpSerializer.
85
+ const serialize = makeOpSerializer();
86
+ this.executions = new ExecutionStore(_client);
87
+ this.approvals = new ApprovalStore(_client);
88
+ this.runs = new WorkflowRunStore(_client, { approvals: this.approvals, serialize });
89
+ this.users = new UserStore(_client);
90
+ this.teams = new TeamStore(_client, { serialize });
91
+ this.feedback = new FeedbackStore(_client);
92
+ this.cronRuns = new CronRunStore(_client);
93
+ }
94
+ /**
95
+ * Production entry: open (or create) the SQLite database, apply the legacy
96
+ * compat pre-step, then run migrations.
97
+ *
98
+ * Normalizes every accepted form HERE so no caller ever builds a `file:` URL:
99
+ * `:memory:` passes through, `file:` URLs pass through, and anything else is
100
+ * treated as a filesystem path.
101
+ *
102
+ * **`:memory:` is only safe for a caller that never opens a transaction.**
103
+ * The libsql client lazily opens a NEW connection after every
104
+ * `client.transaction()`, and for `:memory:` a new connection is a new, EMPTY
105
+ * database — so the first committed transaction silently discards the schema
106
+ * and every subsequent query fails with `no such table`. Verified on
107
+ * @libsql/client 0.17. Nothing in production uses `:memory:`; a test that
108
+ * touches `WorkflowRunStore`'s named ops or any `TeamStore` write must use a
109
+ * temp FILE instead.
110
+ */
111
+ static async open(pathOrUrl) {
112
+ const input = pathOrUrl || DEFAULT_DB_PATH;
113
+ // Case-insensitive: URL schemes are, and `POSTGRES://…` reaching the libsql
114
+ // client produces an opaque ConnectionFailed instead of this message.
115
+ if (/^postgres(ql)?:\/\//i.test(input)) {
116
+ throw new Error(`PG runtime not enabled: StateDb.open() cannot open "${input}". ` +
117
+ `The Postgres dialect is test-only for now — construct it with StateDb.fromClient().`);
118
+ }
119
+ const url = input === ":memory:" || input.startsWith("file:") ? input : `file:${resolve(input)}`;
120
+ const raw = createClient({ url });
121
+ await raw.execute("PRAGMA journal_mode = WAL");
122
+ // Best-effort only: this pragma is connection-scoped and the libsql client
123
+ // opens a fresh connection after every transaction, so it covers just the
124
+ // pre-first-transaction window. The op serializer is the real defense.
125
+ await raw.execute("PRAGMA busy_timeout = 5000");
126
+ await applyLegacySqliteCompat(raw);
127
+ const client = drizzle(raw, { schema: sqliteSchema });
128
+ await migrate(client, { migrationsFolder: MIGRATIONS_DIR });
129
+ return new StateDb(client, "sqlite", () => raw.close());
130
+ }
131
+ /**
132
+ * Test / Phase-4 entry: adopt an existing Drizzle instance. Runs no
133
+ * migrations — the caller owns the schema.
134
+ */
135
+ static fromClient(client, dialect, opts) {
136
+ return new StateDb(client, dialect, opts?.close);
137
+ }
138
+ get client() {
139
+ return this._client;
140
+ }
141
+ get dialect() {
142
+ return this._dialect;
72
143
  }
73
144
  // ── Cron overrides ─────────────────────────────────────────────
74
145
  /** Get the override row for a single cron, or null if none. */
75
- getCronOverride(name) {
76
- const row = this.db
77
- .prepare(`SELECT name, enabled, schedule, updated_at, updated_by FROM cron_overrides WHERE name = ?`)
78
- .get(name);
79
- return row ? this.deserializeCronOverride(row) : null;
146
+ async getCronOverride(name) {
147
+ const { cronOverrides } = this.t;
148
+ const [row] = await this._client
149
+ .select()
150
+ .from(cronOverrides)
151
+ .where(eq(cronOverrides.name, name))
152
+ .limit(1);
153
+ return row ? { ...row, schedule: row.schedule ?? null, updatedBy: row.updatedBy ?? null } : null;
80
154
  }
81
155
  /** All override rows keyed by cron name. */
82
- getAllCronOverrides() {
83
- const rows = this.db
84
- .prepare(`SELECT name, enabled, schedule, updated_at, updated_by FROM cron_overrides`)
85
- .all();
156
+ async getAllCronOverrides() {
157
+ const { cronOverrides } = this.t;
158
+ const rows = await this._client.select().from(cronOverrides);
86
159
  const map = new Map();
87
160
  for (const row of rows) {
88
- const o = this.deserializeCronOverride(row);
89
- map.set(o.name, o);
161
+ map.set(row.name, {
162
+ ...row,
163
+ schedule: row.schedule ?? null,
164
+ updatedBy: row.updatedBy ?? null,
165
+ });
90
166
  }
91
167
  return map;
92
168
  }
@@ -95,89 +171,79 @@ export class StateDb {
95
171
  * fields preserve the existing value (or default to enabled=1, schedule=null
96
172
  * on insert).
97
173
  */
98
- setCronOverride(name, patch) {
174
+ async setCronOverride(name, patch) {
175
+ const { cronOverrides } = this.t;
99
176
  const now = new Date().toISOString();
100
- const existing = this.getCronOverride(name);
177
+ const existing = await this.getCronOverride(name);
101
178
  const enabled = patch.enabled ?? existing?.enabled ?? true;
102
- const schedule = patch.schedule === undefined ? existing?.schedule ?? null : patch.schedule;
103
- this.db
104
- .prepare(`INSERT INTO cron_overrides (name, enabled, schedule, updated_at, updated_by)
105
- VALUES (?, ?, ?, ?, ?)
106
- ON CONFLICT(name) DO UPDATE SET
107
- enabled = excluded.enabled,
108
- schedule = excluded.schedule,
109
- updated_at = excluded.updated_at,
110
- updated_by = excluded.updated_by`)
111
- .run(name, enabled ? 1 : 0, schedule, now, patch.updatedBy ?? null);
179
+ const schedule = patch.schedule === undefined ? (existing?.schedule ?? null) : patch.schedule;
180
+ const values = { name, enabled, schedule, updatedAt: now, updatedBy: patch.updatedBy ?? null };
181
+ await this._client
182
+ .insert(cronOverrides)
183
+ .values(values)
184
+ .onConflictDoUpdate({
185
+ target: cronOverrides.name,
186
+ set: {
187
+ enabled: values.enabled,
188
+ schedule: values.schedule,
189
+ updatedAt: values.updatedAt,
190
+ updatedBy: values.updatedBy,
191
+ },
192
+ });
112
193
  }
113
194
  /** Remove the override entirely (revert to YAML defaults). */
114
- clearCronOverride(name) {
115
- this.db.prepare(`DELETE FROM cron_overrides WHERE name = ?`).run(name);
116
- }
117
- deserializeCronOverride(row) {
118
- return {
119
- name: row.name,
120
- enabled: row.enabled === 1,
121
- schedule: row.schedule ?? null,
122
- updatedAt: row.updated_at,
123
- updatedBy: row.updated_by ?? null,
124
- };
195
+ async clearCronOverride(name) {
196
+ const { cronOverrides } = this.t;
197
+ await this._client.delete(cronOverrides).where(eq(cronOverrides.name, name));
125
198
  }
126
199
  // ── Workflow overrides (kill switch) ───────────────────────────
127
200
  /**
128
201
  * Cheap check used by every dispatch path. Returns true unless an explicit
129
202
  * `workflow_overrides` row says otherwise.
130
203
  */
131
- isWorkflowEnabled(name) {
132
- const row = this.db
133
- .prepare(`SELECT enabled FROM workflow_overrides WHERE name = ?`)
134
- .get(name);
135
- if (!row)
136
- return true;
137
- return row.enabled === 1;
204
+ async isWorkflowEnabled(name) {
205
+ const { workflowOverrides } = this.t;
206
+ const [row] = await this._client
207
+ .select({ enabled: workflowOverrides.enabled })
208
+ .from(workflowOverrides)
209
+ .where(eq(workflowOverrides.name, name))
210
+ .limit(1);
211
+ return row ? row.enabled : true;
138
212
  }
139
- getWorkflowOverride(name) {
140
- const row = this.db
141
- .prepare(`SELECT name, enabled, updated_at, updated_by FROM workflow_overrides WHERE name = ?`)
142
- .get(name);
143
- return row ? this.deserializeWorkflowOverride(row) : null;
213
+ async getWorkflowOverride(name) {
214
+ const { workflowOverrides } = this.t;
215
+ const [row] = await this._client
216
+ .select()
217
+ .from(workflowOverrides)
218
+ .where(eq(workflowOverrides.name, name))
219
+ .limit(1);
220
+ return row ? { ...row, updatedBy: row.updatedBy ?? null } : null;
144
221
  }
145
- getAllWorkflowOverrides() {
146
- const rows = this.db
147
- .prepare(`SELECT name, enabled, updated_at, updated_by FROM workflow_overrides`)
148
- .all();
222
+ async getAllWorkflowOverrides() {
223
+ const { workflowOverrides } = this.t;
224
+ const rows = await this._client.select().from(workflowOverrides);
149
225
  const map = new Map();
150
- for (const row of rows) {
151
- const o = this.deserializeWorkflowOverride(row);
152
- map.set(o.name, o);
153
- }
226
+ for (const row of rows)
227
+ map.set(row.name, { ...row, updatedBy: row.updatedBy ?? null });
154
228
  return map;
155
229
  }
156
- setWorkflowEnabled(name, enabled, updatedBy) {
230
+ async setWorkflowEnabled(name, enabled, updatedBy) {
231
+ const { workflowOverrides } = this.t;
157
232
  const now = new Date().toISOString();
158
- this.db
159
- .prepare(`INSERT INTO workflow_overrides (name, enabled, updated_at, updated_by)
160
- VALUES (?, ?, ?, ?)
161
- ON CONFLICT(name) DO UPDATE SET
162
- enabled = excluded.enabled,
163
- updated_at = excluded.updated_at,
164
- updated_by = excluded.updated_by`)
165
- .run(name, enabled ? 1 : 0, now, updatedBy ?? null);
166
- }
167
- deserializeWorkflowOverride(row) {
168
- return {
169
- name: row.name,
170
- enabled: row.enabled === 1,
171
- updatedAt: row.updated_at,
172
- updatedBy: row.updated_by ?? null,
173
- };
174
- }
175
- /** Expose the underlying Database instance (for SessionManager, etc.) */
176
- get database() {
177
- return this.db;
233
+ await this._client
234
+ .insert(workflowOverrides)
235
+ .values({ name, enabled, updatedAt: now, updatedBy: updatedBy ?? null })
236
+ .onConflictDoUpdate({
237
+ target: workflowOverrides.name,
238
+ set: { enabled, updatedAt: now, updatedBy: updatedBy ?? null },
239
+ });
178
240
  }
179
- close() {
180
- this.db.close();
241
+ /**
242
+ * Async by contract: libsql's `close()` is synchronous today, but a Postgres
243
+ * pool's is not, and every caller already awaits this.
244
+ */
245
+ async close() {
246
+ this.closer?.();
181
247
  }
182
248
  }
183
249
  //# sourceMappingURL=db.js.map