@os-eco/overstory-cli 0.6.1

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 (170) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +381 -0
  3. package/agents/builder.md +137 -0
  4. package/agents/coordinator.md +263 -0
  5. package/agents/lead.md +301 -0
  6. package/agents/merger.md +160 -0
  7. package/agents/monitor.md +214 -0
  8. package/agents/reviewer.md +140 -0
  9. package/agents/scout.md +119 -0
  10. package/agents/supervisor.md +423 -0
  11. package/package.json +47 -0
  12. package/src/agents/checkpoint.test.ts +88 -0
  13. package/src/agents/checkpoint.ts +101 -0
  14. package/src/agents/hooks-deployer.test.ts +2040 -0
  15. package/src/agents/hooks-deployer.ts +607 -0
  16. package/src/agents/identity.test.ts +603 -0
  17. package/src/agents/identity.ts +384 -0
  18. package/src/agents/lifecycle.test.ts +196 -0
  19. package/src/agents/lifecycle.ts +183 -0
  20. package/src/agents/manifest.test.ts +746 -0
  21. package/src/agents/manifest.ts +354 -0
  22. package/src/agents/overlay.test.ts +676 -0
  23. package/src/agents/overlay.ts +308 -0
  24. package/src/beads/client.test.ts +217 -0
  25. package/src/beads/client.ts +202 -0
  26. package/src/beads/molecules.test.ts +338 -0
  27. package/src/beads/molecules.ts +198 -0
  28. package/src/commands/agents.test.ts +322 -0
  29. package/src/commands/agents.ts +287 -0
  30. package/src/commands/clean.test.ts +670 -0
  31. package/src/commands/clean.ts +618 -0
  32. package/src/commands/completions.test.ts +342 -0
  33. package/src/commands/completions.ts +887 -0
  34. package/src/commands/coordinator.test.ts +1530 -0
  35. package/src/commands/coordinator.ts +733 -0
  36. package/src/commands/costs.test.ts +1119 -0
  37. package/src/commands/costs.ts +564 -0
  38. package/src/commands/dashboard.test.ts +308 -0
  39. package/src/commands/dashboard.ts +838 -0
  40. package/src/commands/doctor.test.ts +294 -0
  41. package/src/commands/doctor.ts +213 -0
  42. package/src/commands/errors.test.ts +647 -0
  43. package/src/commands/errors.ts +248 -0
  44. package/src/commands/feed.test.ts +578 -0
  45. package/src/commands/feed.ts +361 -0
  46. package/src/commands/group.test.ts +262 -0
  47. package/src/commands/group.ts +511 -0
  48. package/src/commands/hooks.test.ts +458 -0
  49. package/src/commands/hooks.ts +253 -0
  50. package/src/commands/init.test.ts +347 -0
  51. package/src/commands/init.ts +650 -0
  52. package/src/commands/inspect.test.ts +670 -0
  53. package/src/commands/inspect.ts +431 -0
  54. package/src/commands/log.test.ts +1454 -0
  55. package/src/commands/log.ts +724 -0
  56. package/src/commands/logs.test.ts +379 -0
  57. package/src/commands/logs.ts +546 -0
  58. package/src/commands/mail.test.ts +1270 -0
  59. package/src/commands/mail.ts +771 -0
  60. package/src/commands/merge.test.ts +670 -0
  61. package/src/commands/merge.ts +355 -0
  62. package/src/commands/metrics.test.ts +444 -0
  63. package/src/commands/metrics.ts +143 -0
  64. package/src/commands/monitor.test.ts +191 -0
  65. package/src/commands/monitor.ts +390 -0
  66. package/src/commands/nudge.test.ts +230 -0
  67. package/src/commands/nudge.ts +372 -0
  68. package/src/commands/prime.test.ts +470 -0
  69. package/src/commands/prime.ts +381 -0
  70. package/src/commands/replay.test.ts +741 -0
  71. package/src/commands/replay.ts +360 -0
  72. package/src/commands/run.test.ts +431 -0
  73. package/src/commands/run.ts +351 -0
  74. package/src/commands/sling.test.ts +657 -0
  75. package/src/commands/sling.ts +661 -0
  76. package/src/commands/spec.test.ts +203 -0
  77. package/src/commands/spec.ts +168 -0
  78. package/src/commands/status.test.ts +430 -0
  79. package/src/commands/status.ts +398 -0
  80. package/src/commands/stop.test.ts +420 -0
  81. package/src/commands/stop.ts +151 -0
  82. package/src/commands/supervisor.test.ts +187 -0
  83. package/src/commands/supervisor.ts +535 -0
  84. package/src/commands/trace.test.ts +745 -0
  85. package/src/commands/trace.ts +325 -0
  86. package/src/commands/watch.test.ts +145 -0
  87. package/src/commands/watch.ts +247 -0
  88. package/src/commands/worktree.test.ts +786 -0
  89. package/src/commands/worktree.ts +311 -0
  90. package/src/config.test.ts +822 -0
  91. package/src/config.ts +829 -0
  92. package/src/doctor/agents.test.ts +454 -0
  93. package/src/doctor/agents.ts +396 -0
  94. package/src/doctor/config-check.test.ts +190 -0
  95. package/src/doctor/config-check.ts +183 -0
  96. package/src/doctor/consistency.test.ts +651 -0
  97. package/src/doctor/consistency.ts +294 -0
  98. package/src/doctor/databases.test.ts +290 -0
  99. package/src/doctor/databases.ts +218 -0
  100. package/src/doctor/dependencies.test.ts +184 -0
  101. package/src/doctor/dependencies.ts +175 -0
  102. package/src/doctor/logs.test.ts +251 -0
  103. package/src/doctor/logs.ts +295 -0
  104. package/src/doctor/merge-queue.test.ts +216 -0
  105. package/src/doctor/merge-queue.ts +144 -0
  106. package/src/doctor/structure.test.ts +291 -0
  107. package/src/doctor/structure.ts +198 -0
  108. package/src/doctor/types.ts +37 -0
  109. package/src/doctor/version.test.ts +136 -0
  110. package/src/doctor/version.ts +129 -0
  111. package/src/e2e/init-sling-lifecycle.test.ts +277 -0
  112. package/src/errors.ts +217 -0
  113. package/src/events/store.test.ts +660 -0
  114. package/src/events/store.ts +369 -0
  115. package/src/events/tool-filter.test.ts +330 -0
  116. package/src/events/tool-filter.ts +126 -0
  117. package/src/index.ts +316 -0
  118. package/src/insights/analyzer.test.ts +466 -0
  119. package/src/insights/analyzer.ts +203 -0
  120. package/src/logging/color.test.ts +142 -0
  121. package/src/logging/color.ts +71 -0
  122. package/src/logging/logger.test.ts +813 -0
  123. package/src/logging/logger.ts +266 -0
  124. package/src/logging/reporter.test.ts +259 -0
  125. package/src/logging/reporter.ts +109 -0
  126. package/src/logging/sanitizer.test.ts +190 -0
  127. package/src/logging/sanitizer.ts +57 -0
  128. package/src/mail/broadcast.test.ts +203 -0
  129. package/src/mail/broadcast.ts +92 -0
  130. package/src/mail/client.test.ts +773 -0
  131. package/src/mail/client.ts +223 -0
  132. package/src/mail/store.test.ts +705 -0
  133. package/src/mail/store.ts +387 -0
  134. package/src/merge/queue.test.ts +359 -0
  135. package/src/merge/queue.ts +231 -0
  136. package/src/merge/resolver.test.ts +1345 -0
  137. package/src/merge/resolver.ts +645 -0
  138. package/src/metrics/store.test.ts +667 -0
  139. package/src/metrics/store.ts +445 -0
  140. package/src/metrics/summary.test.ts +398 -0
  141. package/src/metrics/summary.ts +178 -0
  142. package/src/metrics/transcript.test.ts +356 -0
  143. package/src/metrics/transcript.ts +175 -0
  144. package/src/mulch/client.test.ts +671 -0
  145. package/src/mulch/client.ts +332 -0
  146. package/src/sessions/compat.test.ts +280 -0
  147. package/src/sessions/compat.ts +104 -0
  148. package/src/sessions/store.test.ts +873 -0
  149. package/src/sessions/store.ts +494 -0
  150. package/src/test-helpers.test.ts +124 -0
  151. package/src/test-helpers.ts +126 -0
  152. package/src/tracker/beads.ts +56 -0
  153. package/src/tracker/factory.test.ts +80 -0
  154. package/src/tracker/factory.ts +64 -0
  155. package/src/tracker/seeds.ts +182 -0
  156. package/src/tracker/types.ts +52 -0
  157. package/src/types.ts +724 -0
  158. package/src/watchdog/daemon.test.ts +1975 -0
  159. package/src/watchdog/daemon.ts +671 -0
  160. package/src/watchdog/health.test.ts +431 -0
  161. package/src/watchdog/health.ts +264 -0
  162. package/src/watchdog/triage.test.ts +164 -0
  163. package/src/watchdog/triage.ts +179 -0
  164. package/src/worktree/manager.test.ts +439 -0
  165. package/src/worktree/manager.ts +198 -0
  166. package/src/worktree/tmux.test.ts +1009 -0
  167. package/src/worktree/tmux.ts +509 -0
  168. package/templates/CLAUDE.md.tmpl +89 -0
  169. package/templates/hooks.json.tmpl +105 -0
  170. package/templates/overlay.md.tmpl +81 -0
