@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.
- package/LICENSE +21 -0
- package/README.md +381 -0
- package/agents/builder.md +137 -0
- package/agents/coordinator.md +263 -0
- package/agents/lead.md +301 -0
- package/agents/merger.md +160 -0
- package/agents/monitor.md +214 -0
- package/agents/reviewer.md +140 -0
- package/agents/scout.md +119 -0
- package/agents/supervisor.md +423 -0
- package/package.json +47 -0
- package/src/agents/checkpoint.test.ts +88 -0
- package/src/agents/checkpoint.ts +101 -0
- package/src/agents/hooks-deployer.test.ts +2040 -0
- package/src/agents/hooks-deployer.ts +607 -0
- package/src/agents/identity.test.ts +603 -0
- package/src/agents/identity.ts +384 -0
- package/src/agents/lifecycle.test.ts +196 -0
- package/src/agents/lifecycle.ts +183 -0
- package/src/agents/manifest.test.ts +746 -0
- package/src/agents/manifest.ts +354 -0
- package/src/agents/overlay.test.ts +676 -0
- package/src/agents/overlay.ts +308 -0
- package/src/beads/client.test.ts +217 -0
- package/src/beads/client.ts +202 -0
- package/src/beads/molecules.test.ts +338 -0
- package/src/beads/molecules.ts +198 -0
- package/src/commands/agents.test.ts +322 -0
- package/src/commands/agents.ts +287 -0
- package/src/commands/clean.test.ts +670 -0
- package/src/commands/clean.ts +618 -0
- package/src/commands/completions.test.ts +342 -0
- package/src/commands/completions.ts +887 -0
- package/src/commands/coordinator.test.ts +1530 -0
- package/src/commands/coordinator.ts +733 -0
- package/src/commands/costs.test.ts +1119 -0
- package/src/commands/costs.ts +564 -0
- package/src/commands/dashboard.test.ts +308 -0
- package/src/commands/dashboard.ts +838 -0
- package/src/commands/doctor.test.ts +294 -0
- package/src/commands/doctor.ts +213 -0
- package/src/commands/errors.test.ts +647 -0
- package/src/commands/errors.ts +248 -0
- package/src/commands/feed.test.ts +578 -0
- package/src/commands/feed.ts +361 -0
- package/src/commands/group.test.ts +262 -0
- package/src/commands/group.ts +511 -0
- package/src/commands/hooks.test.ts +458 -0
- package/src/commands/hooks.ts +253 -0
- package/src/commands/init.test.ts +347 -0
- package/src/commands/init.ts +650 -0
- package/src/commands/inspect.test.ts +670 -0
- package/src/commands/inspect.ts +431 -0
- package/src/commands/log.test.ts +1454 -0
- package/src/commands/log.ts +724 -0
- package/src/commands/logs.test.ts +379 -0
- package/src/commands/logs.ts +546 -0
- package/src/commands/mail.test.ts +1270 -0
- package/src/commands/mail.ts +771 -0
- package/src/commands/merge.test.ts +670 -0
- package/src/commands/merge.ts +355 -0
- package/src/commands/metrics.test.ts +444 -0
- package/src/commands/metrics.ts +143 -0
- package/src/commands/monitor.test.ts +191 -0
- package/src/commands/monitor.ts +390 -0
- package/src/commands/nudge.test.ts +230 -0
- package/src/commands/nudge.ts +372 -0
- package/src/commands/prime.test.ts +470 -0
- package/src/commands/prime.ts +381 -0
- package/src/commands/replay.test.ts +741 -0
- package/src/commands/replay.ts +360 -0
- package/src/commands/run.test.ts +431 -0
- package/src/commands/run.ts +351 -0
- package/src/commands/sling.test.ts +657 -0
- package/src/commands/sling.ts +661 -0
- package/src/commands/spec.test.ts +203 -0
- package/src/commands/spec.ts +168 -0
- package/src/commands/status.test.ts +430 -0
- package/src/commands/status.ts +398 -0
- package/src/commands/stop.test.ts +420 -0
- package/src/commands/stop.ts +151 -0
- package/src/commands/supervisor.test.ts +187 -0
- package/src/commands/supervisor.ts +535 -0
- package/src/commands/trace.test.ts +745 -0
- package/src/commands/trace.ts +325 -0
- package/src/commands/watch.test.ts +145 -0
- package/src/commands/watch.ts +247 -0
- package/src/commands/worktree.test.ts +786 -0
- package/src/commands/worktree.ts +311 -0
- package/src/config.test.ts +822 -0
- package/src/config.ts +829 -0
- package/src/doctor/agents.test.ts +454 -0
- package/src/doctor/agents.ts +396 -0
- package/src/doctor/config-check.test.ts +190 -0
- package/src/doctor/config-check.ts +183 -0
- package/src/doctor/consistency.test.ts +651 -0
- package/src/doctor/consistency.ts +294 -0
- package/src/doctor/databases.test.ts +290 -0
- package/src/doctor/databases.ts +218 -0
- package/src/doctor/dependencies.test.ts +184 -0
- package/src/doctor/dependencies.ts +175 -0
- package/src/doctor/logs.test.ts +251 -0
- package/src/doctor/logs.ts +295 -0
- package/src/doctor/merge-queue.test.ts +216 -0
- package/src/doctor/merge-queue.ts +144 -0
- package/src/doctor/structure.test.ts +291 -0
- package/src/doctor/structure.ts +198 -0
- package/src/doctor/types.ts +37 -0
- package/src/doctor/version.test.ts +136 -0
- package/src/doctor/version.ts +129 -0
- package/src/e2e/init-sling-lifecycle.test.ts +277 -0
- package/src/errors.ts +217 -0
- package/src/events/store.test.ts +660 -0
- package/src/events/store.ts +369 -0
- package/src/events/tool-filter.test.ts +330 -0
- package/src/events/tool-filter.ts +126 -0
- package/src/index.ts +316 -0
- package/src/insights/analyzer.test.ts +466 -0
- package/src/insights/analyzer.ts +203 -0
- package/src/logging/color.test.ts +142 -0
- package/src/logging/color.ts +71 -0
- package/src/logging/logger.test.ts +813 -0
- package/src/logging/logger.ts +266 -0
- package/src/logging/reporter.test.ts +259 -0
- package/src/logging/reporter.ts +109 -0
- package/src/logging/sanitizer.test.ts +190 -0
- package/src/logging/sanitizer.ts +57 -0
- package/src/mail/broadcast.test.ts +203 -0
- package/src/mail/broadcast.ts +92 -0
- package/src/mail/client.test.ts +773 -0
- package/src/mail/client.ts +223 -0
- package/src/mail/store.test.ts +705 -0
- package/src/mail/store.ts +387 -0
- package/src/merge/queue.test.ts +359 -0
- package/src/merge/queue.ts +231 -0
- package/src/merge/resolver.test.ts +1345 -0
- package/src/merge/resolver.ts +645 -0
- package/src/metrics/store.test.ts +667 -0
- package/src/metrics/store.ts +445 -0
- package/src/metrics/summary.test.ts +398 -0
- package/src/metrics/summary.ts +178 -0
- package/src/metrics/transcript.test.ts +356 -0
- package/src/metrics/transcript.ts +175 -0
- package/src/mulch/client.test.ts +671 -0
- package/src/mulch/client.ts +332 -0
- package/src/sessions/compat.test.ts +280 -0
- package/src/sessions/compat.ts +104 -0
- package/src/sessions/store.test.ts +873 -0
- package/src/sessions/store.ts +494 -0
- package/src/test-helpers.test.ts +124 -0
- package/src/test-helpers.ts +126 -0
- package/src/tracker/beads.ts +56 -0
- package/src/tracker/factory.test.ts +80 -0
- package/src/tracker/factory.ts +64 -0
- package/src/tracker/seeds.ts +182 -0
- package/src/tracker/types.ts +52 -0
- package/src/types.ts +724 -0
- package/src/watchdog/daemon.test.ts +1975 -0
- package/src/watchdog/daemon.ts +671 -0
- package/src/watchdog/health.test.ts +431 -0
- package/src/watchdog/health.ts +264 -0
- package/src/watchdog/triage.test.ts +164 -0
- package/src/watchdog/triage.ts +179 -0
- package/src/worktree/manager.test.ts +439 -0
- package/src/worktree/manager.ts +198 -0
- package/src/worktree/tmux.test.ts +1009 -0
- package/src/worktree/tmux.ts +509 -0
- package/templates/CLAUDE.md.tmpl +89 -0
- package/templates/hooks.json.tmpl +105 -0
- 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
|
+
}
|