agent-working-memory 0.5.4 → 0.5.6

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 (71) hide show
  1. package/README.md +87 -46
  2. package/dist/api/routes.d.ts.map +1 -1
  3. package/dist/api/routes.js +21 -5
  4. package/dist/api/routes.js.map +1 -1
  5. package/dist/cli.js +67 -67
  6. package/dist/coordination/index.d.ts +11 -0
  7. package/dist/coordination/index.d.ts.map +1 -0
  8. package/dist/coordination/index.js +39 -0
  9. package/dist/coordination/index.js.map +1 -0
  10. package/dist/coordination/mcp-tools.d.ts +8 -0
  11. package/dist/coordination/mcp-tools.d.ts.map +1 -0
  12. package/dist/coordination/mcp-tools.js +216 -0
  13. package/dist/coordination/mcp-tools.js.map +1 -0
  14. package/dist/coordination/routes.d.ts +9 -0
  15. package/dist/coordination/routes.d.ts.map +1 -0
  16. package/dist/coordination/routes.js +434 -0
  17. package/dist/coordination/routes.js.map +1 -0
  18. package/dist/coordination/schema.d.ts +12 -0
  19. package/dist/coordination/schema.d.ts.map +1 -0
  20. package/dist/coordination/schema.js +91 -0
  21. package/dist/coordination/schema.js.map +1 -0
  22. package/dist/coordination/schemas.d.ts +208 -0
  23. package/dist/coordination/schemas.d.ts.map +1 -0
  24. package/dist/coordination/schemas.js +109 -0
  25. package/dist/coordination/schemas.js.map +1 -0
  26. package/dist/coordination/stale.d.ts +25 -0
  27. package/dist/coordination/stale.d.ts.map +1 -0
  28. package/dist/coordination/stale.js +53 -0
  29. package/dist/coordination/stale.js.map +1 -0
  30. package/dist/index.js +21 -3
  31. package/dist/index.js.map +1 -1
  32. package/dist/mcp.js +90 -79
  33. package/dist/mcp.js.map +1 -1
  34. package/dist/storage/sqlite.d.ts +3 -0
  35. package/dist/storage/sqlite.d.ts.map +1 -1
  36. package/dist/storage/sqlite.js +285 -281
  37. package/dist/storage/sqlite.js.map +1 -1
  38. package/package.json +55 -55
  39. package/src/api/index.ts +3 -3
  40. package/src/api/routes.ts +551 -536
  41. package/src/cli.ts +397 -397
  42. package/src/coordination/index.ts +47 -0
  43. package/src/coordination/mcp-tools.ts +313 -0
  44. package/src/coordination/routes.ts +656 -0
  45. package/src/coordination/schema.ts +94 -0
  46. package/src/coordination/schemas.ts +136 -0
  47. package/src/coordination/stale.ts +89 -0
  48. package/src/core/decay.ts +63 -63
  49. package/src/core/embeddings.ts +88 -88
  50. package/src/core/hebbian.ts +93 -93
  51. package/src/core/index.ts +5 -5
  52. package/src/core/logger.ts +36 -36
  53. package/src/core/query-expander.ts +66 -66
  54. package/src/core/reranker.ts +101 -101
  55. package/src/engine/activation.ts +656 -656
  56. package/src/engine/connections.ts +103 -103
  57. package/src/engine/consolidation-scheduler.ts +125 -125
  58. package/src/engine/eval.ts +102 -102
  59. package/src/engine/eviction.ts +101 -101
  60. package/src/engine/index.ts +8 -8
  61. package/src/engine/retraction.ts +100 -100
  62. package/src/engine/staging.ts +74 -74
  63. package/src/index.ts +137 -121
  64. package/src/mcp.ts +1024 -1013
  65. package/src/storage/index.ts +3 -3
  66. package/src/storage/sqlite.ts +968 -963
  67. package/src/types/agent.ts +67 -67
  68. package/src/types/checkpoint.ts +46 -46
  69. package/src/types/engram.ts +217 -217
  70. package/src/types/eval.ts +100 -100
  71. package/src/types/index.ts +6 -6