@@ -0,0 +1,387 @@
1
+ /**
2
+ * SQLite-backed mail storage for inter-agent messaging.
3
+ *
4
+ * Provides low-level CRUD operations on the messages table.
5
+ * Uses bun:sqlite for zero-dependency, synchronous database access.
6
+ * The higher-level mail client (L2) wraps this store.
7
+ */
8
+
9
+ import { Database } from "bun:sqlite";
10
+ import { MailError } from "../errors.ts";
11
+ import type { MailMessage } from "../types.ts";
12
+ import { MAIL_MESSAGE_TYPES } from "../types.ts";
13
+
14
+ export interface MailStore {
15
+ insert(
16
+ message: Omit<MailMessage, "read" | "createdAt" | "payload"> & { payload?: string | null },
17
+ ): MailMessage;
18
+ getUnread(agentName: string): MailMessage[];
19
+ getAll(filters?: { from?: string; to?: string; unread?: boolean; limit?: number }): MailMessage[];
20
+ getById(id: string): MailMessage | null;
21
+ getByThread(threadId: string): MailMessage[];
22
+ markRead(id: string): void;
23
+ /** Delete messages matching the given criteria. Returns the number of messages deleted. */
24
+ purge(options: { all?: boolean; olderThanMs?: number; agent?: string }): number;
25
+ close(): void;
26
+ }
27
+
28
+ /** Row shape as stored in SQLite (snake_case columns, integer boolean). */
29
+ interface MessageRow {
30
+ id: string;
31
+ from_agent: string;
32
+ to_agent: string;
33
+ subject: string;
34
+ body: string;
35
+ type: string;
36
+ priority: string;
37
+ thread_id: string | null;
38
+ payload: string | null;
39
+ read: number;
40
+ created_at: string;
41
+ }
42
+
43
+ /** Build the CHECK constraint for message types from the runtime constant. */
44
+ const TYPE_CHECK = `CHECK(type IN (${MAIL_MESSAGE_TYPES.map((t) => `'${t}'`).join(",")}))`;
45
+
46
+ const CREATE_TABLE = `
47
+ CREATE TABLE IF NOT EXISTS messages (
48
+ id TEXT PRIMARY KEY,
49
+ from_agent TEXT NOT NULL,
50
+ to_agent TEXT NOT NULL,
51
+ subject TEXT NOT NULL,
52
+ body TEXT NOT NULL,
53
+ type TEXT NOT NULL DEFAULT 'status' ${TYPE_CHECK},
54
+ priority TEXT NOT NULL DEFAULT 'normal' CHECK(priority IN ('low','normal','high','urgent')),
55
+ thread_id TEXT,
56
+ payload TEXT,
57
+ read INTEGER NOT NULL DEFAULT 0,
58
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
59
+ )`;
60
+
61
+ /**
62
+ * Migrate an existing messages table to the current schema.
63
+ *
64
+ * Handles two migration paths:
65
+ * 1. Tables without CHECK constraints → recreate with constraints
66
+ * 2. Tables without payload column → add payload column
67
+ * 3. Tables with old CHECK constraints (missing protocol types) → recreate with new types
68
+ *
69
+ * SQLite does not support ALTER TABLE ADD CONSTRAINT, so constraint changes
70
+ * require recreating the table.
71
+ */
72
+ function migrateSchema(db: Database): void {
73
+ const row = db
74
+ .prepare<{ sql: string }, []>(
75
+ "SELECT sql FROM sqlite_master WHERE type='table' AND name='messages'",
76
+ )
77
+ .get();
78
+ if (!row) {
79
+ // Table doesn't exist yet; CREATE TABLE IF NOT EXISTS will handle it
80
+ return;
81
+ }
82
+
83
+ const hasCheckConstraints = row.sql.includes("CHECK");
84
+ const hasPayloadColumn = row.sql.includes("payload");
85
+ const hasProtocolTypes = row.sql.includes("worker_done");
86
+
87
+ // If schema is fully up to date, nothing to do
88
+ if (hasCheckConstraints && hasPayloadColumn && hasProtocolTypes) {
89
+ return;
90
+ }
91
+
92
+ // If only missing the payload column (has correct CHECK constraints), use ALTER TABLE
93
+ if (hasCheckConstraints && hasProtocolTypes && !hasPayloadColumn) {
94
+ db.exec("ALTER TABLE messages ADD COLUMN payload TEXT");
95
+ return;
96
+ }
97
+
98
+ // Need to recreate the table (missing CHECK constraints or needs type update)
99
+ const validTypes = MAIL_MESSAGE_TYPES.map((t) => `'${t}'`).join(",");
100
+ db.exec("BEGIN TRANSACTION");
101
+ try {
102
+ db.exec("ALTER TABLE messages RENAME TO messages_old");
103
+ db.exec(`
104
+ CREATE TABLE messages (
105
+ id TEXT PRIMARY KEY,
106
+ from_agent TEXT NOT NULL,
107
+ to_agent TEXT NOT NULL,
108
+ subject TEXT NOT NULL,
109
+ body TEXT NOT NULL,
110
+ type TEXT NOT NULL DEFAULT 'status' CHECK(type IN (${validTypes})),
111
+ priority TEXT NOT NULL DEFAULT 'normal' CHECK(priority IN ('low','normal','high','urgent')),
112
+ thread_id TEXT,
113
+ payload TEXT,
114
+ read INTEGER NOT NULL DEFAULT 0,
115
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
116
+ )`);
117
+ // Copy data, mapping invalid types to 'status'. Old tables may not have payload column.
118
+ const oldHasPayload = row.sql.includes("payload");
119
+ const payloadSelect = oldHasPayload ? "payload" : "NULL";
120
+ db.exec(`
121
+ INSERT INTO messages (id, from_agent, to_agent, subject, body, type, priority, thread_id, payload, read, created_at)
122
+ SELECT id, from_agent, to_agent, subject, body,
123
+ CASE WHEN type IN (${validTypes}) THEN type ELSE 'status' END,
124
+ CASE WHEN priority IN ('low','normal','high','urgent') THEN priority ELSE 'normal' END,
125
+ thread_id, ${payloadSelect}, read, created_at
126
+ FROM messages_old`);
127
+ db.exec("DROP TABLE messages_old");
128
+ db.exec("COMMIT");
129
+ } catch (err) {
130
+ db.exec("ROLLBACK");
131
+ throw err;
132
+ }
133
+ }
134
+
135
+ const CREATE_INDEXES = `
136
+ CREATE INDEX IF NOT EXISTS idx_inbox ON messages(to_agent, read);
137
+ CREATE INDEX IF NOT EXISTS idx_thread ON messages(thread_id)`;
138
+
139
+ /** Generate a random 12-character alphanumeric ID. */
140
+ function randomId(): string {
141
+ const chars = "abcdefghijklmnopqrstuvwxyz0123456789";
142
+ const bytes = new Uint8Array(12);
143
+ crypto.getRandomValues(bytes);
144
+ let result = "";
145
+ for (let i = 0; i < 12; i++) {
146
+ const byte = bytes[i];
147
+ if (byte !== undefined) {
148
+ result += chars[byte % chars.length];
149
+ }
150
+ }
151
+ return result;
152
+ }
153
+
154
+ /** Convert a database row (snake_case) to a MailMessage object (camelCase). */
155
+ function rowToMessage(row: MessageRow): MailMessage {
156
+ return {
157
+ id: row.id,
158
+ from: row.from_agent,
159
+ to: row.to_agent,
160
+ subject: row.subject,
161
+ body: row.body,
162
+ type: row.type as MailMessage["type"],
163
+ priority: row.priority as MailMessage["priority"],
164
+ threadId: row.thread_id,
165
+ payload: row.payload,
166
+ read: row.read === 1,
167
+ createdAt: row.created_at,
168
+ };
169
+ }
170
+
171
+ /**
172
+ * Create a new MailStore backed by a SQLite database at the given path.
173
+ *
174
+ * Initializes the database with WAL mode and a 5-second busy timeout.
175
+ * Creates the messages table and indexes if they do not already exist.
176
+ */
177
+ export function createMailStore(dbPath: string): MailStore {
178
+ const db = new Database(dbPath);
179
+
180
+ // Configure for concurrent access from multiple agent processes.
181
+ // WAL mode allows concurrent readers with one writer.
182
+ // synchronous=NORMAL balances safety and performance in WAL mode.
183
+ // busy_timeout retries for up to 5 seconds on lock contention.
184
+ db.exec("PRAGMA journal_mode = WAL");
185
+ db.exec("PRAGMA synchronous = NORMAL");
186
+ db.exec("PRAGMA busy_timeout = 5000");
187
+
188
+ // Migrate existing tables to current schema (no-op if table is new or already migrated)
189
+ migrateSchema(db);
190
+
191
+ // Create schema (if table doesn't exist yet, creates with CHECK constraints)
192
+ db.exec(CREATE_TABLE);
193
+ db.exec(CREATE_INDEXES);
194
+
195
+ // Prepare statements for all queries
196
+ const insertStmt = db.prepare<
197
+ void,
198
+ {
199
+ $id: string;
200
+ $from_agent: string;
201
+ $to_agent: string;
202
+ $subject: string;
203
+ $body: string;
204
+ $type: string;
205
+ $priority: string;
206
+ $thread_id: string | null;
207
+ $payload: string | null;
208
+ $read: number;
209
+ $created_at: string;
210
+ }
211
+ >(`
212
+ INSERT INTO messages
213
+ (id, from_agent, to_agent, subject, body, type, priority, thread_id, payload, read, created_at)
214
+ VALUES
215
+ ($id, $from_agent, $to_agent, $subject, $body, $type, $priority, $thread_id, $payload, $read, $created_at)
216
+ `);
217
+
218
+ const getByIdStmt = db.prepare<MessageRow, { $id: string }>(`
219
+ SELECT * FROM messages WHERE id = $id
220
+ `);
221
+
222
+ const getUnreadStmt = db.prepare<MessageRow, { $to_agent: string }>(`
223
+ SELECT * FROM messages WHERE to_agent = $to_agent AND read = 0 ORDER BY created_at ASC
224
+ `);
225
+
226
+ const getByThreadStmt = db.prepare<MessageRow, { $thread_id: string }>(`
227
+ SELECT * FROM messages WHERE thread_id = $thread_id ORDER BY created_at ASC
228
+ `);
229
+
230
+ const markReadStmt = db.prepare<void, { $id: string }>(`
231
+ UPDATE messages SET read = 1 WHERE id = $id
232
+ `);
233
+
234
+ // Dynamic filter queries are built at call time since the WHERE clause varies
235
+ function buildFilterQuery(filters?: {
236
+ from?: string;
237
+ to?: string;
238
+ unread?: boolean;
239
+ limit?: number;
240
+ }): MailMessage[] {
241
+ const conditions: string[] = [];
242
+ const params: Record<string, string | number> = {};
243
+
244
+ if (filters?.from !== undefined) {
245
+ conditions.push("from_agent = $from_agent");
246
+ params.$from_agent = filters.from;
247
+ }
248
+ if (filters?.to !== undefined) {
249
+ conditions.push("to_agent = $to_agent");
250
+ params.$to_agent = filters.to;
251
+ }
252
+ if (filters?.unread !== undefined) {
253
+ conditions.push("read = $read");
254
+ params.$read = filters.unread ? 0 : 1;
255
+ }
256
+
257
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
258
+ const limitClause = filters?.limit !== undefined ? ` LIMIT $limit` : "";
259
+ if (filters?.limit !== undefined) {
260
+ params.$limit = filters.limit;
261
+ }
262
+ const query = `SELECT * FROM messages ${whereClause} ORDER BY created_at DESC${limitClause}`;
263
+ const stmt = db.prepare<MessageRow, Record<string, string | number>>(query);
264
+ const rows = stmt.all(params);
265
+ return rows.map(rowToMessage);
266
+ }
267
+
268
+ return {
269
+ insert(
270
+ message: Omit<MailMessage, "read" | "createdAt" | "payload"> & {
271
+ payload?: string | null;
272
+ },
273
+ ): MailMessage {
274
+ const id = message.id || `msg-${randomId()}`;
275
+ const createdAt = new Date().toISOString();
276
+ const payload = message.payload ?? null;
277
+
278
+ try {
279
+ insertStmt.run({
280
+ $id: id,
281
+ $from_agent: message.from,
282
+ $to_agent: message.to,
283
+ $subject: message.subject,
284
+ $body: message.body,
285
+ $type: message.type,
286
+ $priority: message.priority,
287
+ $thread_id: message.threadId,
288
+ $payload: payload,
289
+ $read: 0,
290
+ $created_at: createdAt,
291
+ });
292
+ } catch (err) {
293
+ throw new MailError(`Failed to insert message: ${id}`, {
294
+ messageId: id,
295
+ cause: err instanceof Error ? err : undefined,
296
+ });
297
+ }
298
+
299
+ return {
300
+ ...message,
301
+ id,
302
+ payload,
303
+ read: false,
304
+ createdAt,
305
+ };
306
+ },
307
+
308
+ getUnread(agentName: string): MailMessage[] {
309
+ const rows = getUnreadStmt.all({ $to_agent: agentName });
310
+ return rows.map(rowToMessage);
311
+ },
312
+
313
+ getAll(filters?: {
314
+ from?: string;
315
+ to?: string;
316
+ unread?: boolean;
317
+ limit?: number;
318
+ }): MailMessage[] {
319
+ return buildFilterQuery(filters);
320
+ },
321
+
322
+ getById(id: string): MailMessage | null {
323
+ const row = getByIdStmt.get({ $id: id });
324
+ return row ? rowToMessage(row) : null;
325
+ },
326
+
327
+ getByThread(threadId: string): MailMessage[] {
328
+ const rows = getByThreadStmt.all({ $thread_id: threadId });
329
+ return rows.map(rowToMessage);
330
+ },
331
+
332
+ markRead(id: string): void {
333
+ markReadStmt.run({ $id: id });
334
+ },
335
+
336
+ purge(options: { all?: boolean; olderThanMs?: number; agent?: string }): number {
337
+ // Count matching rows before deletion so we can report accurate numbers
338
+ if (options.all) {
339
+ const countRow = db
340
+ .prepare<{ cnt: number }, []>("SELECT COUNT(*) as cnt FROM messages")
341
+ .get();
342
+ const count = countRow?.cnt ?? 0;
343
+ db.prepare("DELETE FROM messages").run();
344
+ return count;
345
+ }
346
+
347
+ const conditions: string[] = [];
348
+ const params: Record<string, string> = {};
349
+
350
+ if (options.olderThanMs !== undefined) {
351
+ const cutoff = new Date(Date.now() - options.olderThanMs).toISOString();
352
+ conditions.push("created_at < $cutoff");
353
+ params.$cutoff = cutoff;
354
+ }
355
+
356
+ if (options.agent !== undefined) {
357
+ conditions.push("(from_agent = $agent OR to_agent = $agent)");
358
+ params.$agent = options.agent;
359
+ }
360
+
361
+ if (conditions.length === 0) {
362
+ return 0;
363
+ }
364
+
365
+ const whereClause = conditions.join(" AND ");
366
+ const countQuery = `SELECT COUNT(*) as cnt FROM messages WHERE ${whereClause}`;
367
+ const countRow = db.prepare<{ cnt: number }, Record<string, string>>(countQuery).get(params);
368
+ const count = countRow?.cnt ?? 0;
369
+
370
+ const deleteQuery = `DELETE FROM messages WHERE ${whereClause}`;
371
+ db.prepare<void, Record<string, string>>(deleteQuery).run(params);
372
+
373
+ return count;
374
+ },
375
+
376
+ close(): void {
377
+ // Checkpoint WAL to ensure all written data is visible to other processes
378
+ // that may open the database after this connection closes.
379
+ try {
380
+ db.exec("PRAGMA wal_checkpoint(PASSIVE)");
381
+ } catch {
382
+ // Best effort — checkpoint failure is non-fatal
383
+ }
384
+ db.close();
385
+ },
386
+ };
387
+ }