crewboss 0.0.0-stage → 0.3.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.
package/src/session.js ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Identity of a Claude Code session. Every session has CLAUDE_CODE_MESSAGING_SOCKET in its
3
+ * environment (inherited by its hooks and Bash commands), and `uds:<that path>` is the address
4
+ * `SendMessage` accepts to write to it. crewboss uses that address as the main session's name in
5
+ * `presence` and the default `agent --notify`, so nothing needs to be configured.
6
+ */
7
+ import { NOTIFY_ENV, RUN_ID_ENV } from './events.js';
8
+
9
+ export const MESSAGING_SOCKET_ENV = 'CLAUDE_CODE_MESSAGING_SOCKET';
10
+ export const MESSAGING_TOKEN_ENV = 'CLAUDE_CODE_MESSAGING_TOKEN';
11
+ export const UDS_PREFIX = 'uds:';
12
+
13
+ /** The address `SendMessage` accepts for the session that owns `env` (`uds:<socket path>`), or null. */
14
+ export function sessionFromEnv(env = process.env) {
15
+ const socket = typeof env?.[MESSAGING_SOCKET_ENV] === 'string' ? env[MESSAGING_SOCKET_ENV].trim() : '';
16
+ return socket ? `${UDS_PREFIX}${socket}` : null;
17
+ }
18
+
19
+ /**
20
+ * Which session `crewboss agent` reports to: `--notify`, else $CREWBOSS_NOTIFY, else the session whose
21
+ * socket is in the environment. Inside a crewboss agent ($CREWBOSS_RUN_ID) the socket is never used:
22
+ * it is not the launcher's. Returns {notify, source} (`source` names where it came from), or nulls.
23
+ */
24
+ export function resolveNotify(flag, env = process.env) {
25
+ if (flag) return { notify: flag, source: '--notify' };
26
+ if (env[NOTIFY_ENV]) return { notify: env[NOTIFY_ENV], source: NOTIFY_ENV };
27
+ if (!env[RUN_ID_ENV]) {
28
+ const session = sessionFromEnv(env);
29
+ if (session) return { notify: session, source: MESSAGING_SOCKET_ENV };
30
+ }
31
+ return { notify: null, source: null };
32
+ }
33
+
34
+ /** `env` without the session's messaging credentials: an agent's own Claude session creates its own. */
35
+ export function withoutSessionCredentials(env) {
36
+ const clean = { ...env };
37
+ delete clean[MESSAGING_SOCKET_ENV];
38
+ delete clean[MESSAGING_TOKEN_ENV];
39
+ return clean;
40
+ }
package/src/store.js ADDED
@@ -0,0 +1,615 @@
1
+ /**
2
+ * Local store in SQLite (node:sqlite): tasks of the `local` tracker and the history
3
+ * of runs and reports, in <root>/.crewboss/crewboss.db.
4
+ *
5
+ * Schema changes are append-only migrations: `meta.schema_version` records the last
6
+ * one applied, each pending migration runs in its own transaction, and a database
7
+ * newer than this code is refused.
8
+ */
9
+ import { randomUUID } from 'node:crypto';
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { DatabaseSync } from 'node:sqlite';
13
+
14
+ import { StoreError } from './errors.js';
15
+ import { isDue } from './due.js';
16
+ import { processAlive } from './lock.js';
17
+ import { isoNow } from './rundir.js';
18
+ import { filterDoneSince } from './task-time.js';
19
+
20
+ export const STORE_DIR = '.crewboss';
21
+ export const STORE_FILE = 'crewboss.db';
22
+
23
+ /** Ordered schema migrations. Only ever append; never edit a released one. */
24
+ export const MIGRATIONS = [
25
+ {
26
+ version: 1,
27
+ sql: `
28
+ CREATE TABLE tasks (
29
+ id TEXT PRIMARY KEY,
30
+ project TEXT NOT NULL,
31
+ title TEXT NOT NULL,
32
+ notes TEXT NOT NULL DEFAULT '',
33
+ status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'in_progress', 'done')),
34
+ priority TEXT NOT NULL DEFAULT 'medium' CHECK (priority IN ('high', 'medium', 'low')),
35
+ assignee TEXT NOT NULL DEFAULT '',
36
+ created_at TEXT NOT NULL,
37
+ updated_at TEXT NOT NULL
38
+ );
39
+ CREATE INDEX tasks_project_status ON tasks (project, status);
40
+
41
+ CREATE TABLE runs (
42
+ id INTEGER PRIMARY KEY,
43
+ kind TEXT NOT NULL CHECK (kind IN ('agent', 'routine')),
44
+ name TEXT NOT NULL,
45
+ tool TEXT,
46
+ model TEXT,
47
+ status TEXT NOT NULL DEFAULT 'running' CHECK (status IN ('running', 'ok', 'issues', 'error', 'skipped')),
48
+ exit_code INTEGER,
49
+ dry_run INTEGER NOT NULL DEFAULT 0,
50
+ started_at TEXT NOT NULL,
51
+ ended_at TEXT,
52
+ duration_ms INTEGER,
53
+ log_dir TEXT,
54
+ summary TEXT NOT NULL DEFAULT ''
55
+ );
56
+ CREATE INDEX runs_kind_name_started ON runs (kind, name, started_at);
57
+
58
+ CREATE TABLE reports (
59
+ id INTEGER PRIMARY KEY,
60
+ run_id INTEGER REFERENCES runs (id) ON DELETE SET NULL,
61
+ project TEXT NOT NULL,
62
+ source TEXT NOT NULL,
63
+ title TEXT NOT NULL,
64
+ status TEXT NOT NULL CHECK (status IN ('ok', 'issues', 'error', 'skipped')),
65
+ summary TEXT NOT NULL,
66
+ body TEXT NOT NULL,
67
+ created_at TEXT NOT NULL
68
+ );
69
+ CREATE INDEX reports_source_created ON reports (source, created_at);
70
+
71
+ CREATE TABLE findings (
72
+ id INTEGER PRIMARY KEY,
73
+ report_id INTEGER NOT NULL REFERENCES reports (id) ON DELETE CASCADE,
74
+ position INTEGER NOT NULL,
75
+ severity TEXT NOT NULL CHECK (severity IN ('high', 'medium', 'low')),
76
+ title TEXT NOT NULL,
77
+ evidence TEXT NOT NULL,
78
+ proposal TEXT NOT NULL,
79
+ task_id TEXT
80
+ );
81
+ CREATE INDEX findings_report ON findings (report_id);
82
+ `,
83
+ },
84
+ {
85
+ version: 2,
86
+ sql: `
87
+ CREATE TABLE task_comments (
88
+ id INTEGER PRIMARY KEY,
89
+ task_id TEXT NOT NULL REFERENCES tasks (id) ON DELETE CASCADE,
90
+ author TEXT NOT NULL DEFAULT '',
91
+ body TEXT NOT NULL,
92
+ created_at TEXT NOT NULL
93
+ );
94
+ CREATE INDEX task_comments_task ON task_comments (task_id, id);
95
+
96
+ ALTER TABLE runs ADD COLUMN pid INTEGER;
97
+ `,
98
+ },
99
+ {
100
+ // The full-text index (memory_fts) is not part of the migration: it needs FTS5,
101
+ // which some supported Node versions lack. ensureMemoryIndex() manages it.
102
+ version: 3,
103
+ sql: `
104
+ CREATE TABLE memory (
105
+ id INTEGER PRIMARY KEY,
106
+ scope TEXT NOT NULL,
107
+ text TEXT NOT NULL,
108
+ author TEXT NOT NULL DEFAULT '',
109
+ created_at TEXT NOT NULL,
110
+ updated_at TEXT NOT NULL
111
+ );
112
+ CREATE INDEX memory_scope_created ON memory (scope, created_at);
113
+ `,
114
+ },
115
+ {
116
+ // The working directory of agent runs, exposed as a repository name by the API.
117
+ version: 4,
118
+ sql: 'ALTER TABLE runs ADD COLUMN work_dir TEXT;',
119
+ },
120
+ {
121
+ // The channel between a run's agent and whoever launched it. `out` goes agent -> launcher,
122
+ // `in` goes launcher -> agent (read_at is set when the agent reads it with `crewboss inbox`).
123
+ version: 5,
124
+ sql: `
125
+ CREATE TABLE run_events (
126
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
127
+ run_id INTEGER NOT NULL REFERENCES runs (id) ON DELETE CASCADE,
128
+ at TEXT NOT NULL,
129
+ direction TEXT NOT NULL CHECK (direction IN ('out', 'in')),
130
+ kind TEXT NOT NULL CHECK (kind IN ('started', 'finished', 'blocked', 'question', 'note', 'reply')),
131
+ message TEXT NOT NULL,
132
+ read_at TEXT
133
+ );
134
+ CREATE INDEX run_events_run ON run_events (run_id, id);
135
+ `,
136
+ },
137
+ {
138
+ // Presence of main sessions, kept by `crewboss presence`
139
+ // from Claude Code hooks, and the session each run was launched with --notify (runs.notify).
140
+ version: 6,
141
+ sql: `
142
+ CREATE TABLE presence (
143
+ session TEXT PRIMARY KEY,
144
+ state TEXT NOT NULL CHECK (state IN ('busy', 'idle')),
145
+ cwd TEXT NOT NULL DEFAULT '',
146
+ updated_at TEXT NOT NULL,
147
+ started_at TEXT NOT NULL
148
+ );
149
+
150
+ ALTER TABLE runs ADD COLUMN notify TEXT;
151
+ `,
152
+ },
153
+ {
154
+ // Display name of a presence (the session itself can be a socket address such as uds:/tmp/cc-socks/1.sock).
155
+ version: 7,
156
+ sql: `
157
+ ALTER TABLE presence ADD COLUMN label TEXT NOT NULL DEFAULT '';
158
+ `,
159
+ },
160
+ {
161
+ version: 8,
162
+ sql: 'ALTER TABLE tasks ADD COLUMN due TEXT;',
163
+ },
164
+ {
165
+ version: 9,
166
+ sql: `
167
+ ALTER TABLE tasks ADD COLUMN done_at TEXT;
168
+ UPDATE tasks SET done_at = NULLIF(updated_at, '') WHERE status = 'done';
169
+ UPDATE tasks SET updated_at = COALESCE(NULLIF(updated_at, ''), NULLIF(created_at, ''), strftime('%Y-%m-%dT%H:%M:%S+00:00', 'now'));
170
+ `,
171
+ },
172
+ ];
173
+
174
+ export const PRESENCE_STATES = ['busy', 'idle'];
175
+
176
+ export const EVENT_DIRECTIONS = ['out', 'in'];
177
+ export const EVENT_KINDS = ['started', 'finished', 'blocked', 'question', 'note', 'reply'];
178
+ /** Kinds an agent can send with `crewboss notify` (started and finished are crewboss's own). */
179
+ export const NOTIFY_KINDS = ['blocked', 'question', 'note'];
180
+
181
+ const MEMORY_TRIGGERS = {
182
+ memory_ai: `CREATE TRIGGER IF NOT EXISTS memory_ai AFTER INSERT ON memory BEGIN
183
+ INSERT INTO memory_fts (rowid, text) VALUES (new.id, new.text); END`,
184
+ memory_ad: `CREATE TRIGGER IF NOT EXISTS memory_ad AFTER DELETE ON memory BEGIN
185
+ INSERT INTO memory_fts (memory_fts, rowid, text) VALUES ('delete', old.id, old.text); END`,
186
+ memory_au: `CREATE TRIGGER IF NOT EXISTS memory_au AFTER UPDATE ON memory BEGIN
187
+ INSERT INTO memory_fts (memory_fts, rowid, text) VALUES ('delete', old.id, old.text);
188
+ INSERT INTO memory_fts (rowid, text) VALUES (new.id, new.text); END`,
189
+ };
190
+
191
+ /** True if this SQLite build has the FTS5 module (Node 22.13 does not). */
192
+ export function hasFts5(db) {
193
+ try {
194
+ db.exec('CREATE VIRTUAL TABLE temp.crewboss_fts5_probe USING fts5(x); DROP TABLE temp.crewboss_fts5_probe;');
195
+ return true;
196
+ } catch {
197
+ return false;
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Keep the FTS5 index of memory in step with this SQLite build. With FTS5, create
203
+ * memory_fts and its triggers if missing and rebuild it from memory. Without FTS5,
204
+ * drop the triggers (they would make every write fail) and leave search to LIKE.
205
+ * Returns whether full-text search is available.
206
+ */
207
+ export function ensureMemoryIndex(db, available = hasFts5(db)) {
208
+ const names = Object.keys(MEMORY_TRIGGERS);
209
+ const existing = new Set(db.prepare(`SELECT name FROM sqlite_master WHERE name IN (${['memory_fts', ...names].map(() => '?').join(', ')})`)
210
+ .all('memory_fts', ...names).map((row) => row.name));
211
+ if (!available) {
212
+ for (const name of names) if (existing.has(name)) db.exec(`DROP TRIGGER IF EXISTS ${name}`);
213
+ return false;
214
+ }
215
+ if (existing.has('memory_fts') && names.every((name) => existing.has(name))) return true;
216
+ inTransaction(db, () => {
217
+ db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5 (text, content = 'memory', content_rowid = 'id')");
218
+ for (const sql of Object.values(MEMORY_TRIGGERS)) db.exec(sql);
219
+ db.exec("INSERT INTO memory_fts (memory_fts) VALUES ('rebuild')");
220
+ });
221
+ return true;
222
+ }
223
+
224
+ const NOTE_COLUMNS = 'memory.id, memory.scope, memory.text, memory.author, memory.created_at, memory.updated_at';
225
+
226
+ export const TASK_STATUSES = ['open', 'in_progress', 'done'];
227
+ export const TASK_PRIORITIES = ['high', 'medium', 'low'];
228
+ const TASK_FIELDS = ['title', 'notes', 'status', 'priority', 'assignee', 'due'];
229
+ export const ORPHAN_SUMMARY = 'process gone';
230
+
231
+ function readVersion(db) {
232
+ const row = db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get();
233
+ return row ? Number(row.value) : 0;
234
+ }
235
+
236
+ /** Run fn inside BEGIN IMMEDIATE ... COMMIT, rolling back on error. */
237
+ export function inTransaction(db, fn) {
238
+ db.exec('BEGIN IMMEDIATE');
239
+ try {
240
+ const result = fn();
241
+ db.exec('COMMIT');
242
+ return result;
243
+ } catch (err) {
244
+ db.exec('ROLLBACK');
245
+ throw err;
246
+ }
247
+ }
248
+
249
+ /**
250
+ * Bring the schema up to the last migration. Each pending migration and its version
251
+ * bump share one transaction; the version is re-read inside it so that concurrent
252
+ * processes never apply a migration twice. Returns the resulting version.
253
+ */
254
+ export function migrate(db, migrations = MIGRATIONS) {
255
+ db.exec('CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)');
256
+ const latest = migrations.length ? migrations.at(-1).version : 0;
257
+ const current = readVersion(db);
258
+ if (current > latest) {
259
+ throw new StoreError(`database schema version ${current} is newer than this crewboss supports (${latest}); upgrade crewboss`);
260
+ }
261
+ for (const migration of migrations) {
262
+ if (migration.version <= current) continue;
263
+ try {
264
+ inTransaction(db, () => {
265
+ if (readVersion(db) >= migration.version) return;
266
+ db.exec(migration.sql);
267
+ db.prepare("INSERT INTO meta (key, value) VALUES ('schema_version', ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value")
268
+ .run(String(migration.version));
269
+ });
270
+ } catch (err) {
271
+ throw new StoreError(`schema migration ${migration.version} failed: ${err.message}`);
272
+ }
273
+ }
274
+ return readVersion(db);
275
+ }
276
+
277
+ function scopeFilter(scopes) {
278
+ if (scopes === null) return ['', []];
279
+ if (!scopes.length) return ['0', []];
280
+ return [`memory.scope IN (${scopes.map(() => '?').join(', ')})`, scopes];
281
+ }
282
+
283
+ export function storePath(root) {
284
+ return path.join(root, STORE_DIR, STORE_FILE);
285
+ }
286
+
287
+ const OPEN_STATUSES = ['open', 'in_progress'];
288
+
289
+ export class Store {
290
+ /**
291
+ * Open (creating it if needed) and migrate the database at `file`, then mark as
292
+ * errors the runs left `running` by processes that no longer exist.
293
+ */
294
+ constructor(file, { migrations = MIGRATIONS, pid = process.pid, isAlive = processAlive, fts5 = undefined } = {}) {
295
+ this.pid = pid;
296
+ this.file = file;
297
+ fs.mkdirSync(path.dirname(file), { recursive: true });
298
+ try {
299
+ this.db = new DatabaseSync(file);
300
+ this.db.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;');
301
+ } catch (err) {
302
+ throw new StoreError(`cannot open ${file}: ${err.message}`);
303
+ }
304
+ this.closed = false;
305
+ try {
306
+ this.version = migrate(this.db, migrations);
307
+ if (this.version >= 2) this.reapOrphanRuns(isAlive);
308
+ this.fts = this.version >= 3 ? ensureMemoryIndex(this.db, fts5 ?? hasFts5(this.db)) : false;
309
+ } catch (err) {
310
+ this.close();
311
+ throw err;
312
+ }
313
+ this.runStarts = new Map();
314
+ }
315
+
316
+ /** Runs still `running` whose process is gone become errors. Returns how many. */
317
+ reapOrphanRuns(isAlive = processAlive) {
318
+ const orphans = this.db.prepare("SELECT id, pid FROM runs WHERE status = 'running' AND pid IS NOT NULL").all()
319
+ .filter((row) => !isAlive(Number(row.pid)));
320
+ const mark = this.db.prepare("UPDATE runs SET status = 'error', summary = ?, ended_at = ? WHERE id = ? AND status = 'running'");
321
+ for (const row of orphans) mark.run(ORPHAN_SUMMARY, isoNow(), row.id);
322
+ return orphans.length;
323
+ }
324
+
325
+ close() {
326
+ if (this.closed) return;
327
+ this.db.close();
328
+ this.closed = true;
329
+ }
330
+
331
+ // Tasks of the local tracker.
332
+
333
+ createTask({ project, title, notes = '', priority = 'medium', assignee = '', due = null }) {
334
+ if (!isDue(due)) throw new StoreError('invalid due date; expected YYYY-MM-DD or null');
335
+ const now = isoNow();
336
+ const withDue = this.version >= 8;
337
+ const insert = this.db.prepare(`INSERT INTO tasks (id, project, title, notes, priority, assignee${withDue ? ', due' : ''}, created_at, updated_at)
338
+ VALUES (?, ?, ?, ?, ?, ?${withDue ? ', ?' : ''}, ?, ?)`);
339
+ for (;;) {
340
+ const id = randomUUID().replaceAll('-', '').slice(0, 8);
341
+ try {
342
+ insert.run(id, project, title, notes, priority, assignee, ...(withDue ? [due] : []), now, now);
343
+ return id;
344
+ } catch (err) {
345
+ if (!/UNIQUE constraint failed: tasks\.id/.test(err.message)) throw new StoreError(`cannot create task: ${err.message}`);
346
+ }
347
+ }
348
+ }
349
+
350
+ /** Open tasks (status open or in_progress) of a project, oldest first. */
351
+ openTasks(project) {
352
+ return this.db.prepare(`SELECT id, title, assignee FROM tasks WHERE project = ? AND status IN (${OPEN_STATUSES.map(() => '?').join(', ')})
353
+ ORDER BY created_at, rowid`).all(project, ...OPEN_STATUSES).map((row) => ({ ...row }));
354
+ }
355
+
356
+ getTask(id) {
357
+ const row = this.db.prepare('SELECT * FROM tasks WHERE id = ?').get(id);
358
+ return row ? { ...row } : null;
359
+ }
360
+
361
+ setTaskStatus(id, status) {
362
+ this.updateTask(id, { status });
363
+ }
364
+
365
+ /**
366
+ * Tasks filtered by project, assignee and ids. `status` is one of the task statuses,
367
+ * 'all', or null for every task that is not done. Oldest first.
368
+ */
369
+ listTasks({ project = null, status = null, assignee = null, ids = null, doneSince = null } = {}) {
370
+ const where = [];
371
+ const params = [];
372
+ if (project !== null) { where.push('project = ?'); params.push(project); }
373
+ if (assignee !== null) { where.push('assignee = ?'); params.push(assignee); }
374
+ if (status === null && doneSince === null) where.push("status <> 'done'");
375
+ else if (status !== null && status !== 'all') { where.push('status = ?'); params.push(status); }
376
+ if (ids !== null) {
377
+ if (!ids.length) return [];
378
+ where.push(`id IN (${ids.map(() => '?').join(', ')})`);
379
+ params.push(...ids);
380
+ }
381
+ const sql = `SELECT * FROM tasks ${where.length ? `WHERE ${where.join(' AND ')}` : ''} ORDER BY created_at, rowid`;
382
+ const rows = this.db.prepare(sql).all(...params).map((row) => ({ ...row }));
383
+ return doneSince === null ? rows : filterDoneSince(rows, doneSince);
384
+ }
385
+
386
+ /** Change some task fields. Returns the task, or null if missing. */
387
+ updateTask(id, changes) {
388
+ if (changes.due !== undefined && !isDue(changes.due)) throw new StoreError('invalid due date; expected YYYY-MM-DD or null');
389
+ const fields = TASK_FIELDS.filter((field) => changes[field] !== undefined);
390
+ if (fields.length) {
391
+ const old = this.getTask(id);
392
+ if (!old) return null;
393
+ const now = isoNow();
394
+ const doneAt = changes.status === 'done' && old.status !== 'done' ? now
395
+ : changes.status !== undefined && changes.status !== 'done' ? null : old.done_at;
396
+ this.db.prepare(`UPDATE tasks SET ${fields.map((f) => `${f} = ?`).join(', ')}, updated_at = ?, done_at = ? WHERE id = ?`)
397
+ .run(...fields.map((f) => changes[f]), now, doneAt, id);
398
+ }
399
+ return this.getTask(id);
400
+ }
401
+
402
+ /** Add a comment to a task. Returns the comment, or null if the task does not exist. */
403
+ addComment(taskId, { author = '', body }) {
404
+ if (!this.getTask(taskId)) return null;
405
+ const createdAt = isoNow();
406
+ const { lastInsertRowid } = this.db.prepare('INSERT INTO task_comments (task_id, author, body, created_at) VALUES (?, ?, ?, ?)')
407
+ .run(taskId, author, body, createdAt);
408
+ this.db.prepare('UPDATE tasks SET updated_at = ? WHERE id = ?').run(createdAt, taskId);
409
+ return { id: Number(lastInsertRowid), task_id: taskId, author, body, created_at: createdAt };
410
+ }
411
+
412
+ comments(taskId) {
413
+ return this.db.prepare('SELECT * FROM task_comments WHERE task_id = ? ORDER BY id').all(taskId).map((row) => ({ ...row }));
414
+ }
415
+
416
+ // Memory notes.
417
+
418
+ addMemory({ scope, text, author = '' }) {
419
+ const now = isoNow();
420
+ const { lastInsertRowid } = this.db.prepare('INSERT INTO memory (scope, text, author, created_at, updated_at) VALUES (?, ?, ?, ?, ?)')
421
+ .run(scope, text, author, now, now);
422
+ return this.getMemory(Number(lastInsertRowid));
423
+ }
424
+
425
+ getMemory(id) {
426
+ const row = this.db.prepare(`SELECT ${NOTE_COLUMNS} FROM memory WHERE id = ?`).get(id);
427
+ return row ? { ...row } : null;
428
+ }
429
+
430
+ /** Notes of the given scopes (all if null), newest first. */
431
+ listMemory({ scopes = null, limit = 50 } = {}) {
432
+ const [where, params] = scopeFilter(scopes);
433
+ return this.db.prepare(`SELECT ${NOTE_COLUMNS} FROM memory ${where ? `WHERE ${where}` : ''} ORDER BY memory.id DESC LIMIT ?`)
434
+ .all(...params, limit).map((row) => ({ ...row }));
435
+ }
436
+
437
+ /**
438
+ * Notes containing every word of `query`: ranked by FTS5 when available, otherwise
439
+ * matched with LIKE (newest first).
440
+ */
441
+ searchMemory(query, { scopes = null, limit = 20 } = {}) {
442
+ const words = query.split(/\s+/).filter(Boolean);
443
+ if (!words.length) return [];
444
+ const [scopeWhere, scopeParams] = scopeFilter(scopes);
445
+ if (this.fts) {
446
+ const match = words.map((w) => `"${w.replaceAll('"', '""')}"`).join(' ');
447
+ return this.db.prepare(`SELECT ${NOTE_COLUMNS} FROM memory_fts JOIN memory ON memory.id = memory_fts.rowid
448
+ WHERE memory_fts MATCH ? ${scopeWhere ? `AND ${scopeWhere}` : ''} ORDER BY bm25(memory_fts), memory.id DESC LIMIT ?`)
449
+ .all(match, ...scopeParams, limit).map((row) => ({ ...row }));
450
+ }
451
+ const likes = words.map(() => "memory.text LIKE ? ESCAPE '\\'");
452
+ const patterns = words.map((w) => `%${w.replace(/[\\%_]/g, (c) => `\\${c}`)}%`);
453
+ return this.db.prepare(`SELECT ${NOTE_COLUMNS} FROM memory WHERE ${[...likes, scopeWhere].filter(Boolean).join(' AND ')}
454
+ ORDER BY memory.id DESC LIMIT ?`).all(...patterns, ...scopeParams, limit).map((row) => ({ ...row }));
455
+ }
456
+
457
+ /** Delete a note. Returns whether it existed. */
458
+ removeMemory(id) {
459
+ return this.db.prepare('DELETE FROM memory WHERE id = ?').run(id).changes > 0;
460
+ }
461
+
462
+ // History of runs and reports.
463
+
464
+ startRun({ kind, name, dryRun = false, logDir = null, workDir = null, notify = null, reserved = false }) {
465
+ // `notify` needs migration 6; a database opened with older migrations (tests) simply lacks it.
466
+ const withNotify = this.version >= 6;
467
+ const { lastInsertRowid } = this.db.prepare(`INSERT INTO runs (kind, name, dry_run, started_at, log_dir, pid, work_dir${withNotify ? ', notify' : ''})
468
+ VALUES (?, ?, ?, ?, ?, ?, ?${withNotify ? ', ?' : ''})`)
469
+ .run(kind, name, dryRun ? 1 : 0, isoNow(), logDir, reserved ? null : this.pid, workDir, ...(withNotify ? [notify] : []));
470
+ const id = Number(lastInsertRowid);
471
+ this.runStarts.set(id, Date.now());
472
+ return id;
473
+ }
474
+
475
+ /** Atomically attach this agent process to an MCP-reserved run. */
476
+ claimAgentRun(id, name, { dryRun = false, logDir = null, workDir = null, notify = null } = {}) {
477
+ const row = this.getRun(id);
478
+ if (!row || row.kind !== 'agent' || row.name !== name || row.status !== 'running' || row.pid !== null) {
479
+ throw new StoreError(`run ${id} is not an unclaimed agent run for ${name}`);
480
+ }
481
+ const withNotify = this.version >= 6;
482
+ const result = this.db.prepare(`UPDATE runs SET pid = ?, dry_run = ?, log_dir = ?, work_dir = ?${withNotify ? ', notify = ?' : ''}
483
+ WHERE id = ? AND kind = 'agent' AND name = ? AND status = 'running' AND pid IS NULL`)
484
+ .run(this.pid, dryRun ? 1 : 0, logDir, workDir, ...(withNotify ? [notify] : []), id, name);
485
+ if (result.changes !== 1) throw new StoreError(`run ${id} was already claimed`);
486
+ this.runStarts.set(id, Date.now());
487
+ return id;
488
+ }
489
+
490
+ finishRun(id, { status, tool = null, model = null, exitCode = null, summary = '', logDir = undefined }) {
491
+ const started = this.runStarts.get(id);
492
+ this.runStarts.delete(id);
493
+ const duration = started === undefined ? null : Date.now() - started;
494
+ this.db.prepare(`UPDATE runs SET status = ?, tool = ?, model = ?, exit_code = ?, summary = ?, ended_at = ?, duration_ms = ?,
495
+ log_dir = COALESCE(?, log_dir) WHERE id = ?`)
496
+ .run(status, tool, model, exitCode, summary, isoNow(), duration, logDir ?? null, id);
497
+ }
498
+
499
+ listRuns({ kind = null, name = null, limit = 50 } = {}) {
500
+ return this.db.prepare(`SELECT * FROM runs WHERE (? IS NULL OR kind = ?) AND (? IS NULL OR name = ?)
501
+ ORDER BY id DESC LIMIT ?`).all(kind, kind, name, name, limit).map((row) => ({ ...row }));
502
+ }
503
+
504
+ getRun(id) {
505
+ const row = this.db.prepare('SELECT * FROM runs WHERE id = ?').get(id);
506
+ return row ? { ...row } : null;
507
+ }
508
+
509
+ // Events between a run's agent and whoever launched it.
510
+
511
+ /** Add an event to a run. Returns it. Needs migration 5. */
512
+ addEvent(runId, { direction, kind, message }) {
513
+ if (!EVENT_DIRECTIONS.includes(direction)) throw new StoreError(`invalid event direction: ${direction}`);
514
+ if (!EVENT_KINDS.includes(kind)) throw new StoreError(`invalid event kind: ${kind}`);
515
+ const at = isoNow();
516
+ try {
517
+ const { lastInsertRowid } = this.db.prepare('INSERT INTO run_events (run_id, at, direction, kind, message) VALUES (?, ?, ?, ?, ?)')
518
+ .run(runId, at, direction, kind, message);
519
+ return { id: Number(lastInsertRowid), run_id: runId, at, direction, kind, message, read_at: null };
520
+ } catch (err) {
521
+ throw new StoreError(`cannot add event: ${err.message}`);
522
+ }
523
+ }
524
+
525
+ /**
526
+ * Events with id > `since`, oldest first, optionally of one run and/or one direction.
527
+ * With `limit`, the newest `limit` events (still oldest first).
528
+ */
529
+ listEvents({ since = 0, runId = null, direction = null, limit = null, notify = null } = {}) {
530
+ const where = ['id > ?'];
531
+ const params = [since];
532
+ if (runId !== null) { where.push('run_id = ?'); params.push(runId); }
533
+ if (direction !== null) { where.push('direction = ?'); params.push(direction); }
534
+ if (notify !== null) { where.push('run_id IN (SELECT id FROM runs WHERE notify = ?)'); params.push(notify); }
535
+ const sql = `SELECT * FROM run_events WHERE ${where.join(' AND ')}`;
536
+ if (limit === null) return this.db.prepare(`${sql} ORDER BY id`).all(...params).map((row) => ({ ...row }));
537
+ return this.db.prepare(`SELECT * FROM (${sql} ORDER BY id DESC LIMIT ?) ORDER BY id`).all(...params, limit).map((row) => ({ ...row }));
538
+ }
539
+
540
+ // Presence of the main sessions. Needs migrations 6 and 7 (label).
541
+
542
+ /**
543
+ * Record that `session` is `state` now. `startedAt` is kept while the session stays present;
544
+ * if the previous row had `expired` (a function of the row), it starts over.
545
+ */
546
+ setPresence(session, { state, cwd = '', label = '', expired = () => false }) {
547
+ if (!PRESENCE_STATES.includes(state)) throw new StoreError(`invalid presence state: ${state}`);
548
+ const now = isoNow();
549
+ inTransaction(this.db, () => {
550
+ const old = this.db.prepare('SELECT * FROM presence WHERE session = ?').get(session);
551
+ const keep = old && !expired({ ...old });
552
+ this.db.prepare(`INSERT INTO presence (session, state, cwd, label, updated_at, started_at) VALUES (?, ?, ?, ?, ?, ?)
553
+ ON CONFLICT (session) DO UPDATE SET state = excluded.state, cwd = excluded.cwd, label = excluded.label,
554
+ updated_at = excluded.updated_at, started_at = excluded.started_at`)
555
+ .run(session, state, cwd || (keep ? old.cwd : ''), label || (keep ? old.label : ''), now, keep ? old.started_at : now);
556
+ });
557
+ }
558
+
559
+ /** Forget a session. Returns whether it was there. */
560
+ removePresence(session) {
561
+ return this.db.prepare('DELETE FROM presence WHERE session = ?').run(session).changes > 0;
562
+ }
563
+
564
+ /** Every presence row, oldest start first (expired ones included: see livePresence). */
565
+ listPresence() {
566
+ return this.db.prepare('SELECT * FROM presence ORDER BY started_at, session').all().map((row) => ({ ...row }));
567
+ }
568
+
569
+ /** Id of the newest event (0 when there are none). */
570
+ lastEventId() {
571
+ return Number(this.db.prepare('SELECT COALESCE(MAX(id), 0) AS id FROM run_events').get().id);
572
+ }
573
+
574
+ /** Unread `in` events of a run, oldest first, marking them as read (atomically). */
575
+ takeInbox(runId) {
576
+ return inTransaction(this.db, () => {
577
+ const rows = this.db.prepare("SELECT * FROM run_events WHERE run_id = ? AND direction = 'in' AND read_at IS NULL ORDER BY id")
578
+ .all(runId).map((row) => ({ ...row }));
579
+ const readAt = isoNow();
580
+ const mark = this.db.prepare('UPDATE run_events SET read_at = ? WHERE id = ?');
581
+ for (const row of rows) mark.run(readAt, row.id);
582
+ return rows.map((row) => ({ ...row, read_at: readAt }));
583
+ });
584
+ }
585
+
586
+ /** Store a report and its findings (with their task ids) in one transaction. */
587
+ recordReport({ runId = null, project, source, title, status, summary, body, findings = [] }) {
588
+ return inTransaction(this.db, () => {
589
+ const { lastInsertRowid } = this.db.prepare(`INSERT INTO reports (run_id, project, source, title, status, summary, body, created_at)
590
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(runId, project, source, title, status, summary, body, isoNow());
591
+ const reportId = Number(lastInsertRowid);
592
+ const insert = this.db.prepare(`INSERT INTO findings (report_id, position, severity, title, evidence, proposal, task_id)
593
+ VALUES (?, ?, ?, ?, ?, ?, ?)`);
594
+ findings.forEach((f, i) => insert.run(reportId, i, f.severity, f.title, f.evidence, f.proposal, f.task ?? null));
595
+ return reportId;
596
+ });
597
+ }
598
+
599
+ listReports({ source = null, limit = 50 } = {}) {
600
+ return this.db.prepare('SELECT * FROM reports WHERE (? IS NULL OR source = ?) ORDER BY id DESC LIMIT ?')
601
+ .all(source, source, limit).map((row) => ({ ...row }));
602
+ }
603
+
604
+ getReport(id) {
605
+ const report = this.db.prepare('SELECT * FROM reports WHERE id = ?').get(id);
606
+ if (!report) return null;
607
+ const findings = this.db.prepare('SELECT * FROM findings WHERE report_id = ? ORDER BY position').all(id).map((row) => ({ ...row }));
608
+ return { ...report, findings };
609
+ }
610
+ }
611
+
612
+ /** Open the store of a workspace root: <root>/.crewboss/crewboss.db. */
613
+ export function openStore(root, options = {}) {
614
+ return new Store(storePath(root), options);
615
+ }
@@ -0,0 +1,6 @@
1
+ /** Scheduled entries managed alongside routines, without launching an agent. */
2
+ export function scheduledEntries(config) {
3
+ const entries = config.routines.filter((routine) => routine.enabled);
4
+ return config.tasks?.stale_after_days === undefined ? entries
5
+ : [...entries, { name: 'tidy', schedule: '*-*-* 07:00:00', tidy: true }];
6
+ }