@@ -0,0 +1,656 @@
1
+ // Copyright 2026 Robert Winter / Complete Ideas
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ /**
4
+ * HTTP routes for the coordination module.
5
+ * Ported from AgentSynapse packages/coordinator/src/routes/*.ts into a single file.
6
+ * All tables use coord_ prefix to avoid collision with AWM core tables.
7
+ */
8
+
9
+ import type { FastifyInstance } from 'fastify';
10
+ import type Database from 'better-sqlite3';
11
+ import { randomUUID } from 'node:crypto';
12
+ import {
13
+ checkinSchema, checkoutSchema, pulseSchema,
14
+ assignCreateSchema, assignmentQuerySchema, assignmentClaimSchema, assignmentUpdateSchema, assignmentIdParamSchema,
15
+ lockAcquireSchema, lockReleaseSchema,
16
+ commandCreateSchema, commandWaitQuerySchema,
17
+ findingCreateSchema, findingsQuerySchema, findingIdParamSchema,
18
+ eventsQuerySchema, staleQuerySchema, workersQuerySchema,
19
+ } from './schemas.js';
20
+ import { detectStale, cleanupStale } from './stale.js';
21
+
22
+ /** Pretty timestamp for coordination logs. */
23
+ function ts(): string {
24
+ return new Date().toLocaleTimeString('en-GB', { hour12: false });
25
+ }
26
+
27
+ /** Log a coordination event in human-readable format. */
28
+ function coordLog(msg: string): void {
29
+ console.log(`${ts()} [coord] ${msg}`);
30
+ }
31
+
32
+ export function registerCoordinationRoutes(app: FastifyInstance, db: Database.Database): void {
33
+
34
+ // Log errors and non-200 responses
35
+ app.addHook('onResponse', async (request, reply) => {
36
+ if (reply.statusCode >= 400) {
37
+ coordLog(`${request.method} ${request.url} → ${reply.statusCode}`);
38
+ }
39
+ });
40
+
41
+ // ─── Checkin ────────────────────────────────────────────────────
42
+
43
+ app.post('/checkin', async (req, reply) => {
44
+ const parsed = checkinSchema.safeParse(req.body);
45
+ if (!parsed.success) return reply.code(400).send({ error: parsed.error.issues[0].message });
46
+ const { name, role, pid, metadata, capabilities, workspace } = parsed.data;
47
+ const capsJson = capabilities ? JSON.stringify(capabilities) : null;
48
+
49
+ const existing = workspace
50
+ ? db.prepare(
51
+ `SELECT id, status FROM coord_agents WHERE name = ? AND workspace = ? AND status != 'dead'`
52
+ ).get(name, workspace) as { id: string; status: string } | undefined
53
+ : db.prepare(
54
+ `SELECT id, status FROM coord_agents WHERE name = ? AND workspace IS NULL AND status != 'dead'`
55
+ ).get(name) as { id: string; status: string } | undefined;
56
+
57
+ if (existing) {
58
+ db.prepare(
59
+ `UPDATE coord_agents SET last_seen = datetime('now'), status = CASE WHEN status = 'dead' THEN 'idle' ELSE status END, pid = COALESCE(?, pid), capabilities = COALESCE(?, capabilities) WHERE id = ?`
60
+ ).run(pid ?? null, capsJson, existing.id);
61
+
62
+ db.prepare(
63
+ `INSERT INTO coord_events (agent_id, event_type, detail) VALUES (?, 'heartbeat', ?)`
64
+ ).run(existing.id, `heartbeat from ${name}`);
65
+
66
+ return reply.send({ agentId: existing.id, action: 'heartbeat', status: existing.status, workspace });
67
+ }
68
+
69
+ const id = randomUUID();
70
+ db.prepare(
71
+ `INSERT INTO coord_agents (id, name, role, pid, status, metadata, capabilities, workspace) VALUES (?, ?, ?, ?, 'idle', ?, ?, ?)`
72
+ ).run(id, name, role ?? 'worker', pid ?? null, metadata ? JSON.stringify(metadata) : null, capsJson, workspace ?? null);
73
+
74
+ db.prepare(
75
+ `INSERT INTO coord_events (agent_id, event_type, detail) VALUES (?, 'registered', ?)`
76
+ ).run(id, `${name} joined as ${role ?? 'worker'}${workspace ? ' [' + workspace + ']' : ''}${capabilities ? ' [' + capabilities.join(', ') + ']' : ''}`);
77
+
78
+ coordLog(`${name} registered (${role ?? 'worker'})${capabilities ? ' [' + capabilities.join(', ') + ']' : ''}`);
79
+ return reply.code(201).send({ agentId: id, action: 'registered', status: 'idle', workspace });
80
+ });
81
+
82
+ app.post('/checkout', async (req, reply) => {
83
+ const parsed = checkoutSchema.safeParse(req.body);
84
+ if (!parsed.success) return reply.code(400).send({ error: parsed.error.issues[0].message });
85
+ const { agentId } = parsed.data;
86
+
87
+ db.prepare(`DELETE FROM coord_locks WHERE agent_id = ?`).run(agentId);
88
+ db.prepare(
89
+ `UPDATE coord_agents SET status = 'dead', last_seen = datetime('now') WHERE id = ?`
90
+ ).run(agentId);
91
+ db.prepare(
92
+ `INSERT INTO coord_events (agent_id, event_type, detail) VALUES (?, 'checkout', 'agent signed off')`
93
+ ).run(agentId);
94
+
95
+ // Look up agent name for logging
96
+ const agent = db.prepare(`SELECT name FROM coord_agents WHERE id = ?`).get(agentId) as { name: string } | undefined;
97
+ coordLog(`${agent?.name ?? agentId} checked out`);
98
+ return reply.send({ ok: true });
99
+ });
100
+
101
+ // ─── Pulse (lightweight heartbeat — no event row) ──────────────
102
+
103
+ app.patch('/pulse', async (req, reply) => {
104
+ const parsed = pulseSchema.safeParse(req.body);
105
+ if (!parsed.success) return reply.code(400).send({ error: parsed.error.issues[0].message });
106
+ const { agentId } = parsed.data;
107
+
108
+ db.prepare(`UPDATE coord_agents SET last_seen = datetime('now') WHERE id = ?`).run(agentId);
109
+ return reply.send({ ok: true });
110
+ });
111
+
112
+ // ─── Assignments ────────────────────────────────────────────────
113
+
114
+ app.post('/assign', async (req, reply) => {
115
+ const parsed = assignCreateSchema.safeParse(req.body);
116
+ if (!parsed.success) return reply.code(400).send({ error: parsed.error.issues[0].message });
117
+ const { agentId, task, description, workspace } = parsed.data;
118
+
119
+ const id = randomUUID();
120
+ db.prepare(
121
+ `INSERT INTO coord_assignments (id, agent_id, task, description, status, workspace) VALUES (?, ?, ?, ?, ?, ?)`
122
+ ).run(id, agentId ?? null, task, description ?? null, agentId ? 'assigned' : 'pending', workspace ?? null);
123
+
124
+ if (agentId) {
125
+ db.prepare(
126
+ `UPDATE coord_agents SET status = 'working', current_task = ? WHERE id = ?`
127
+ ).run(id, agentId);
128
+ }
129
+
130
+ db.prepare(
131
+ `INSERT INTO coord_events (agent_id, event_type, detail) VALUES (?, 'assignment_created', ?)`
132
+ ).run(agentId ?? null, `task: ${task}`);
133
+
134
+ // Log assignment with agent name
135
+ if (agentId) {
136
+ const agent = db.prepare(`SELECT name FROM coord_agents WHERE id = ?`).get(agentId) as { name: string } | undefined;
137
+ coordLog(`assigned → ${agent?.name ?? 'unknown'}: ${task.slice(0, 80)}`);
138
+ } else {
139
+ coordLog(`assignment queued (pending): ${task.slice(0, 80)}`);
140
+ }
141
+ return reply.code(201).send({ assignmentId: id, status: agentId ? 'assigned' : 'pending' });
142
+ });
143
+
144
+ app.get('/assignment', async (req, reply) => {
145
+ const agentId = (req.headers['x-agent-id'] as string | undefined) ?? assignmentQuerySchema.parse(req.query).agentId;
146
+
147
+ if (!agentId) {
148
+ return reply.send({ assignment: null });
149
+ }
150
+
151
+ const active = db.prepare(
152
+ `SELECT * FROM coord_assignments WHERE agent_id = ? AND status IN ('assigned', 'in_progress') ORDER BY created_at DESC LIMIT 1`
153
+ ).get(agentId);
154
+
155
+ if (active) return reply.send({ assignment: active });
156
+
157
+ const agentRow = db.prepare(`SELECT workspace FROM coord_agents WHERE id = ?`).get(agentId) as { workspace: string | null } | undefined;
158
+ const agentWorkspace = agentRow?.workspace;
159
+
160
+ const pending = agentWorkspace
161
+ ? db.prepare(
162
+ `SELECT * FROM coord_assignments WHERE status = 'pending' AND (workspace = ? OR workspace IS NULL) ORDER BY created_at ASC LIMIT 1`
163
+ ).get(agentWorkspace) as { id: string } | undefined
164
+ : db.prepare(
165
+ `SELECT * FROM coord_assignments WHERE status = 'pending' ORDER BY created_at ASC LIMIT 1`
166
+ ).get() as { id: string } | undefined;
167
+
168
+ if (pending) {
169
+ const claimed = db.prepare(
170
+ `UPDATE coord_assignments SET agent_id = ?, status = 'assigned', started_at = datetime('now') WHERE id = ? AND status = 'pending'`
171
+ ).run(agentId, pending.id);
172
+
173
+ if (claimed.changes > 0) {
174
+ db.prepare(
175
+ `UPDATE coord_agents SET status = 'working', current_task = ? WHERE id = ?`
176
+ ).run(pending.id, agentId);
177
+
178
+ db.prepare(
179
+ `INSERT INTO coord_events (agent_id, event_type, detail) VALUES (?, 'assignment_claimed', ?)`
180
+ ).run(agentId, `auto-claimed assignment ${pending.id}`);
181
+
182
+ const assignment = db.prepare(`SELECT * FROM coord_assignments WHERE id = ?`).get(pending.id);
183
+ return reply.send({ assignment });
184
+ }
185
+ }
186
+
187
+ const busyCount = (db.prepare(
188
+ `SELECT COUNT(*) as c FROM coord_agents WHERE status = 'working' AND last_seen > datetime('now', '-120 seconds')`
189
+ ).get() as { c: number }).c;
190
+
191
+ const retryAfter = busyCount > 0 ? 30 : 300;
192
+ return reply.send({ assignment: null, retry_after_seconds: retryAfter });
193
+ });
194
+
195
+ app.post('/assignment/:id/claim', async (req, reply) => {
196
+ const { id } = assignmentIdParamSchema.parse(req.params);
197
+ const parsed = assignmentClaimSchema.safeParse(req.body);
198
+ if (!parsed.success) return reply.code(400).send({ error: parsed.error.issues[0].message });
199
+ const { agentId } = parsed.data;
200
+
201
+ const result = db.prepare(
202
+ `UPDATE coord_assignments SET agent_id = ?, status = 'assigned', started_at = datetime('now') WHERE id = ? AND status = 'pending'`
203
+ ).run(agentId, id);
204
+
205
+ if (result.changes === 0) {
206
+ return reply.code(409).send({ error: 'assignment not available (already claimed or missing)' });
207
+ }
208
+
209
+ db.prepare(
210
+ `UPDATE coord_agents SET status = 'working', current_task = ? WHERE id = ?`
211
+ ).run(id, agentId);
212
+
213
+ db.prepare(
214
+ `INSERT INTO coord_events (agent_id, event_type, detail) VALUES (?, 'assignment_claimed', ?)`
215
+ ).run(agentId, `claimed assignment ${id}`);
216
+
217
+ return reply.send({ ok: true, assignmentId: id });
218
+ });
219
+
220
+ function handleAssignmentUpdate(id: string, status: string, result: string | undefined) {
221
+ if (['completed', 'failed'].includes(status)) {
222
+ db.prepare(
223
+ `UPDATE coord_assignments SET status = ?, result = ?, completed_at = datetime('now') WHERE id = ?`
224
+ ).run(status, result ?? null, id);
225
+ } else {
226
+ db.prepare(
227
+ `UPDATE coord_assignments SET status = ?, result = ? WHERE id = ?`
228
+ ).run(status, result ?? null, id);
229
+ }
230
+
231
+ if (['completed', 'failed'].includes(status)) {
232
+ const assignment = db.prepare(`SELECT agent_id FROM coord_assignments WHERE id = ?`).get(id) as { agent_id: string } | undefined;
233
+ if (assignment?.agent_id) {
234
+ db.prepare(
235
+ `UPDATE coord_agents SET status = 'idle', current_task = NULL WHERE id = ?`
236
+ ).run(assignment.agent_id);
237
+ }
238
+ }
239
+
240
+ db.prepare(
241
+ `INSERT INTO coord_events (agent_id, event_type, detail) VALUES ((SELECT agent_id FROM coord_assignments WHERE id = ?), 'assignment_update', ?)`
242
+ ).run(id, `${id} → ${status}`);
243
+
244
+ // Log completion/failure with agent name and task
245
+ if (['completed', 'failed'].includes(status)) {
246
+ const info = db.prepare(
247
+ `SELECT a.task, g.name AS agent_name FROM coord_assignments a LEFT JOIN coord_agents g ON a.agent_id = g.id WHERE a.id = ?`
248
+ ).get(id) as { task: string; agent_name: string | null } | undefined;
249
+ coordLog(`${info?.agent_name ?? 'unknown'} ${status}: ${info?.task?.slice(0, 80) ?? id}`);
250
+ }
251
+ }
252
+
253
+ app.post('/assignment/:id/update', async (req, reply) => {
254
+ const { id } = assignmentIdParamSchema.parse(req.params);
255
+ const parsed = assignmentUpdateSchema.safeParse(req.body);
256
+ if (!parsed.success) return reply.code(400).send({ error: parsed.error.issues[0].message });
257
+ handleAssignmentUpdate(id, parsed.data.status, parsed.data.result);
258
+ return reply.send({ ok: true });
259
+ });
260
+
261
+ app.patch('/assignment/:id', async (req, reply) => {
262
+ const { id } = assignmentIdParamSchema.parse(req.params);
263
+ const parsed = assignmentUpdateSchema.safeParse(req.body);
264
+ if (!parsed.success) return reply.code(400).send({ error: parsed.error.issues[0].message });
265
+ handleAssignmentUpdate(id, parsed.data.status, parsed.data.result);
266
+ return reply.send({ ok: true });
267
+ });
268
+
269
+ app.put('/assignment/:id', async (req, reply) => {
270
+ const { id } = assignmentIdParamSchema.parse(req.params);
271
+ const parsed = assignmentUpdateSchema.safeParse(req.body);
272
+ if (!parsed.success) return reply.code(400).send({ error: parsed.error.issues[0].message });
273
+ handleAssignmentUpdate(id, parsed.data.status, parsed.data.result);
274
+ return reply.send({ ok: true });
275
+ });
276
+
277
+ // ─── Locks ──────────────────────────────────────────────────────
278
+
279
+ app.post('/lock', async (req, reply) => {
280
+ const parsed = lockAcquireSchema.safeParse(req.body);
281
+ if (!parsed.success) return reply.code(400).send({ error: parsed.error.issues[0].message });
282
+ const { agentId, filePath, reason } = parsed.data;
283
+
284
+ const inserted = db.prepare(
285
+ `INSERT OR IGNORE INTO coord_locks (file_path, agent_id, reason) VALUES (?, ?, ?)`
286
+ ).run(filePath, agentId, reason ?? null);
287
+
288
+ if (inserted.changes > 0) {
289
+ db.prepare(
290
+ `INSERT INTO coord_events (agent_id, event_type, detail) VALUES (?, 'lock_acquired', ?)`
291
+ ).run(agentId, filePath);
292
+ return reply.send({ ok: true, action: 'acquired' });
293
+ }
294
+
295
+ const existing = db.prepare(
296
+ `SELECT agent_id FROM coord_locks WHERE file_path = ?`
297
+ ).get(filePath) as { agent_id: string } | undefined;
298
+
299
+ if (existing?.agent_id === agentId) {
300
+ db.prepare(`UPDATE coord_locks SET locked_at = datetime('now') WHERE file_path = ?`).run(filePath);
301
+ return reply.send({ ok: true, action: 'refreshed' });
302
+ }
303
+
304
+ return reply.code(409).send({
305
+ error: 'file locked by another agent',
306
+ lockedBy: existing?.agent_id,
307
+ });
308
+ });
309
+
310
+ app.delete('/lock', async (req, reply) => {
311
+ const parsed = lockReleaseSchema.safeParse(req.body);
312
+ if (!parsed.success) return reply.code(400).send({ error: parsed.error.issues[0].message });
313
+ const { agentId, filePath } = parsed.data;
314
+
315
+ const result = db.prepare(
316
+ `DELETE FROM coord_locks WHERE file_path = ? AND agent_id = ?`
317
+ ).run(filePath, agentId);
318
+
319
+ if (result.changes === 0) {
320
+ return reply.code(404).send({ error: 'lock not found or not owned by this agent' });
321
+ }
322
+
323
+ db.prepare(
324
+ `INSERT INTO coord_events (agent_id, event_type, detail) VALUES (?, 'lock_released', ?)`
325
+ ).run(agentId, filePath);
326
+
327
+ return reply.send({ ok: true });
328
+ });
329
+
330
+ app.get('/locks', async (_req, reply) => {
331
+ const locks = db.prepare(
332
+ `SELECT l.file_path, l.agent_id, a.name AS agent_name, l.locked_at, l.reason
333
+ FROM coord_locks l JOIN coord_agents a ON l.agent_id = a.id
334
+ ORDER BY l.locked_at DESC`
335
+ ).all();
336
+
337
+ return reply.send({ locks });
338
+ });
339
+
340
+ // ─── Commands ───────────────────────────────────────────────────
341
+
342
+ app.post('/command', async (req, reply) => {
343
+ const parsed = commandCreateSchema.safeParse(req.body);
344
+ if (!parsed.success) return reply.code(400).send({ error: parsed.error.issues[0].message });
345
+ const { command, reason, issuedBy, workspace } = parsed.data;
346
+
347
+ if (command === 'RESUME') {
348
+ if (workspace) {
349
+ db.prepare(
350
+ `UPDATE coord_commands SET cleared_at = datetime('now') WHERE cleared_at IS NULL AND workspace = ?`
351
+ ).run(workspace);
352
+ } else {
353
+ db.prepare(
354
+ `UPDATE coord_commands SET cleared_at = datetime('now') WHERE cleared_at IS NULL`
355
+ ).run();
356
+ }
357
+
358
+ db.prepare(
359
+ `INSERT INTO coord_events (agent_id, event_type, detail) VALUES (?, 'command', ?)`
360
+ ).run(issuedBy ?? null, `RESUME${workspace ? ' [' + workspace + ']' : ''} — commands cleared`);
361
+
362
+ return reply.send({ ok: true, command: 'RESUME', workspace, message: workspace ? `commands cleared for ${workspace}` : 'all active commands cleared' });
363
+ }
364
+
365
+ db.prepare(
366
+ `INSERT INTO coord_commands (command, reason, issued_by, workspace) VALUES (?, ?, ?, ?)`
367
+ ).run(command, reason ?? null, issuedBy ?? null, workspace ?? null);
368
+
369
+ db.prepare(
370
+ `INSERT INTO coord_events (agent_id, event_type, detail) VALUES (?, 'command', ?)`
371
+ ).run(issuedBy ?? null, `${command}${workspace ? ' [' + workspace + ']' : ''}: ${reason ?? 'no reason given'}`);
372
+
373
+ coordLog(`COMMAND: ${command}${reason ? ' — ' + reason : ''}`);
374
+ return reply.code(201).send({ ok: true, command, reason, workspace });
375
+ });
376
+
377
+ app.get('/command', async (req, reply) => {
378
+ const workspace = (req.query as Record<string, string>).workspace;
379
+
380
+ const active = workspace
381
+ ? db.prepare(
382
+ `SELECT id, command, reason, issued_by, issued_at, workspace
383
+ FROM coord_commands WHERE cleared_at IS NULL AND (workspace = ? OR workspace IS NULL)
384
+ ORDER BY issued_at DESC`
385
+ ).all(workspace) as Array<{ id: number; command: string; reason: string; issued_by: string; issued_at: string; workspace: string | null }>
386
+ : db.prepare(
387
+ `SELECT id, command, reason, issued_by, issued_at, workspace
388
+ FROM coord_commands WHERE cleared_at IS NULL
389
+ ORDER BY issued_at DESC`
390
+ ).all() as Array<{ id: number; command: string; reason: string; issued_by: string; issued_at: string; workspace: string | null }>;
391
+
392
+ if (active.length === 0) {
393
+ return reply.send({ active: false, commands: [] });
394
+ }
395
+
396
+ const priority: Record<string, number> = { SHUTDOWN: 3, BUILD_FREEZE: 2, PAUSE: 1 };
397
+ active.sort((a, b) => (priority[b.command] ?? 0) - (priority[a.command] ?? 0));
398
+
399
+ return reply.send({
400
+ active: true,
401
+ command: active[0].command,
402
+ reason: active[0].reason,
403
+ issued_at: active[0].issued_at,
404
+ commands: active,
405
+ });
406
+ });
407
+
408
+ app.get('/command/wait', async (req, reply) => {
409
+ const q = commandWaitQuerySchema.safeParse(req.query);
410
+ const { status: targetStatus, workspace } = q.success ? q.data : { status: 'idle', workspace: undefined };
411
+
412
+ const agents = workspace
413
+ ? db.prepare(
414
+ `SELECT id, name, role, status, current_task, last_seen
415
+ FROM coord_agents WHERE status NOT IN ('dead') AND workspace = ?
416
+ ORDER BY name`
417
+ ).all(workspace) as Array<{ id: string; name: string; role: string; status: string; current_task: string | null; last_seen: string }>
418
+ : db.prepare(
419
+ `SELECT id, name, role, status, current_task, last_seen
420
+ FROM coord_agents WHERE status NOT IN ('dead')
421
+ ORDER BY name`
422
+ ).all() as Array<{ id: string; name: string; role: string; status: string; current_task: string | null; last_seen: string }>;
423
+
424
+ const ready = agents.filter(a => a.status === targetStatus || a.role === 'orchestrator');
425
+ const notReady = agents.filter(a => a.status !== targetStatus && a.role !== 'orchestrator');
426
+
427
+ return reply.send({
428
+ allReady: notReady.length === 0,
429
+ total: agents.length,
430
+ ready: ready.map(a => ({ name: a.name, status: a.status })),
431
+ waiting: notReady.map(a => ({ name: a.name, status: a.status, task: a.current_task })),
432
+ });
433
+ });
434
+
435
+ // ─── Findings ───────────────────────────────────────────────────
436
+
437
+ app.post('/finding', async (req, reply) => {
438
+ const parsed = findingCreateSchema.safeParse(req.body);
439
+ if (!parsed.success) return reply.code(400).send({ error: parsed.error.issues[0].message });
440
+ const { agentId, category, severity, filePath, lineNumber, description, suggestion } = parsed.data;
441
+
442
+ db.prepare(
443
+ `INSERT INTO coord_findings (agent_id, category, severity, file_path, line_number, description, suggestion)
444
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
445
+ ).run(agentId, category, severity ?? 'info', filePath ?? null, lineNumber ?? null, description, suggestion ?? null);
446
+
447
+ db.prepare(
448
+ `INSERT INTO coord_events (agent_id, event_type, detail) VALUES (?, 'finding', ?)`
449
+ ).run(agentId, `[${severity ?? 'info'}] ${category}: ${description.slice(0, 100)}`);
450
+
451
+ return reply.code(201).send({ ok: true });
452
+ });
453
+
454
+ app.get('/findings', async (req, reply) => {
455
+ const q = findingsQuerySchema.safeParse(req.query);
456
+ const { category, severity, status, limit } = q.success ? q.data : { category: undefined, severity: undefined, status: undefined, limit: 50 };
457
+
458
+ let sql = `
459
+ SELECT f.id, f.category, f.severity, f.file_path, f.line_number,
460
+ f.description, f.suggestion, f.status, f.created_at,
461
+ a.name AS agent_name
462
+ FROM coord_findings f JOIN coord_agents a ON f.agent_id = a.id
463
+ WHERE 1=1
464
+ `;
465
+ const params: unknown[] = [];
466
+
467
+ if (category) { sql += ` AND f.category = ?`; params.push(category); }
468
+ if (severity) { sql += ` AND f.severity = ?`; params.push(severity); }
469
+ if (status) { sql += ` AND f.status = ?`; params.push(status); }
470
+
471
+ sql += ` ORDER BY
472
+ CASE f.severity WHEN 'critical' THEN 0 WHEN 'error' THEN 1 WHEN 'warn' THEN 2 ELSE 3 END,
473
+ f.created_at DESC
474
+ LIMIT ?`;
475
+ params.push(limit);
476
+
477
+ const findings = db.prepare(sql).all(...params);
478
+
479
+ const stats = db.prepare(
480
+ `SELECT severity, COUNT(*) as count FROM coord_findings WHERE status = 'open' GROUP BY severity`
481
+ ).all();
482
+
483
+ return reply.send({ findings, stats });
484
+ });
485
+
486
+ app.post('/finding/:id/resolve', async (req, reply) => {
487
+ const { id } = findingIdParamSchema.parse(req.params);
488
+ db.prepare(
489
+ `UPDATE coord_findings SET status = 'resolved', resolved_at = datetime('now') WHERE id = ?`
490
+ ).run(id);
491
+ return reply.send({ ok: true });
492
+ });
493
+
494
+ app.get('/findings/summary', async (_req, reply) => {
495
+ const bySeverity = db.prepare(
496
+ `SELECT severity, COUNT(*) as count FROM coord_findings WHERE status = 'open' GROUP BY severity`
497
+ ).all();
498
+
499
+ const byCategory = db.prepare(
500
+ `SELECT category, COUNT(*) as count FROM coord_findings WHERE status = 'open' GROUP BY category ORDER BY count DESC`
501
+ ).all();
502
+
503
+ const total = db.prepare(
504
+ `SELECT COUNT(*) as total FROM coord_findings WHERE status = 'open'`
505
+ ).get() as { total: number };
506
+
507
+ return reply.send({ total: total.total, bySeverity, byCategory });
508
+ });
509
+
510
+ // ─── Status ─────────────────────────────────────────────────────
511
+
512
+ app.get('/status', async (_req, reply) => {
513
+ const agents = db.prepare(
514
+ `SELECT id, name, role, status, current_task, last_seen,
515
+ ROUND((julianday('now') - julianday(last_seen)) * 86400) AS seconds_since_seen
516
+ FROM coord_agents WHERE status != 'dead'
517
+ ORDER BY role, name`
518
+ ).all();
519
+
520
+ const assignments = db.prepare(
521
+ `SELECT a.id, a.task, a.description, a.status, a.agent_id, ag.name AS agent_name,
522
+ a.created_at, a.started_at, a.completed_at
523
+ FROM coord_assignments a LEFT JOIN coord_agents ag ON a.agent_id = ag.id
524
+ WHERE a.status NOT IN ('completed', 'failed')
525
+ ORDER BY a.created_at`
526
+ ).all();
527
+
528
+ const locks = db.prepare(
529
+ `SELECT l.file_path, l.agent_id, a.name AS agent_name, l.locked_at, l.reason
530
+ FROM coord_locks l JOIN coord_agents a ON l.agent_id = a.id`
531
+ ).all();
532
+
533
+ const stats = db.prepare(
534
+ `SELECT
535
+ (SELECT COUNT(*) FROM coord_agents WHERE status != 'dead') AS alive_agents,
536
+ (SELECT COUNT(*) FROM coord_agents WHERE status = 'working') AS busy_agents,
537
+ (SELECT COUNT(*) FROM coord_assignments WHERE status = 'pending') AS pending_tasks,
538
+ (SELECT COUNT(*) FROM coord_assignments WHERE status IN ('assigned', 'in_progress')) AS active_tasks,
539
+ (SELECT COUNT(*) FROM coord_locks) AS active_locks,
540
+ (SELECT COUNT(*) FROM coord_findings WHERE status = 'open') AS open_findings,
541
+ (SELECT COUNT(*) FROM coord_findings WHERE status = 'open' AND severity IN ('critical', 'error')) AS urgent_findings`
542
+ ).get();
543
+
544
+ const recentFindings = db.prepare(
545
+ `SELECT f.id, f.category, f.severity, f.file_path, f.description, a.name AS agent_name, f.created_at
546
+ FROM coord_findings f JOIN coord_agents a ON f.agent_id = a.id
547
+ WHERE f.status = 'open'
548
+ ORDER BY CASE f.severity WHEN 'critical' THEN 0 WHEN 'error' THEN 1 WHEN 'warn' THEN 2 ELSE 3 END,
549
+ f.created_at DESC
550
+ LIMIT 10`
551
+ ).all();
552
+
553
+ return reply.send({ agents, assignments, locks, stats, recentFindings });
554
+ });
555
+
556
+ app.get('/workers', async (req, reply) => {
557
+ const q = workersQuerySchema.safeParse(req.query);
558
+ const { capability, status: filterStatus, workspace } = q.success ? q.data : { capability: undefined, status: undefined, workspace: undefined };
559
+
560
+ let workers = workspace
561
+ ? db.prepare(
562
+ `SELECT id, name, role, status, current_task, capabilities, workspace, last_seen,
563
+ ROUND((julianday('now') - julianday(last_seen)) * 86400) AS seconds_since_seen
564
+ FROM coord_agents
565
+ WHERE status != 'dead' AND role != 'orchestrator' AND workspace = ?
566
+ ORDER BY name`
567
+ ).all(workspace) as Array<{
568
+ id: string; name: string; role: string; status: string;
569
+ current_task: string | null; capabilities: string | null;
570
+ workspace: string | null; last_seen: string; seconds_since_seen: number;
571
+ }>
572
+ : db.prepare(
573
+ `SELECT id, name, role, status, current_task, capabilities, workspace, last_seen,
574
+ ROUND((julianday('now') - julianday(last_seen)) * 86400) AS seconds_since_seen
575
+ FROM coord_agents
576
+ WHERE status != 'dead' AND role != 'orchestrator'
577
+ ORDER BY name`
578
+ ).all() as Array<{
579
+ id: string; name: string; role: string; status: string;
580
+ current_task: string | null; capabilities: string | null;
581
+ workspace: string | null; last_seen: string; seconds_since_seen: number;
582
+ }>;
583
+
584
+ if (capability) {
585
+ workers = workers.filter(w => {
586
+ if (!w.capabilities) return false;
587
+ try {
588
+ const caps = JSON.parse(w.capabilities) as string[];
589
+ return caps.includes(capability);
590
+ } catch {
591
+ return false;
592
+ }
593
+ });
594
+ }
595
+
596
+ if (filterStatus) {
597
+ workers = workers.filter(w => w.status === filterStatus);
598
+ }
599
+
600
+ const result = workers.map(w => ({
601
+ id: w.id,
602
+ name: w.name,
603
+ role: w.role,
604
+ status: w.status,
605
+ currentTask: w.current_task,
606
+ capabilities: w.capabilities ? JSON.parse(w.capabilities) : [],
607
+ workspace: w.workspace,
608
+ lastSeen: w.last_seen,
609
+ secondsSinceSeen: w.seconds_since_seen,
610
+ alive: w.seconds_since_seen < 120,
611
+ }));
612
+
613
+ return reply.send({
614
+ count: result.length,
615
+ idle: result.filter(w => w.status === 'idle').length,
616
+ working: result.filter(w => w.status === 'working').length,
617
+ workers: result,
618
+ });
619
+ });
620
+
621
+ app.get('/events', async (req, reply) => {
622
+ const q = eventsQuerySchema.safeParse(req.query);
623
+ const limit = q.success ? q.data.limit : 50;
624
+
625
+ const events = db.prepare(
626
+ `SELECT e.id, e.agent_id, a.name AS agent_name, e.event_type, e.detail, e.created_at
627
+ FROM coord_events e LEFT JOIN coord_agents a ON e.agent_id = a.id
628
+ ORDER BY e.created_at DESC LIMIT ?`
629
+ ).all(limit);
630
+
631
+ return reply.send({ events });
632
+ });
633
+
634
+ app.get('/stale', async (req, reply) => {
635
+ const q = staleQuerySchema.safeParse(req.query);
636
+ const threshold = q.success ? q.data.seconds : 120;
637
+ const cleanup = q.success ? q.data.cleanup : undefined;
638
+
639
+ const stale = detectStale(db, threshold);
640
+
641
+ if (cleanup === '1' || cleanup === 'true') {
642
+ const { cleaned } = cleanupStale(db, threshold);
643
+ return reply.send({ stale, threshold_seconds: threshold, cleaned });
644
+ }
645
+
646
+ return reply.send({ stale, threshold_seconds: threshold });
647
+ });
648
+
649
+ app.post('/stale/cleanup', async (req, reply) => {
650
+ const q = staleQuerySchema.safeParse(req.query);
651
+ const threshold = q.success ? q.data.seconds : 120;
652
+
653
+ const { stale, cleaned } = cleanupStale(db, threshold);
654
+ return reply.send({ stale, threshold_seconds: threshold, cleaned });
655
+ });
656
+ }