@hasna/todos 0.9.83 → 0.10.2

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/dist/mcp/index.js CHANGED
@@ -220,6 +220,30 @@ function ensureSchema(db) {
220
220
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
221
221
  updated_at TEXT NOT NULL DEFAULT (datetime('now'))
222
222
  )`);
223
+ ensureTable("task_relationships", `
224
+ CREATE TABLE task_relationships (
225
+ id TEXT PRIMARY KEY,
226
+ source_task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
227
+ target_task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
228
+ relationship_type TEXT NOT NULL,
229
+ metadata TEXT DEFAULT '{}',
230
+ created_by TEXT,
231
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
232
+ CHECK (source_task_id != target_task_id)
233
+ )`);
234
+ ensureTable("kg_edges", `
235
+ CREATE TABLE kg_edges (
236
+ id TEXT PRIMARY KEY,
237
+ source_id TEXT NOT NULL,
238
+ source_type TEXT NOT NULL,
239
+ target_id TEXT NOT NULL,
240
+ target_type TEXT NOT NULL,
241
+ relation_type TEXT NOT NULL,
242
+ weight REAL NOT NULL DEFAULT 1.0,
243
+ metadata TEXT DEFAULT '{}',
244
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
245
+ UNIQUE(source_id, source_type, target_id, target_type, relation_type)
246
+ )`);
223
247
  ensureColumn("projects", "task_list_id", "TEXT");
224
248
  ensureColumn("projects", "task_prefix", "TEXT");
225
249
  ensureColumn("projects", "task_counter", "INTEGER NOT NULL DEFAULT 0");
@@ -244,6 +268,7 @@ function ensureSchema(db) {
244
268
  ensureColumn("agents", "title", "TEXT");
245
269
  ensureColumn("agents", "level", "TEXT");
246
270
  ensureColumn("agents", "org_id", "TEXT");
271
+ ensureColumn("agents", "capabilities", "TEXT DEFAULT '[]'");
247
272
  ensureColumn("projects", "org_id", "TEXT");
248
273
  ensureColumn("plans", "task_list_id", "TEXT");
249
274
  ensureColumn("plans", "agent_id", "TEXT");
@@ -270,6 +295,12 @@ function ensureSchema(db) {
270
295
  ensureIndex("CREATE INDEX IF NOT EXISTS idx_project_sources_project ON project_sources(project_id)");
271
296
  ensureIndex("CREATE INDEX IF NOT EXISTS idx_project_sources_type ON project_sources(type)");
272
297
  ensureIndex("CREATE INDEX IF NOT EXISTS idx_tasks_assigned_by ON tasks(assigned_by)");
298
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_rel_source ON task_relationships(source_task_id)");
299
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_rel_target ON task_relationships(target_task_id)");
300
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_task_rel_type ON task_relationships(relationship_type)");
301
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_kg_source ON kg_edges(source_id, source_type)");
302
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_kg_target ON kg_edges(target_id, target_type)");
303
+ ensureIndex("CREATE INDEX IF NOT EXISTS idx_kg_relation ON kg_edges(relation_type)");
273
304
  }
274
305
  function backfillTaskTags(db) {
275
306
  try {
@@ -730,6 +761,44 @@ var init_database = __esm(() => {
730
761
  ALTER TABLE tasks ADD COLUMN assigned_from_project TEXT;
731
762
  CREATE INDEX IF NOT EXISTS idx_tasks_assigned_by ON tasks(assigned_by);
732
763
  INSERT OR IGNORE INTO _migrations (id) VALUES (26);
764
+ `,
765
+ `
766
+ CREATE TABLE IF NOT EXISTS task_relationships (
767
+ id TEXT PRIMARY KEY,
768
+ source_task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
769
+ target_task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
770
+ relationship_type TEXT NOT NULL CHECK(relationship_type IN ('related_to', 'conflicts_with', 'similar_to', 'duplicates', 'supersedes', 'modifies_same_file')),
771
+ metadata TEXT DEFAULT '{}',
772
+ created_by TEXT,
773
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
774
+ CHECK (source_task_id != target_task_id)
775
+ );
776
+ CREATE INDEX IF NOT EXISTS idx_task_rel_source ON task_relationships(source_task_id);
777
+ CREATE INDEX IF NOT EXISTS idx_task_rel_target ON task_relationships(target_task_id);
778
+ CREATE INDEX IF NOT EXISTS idx_task_rel_type ON task_relationships(relationship_type);
779
+ INSERT OR IGNORE INTO _migrations (id) VALUES (27);
780
+ `,
781
+ `
782
+ CREATE TABLE IF NOT EXISTS kg_edges (
783
+ id TEXT PRIMARY KEY,
784
+ source_id TEXT NOT NULL,
785
+ source_type TEXT NOT NULL,
786
+ target_id TEXT NOT NULL,
787
+ target_type TEXT NOT NULL,
788
+ relation_type TEXT NOT NULL,
789
+ weight REAL NOT NULL DEFAULT 1.0,
790
+ metadata TEXT DEFAULT '{}',
791
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
792
+ UNIQUE(source_id, source_type, target_id, target_type, relation_type)
793
+ );
794
+ CREATE INDEX IF NOT EXISTS idx_kg_source ON kg_edges(source_id, source_type);
795
+ CREATE INDEX IF NOT EXISTS idx_kg_target ON kg_edges(target_id, target_type);
796
+ CREATE INDEX IF NOT EXISTS idx_kg_relation ON kg_edges(relation_type);
797
+ INSERT OR IGNORE INTO _migrations (id) VALUES (28);
798
+ `,
799
+ `
800
+ ALTER TABLE agents ADD COLUMN capabilities TEXT DEFAULT '[]';
801
+ INSERT OR IGNORE INTO _migrations (id) VALUES (29);
733
802
  `
734
803
  ];
735
804
  });
@@ -885,10 +954,12 @@ __export(exports_agents, {
885
954
  updateAgentActivity: () => updateAgentActivity,
886
955
  updateAgent: () => updateAgent,
887
956
  registerAgent: () => registerAgent,
957
+ matchCapabilities: () => matchCapabilities,
888
958
  listAgents: () => listAgents,
889
959
  isAgentConflict: () => isAgentConflict,
890
960
  getOrgChart: () => getOrgChart,
891
961
  getDirectReports: () => getDirectReports,
962
+ getCapableAgents: () => getCapableAgents,
892
963
  getAvailableNamesFromPool: () => getAvailableNamesFromPool,
893
964
  getAgentByName: () => getAgentByName,
894
965
  getAgent: () => getAgent,
@@ -906,30 +977,13 @@ function rowToAgent(row) {
906
977
  return {
907
978
  ...row,
908
979
  permissions: JSON.parse(row.permissions || '["*"]'),
980
+ capabilities: JSON.parse(row.capabilities || "[]"),
909
981
  metadata: JSON.parse(row.metadata || "{}")
910
982
  };
911
983
  }
912
984
  function registerAgent(input, db) {
913
985
  const d = db || getDatabase();
914
986
  const normalizedName = input.name.trim().toLowerCase();
915
- if (input.pool && input.pool.length > 0) {
916
- const poolLower = input.pool.map((n) => n.toLowerCase());
917
- if (!poolLower.includes(normalizedName)) {
918
- const available = getAvailableNamesFromPool(input.pool, d);
919
- const suggestion = available.length > 0 ? available[0] : null;
920
- return {
921
- conflict: true,
922
- pool_violation: true,
923
- existing_id: "",
924
- existing_name: normalizedName,
925
- last_seen_at: "",
926
- session_hint: null,
927
- working_dir: input.working_dir || null,
928
- suggestions: available.slice(0, 5),
929
- message: `"${normalizedName}" is not in this project's agent pool [${input.pool.join(", ")}]. ${available.length > 0 ? `Try: ${available.slice(0, 3).join(", ")}` : "No names are currently available \u2014 wait for an active agent to go stale."}${suggestion ? ` Suggested: ${suggestion}` : ""}`
930
- };
931
- }
932
- }
933
987
  const existing = getAgentByName(normalizedName, d);
934
988
  if (existing) {
935
989
  const lastSeenMs = new Date(existing.last_seen_at).getTime();
@@ -970,8 +1024,8 @@ function registerAgent(input, db) {
970
1024
  }
971
1025
  const id = shortUuid();
972
1026
  const timestamp = now();
973
- d.run(`INSERT INTO agents (id, name, description, role, title, level, permissions, reports_to, org_id, metadata, created_at, last_seen_at, session_id, working_dir)
974
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
1027
+ d.run(`INSERT INTO agents (id, name, description, role, title, level, permissions, capabilities, reports_to, org_id, metadata, created_at, last_seen_at, session_id, working_dir)
1028
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
975
1029
  id,
976
1030
  normalizedName,
977
1031
  input.description || null,
@@ -979,6 +1033,7 @@ function registerAgent(input, db) {
979
1033
  input.title || null,
980
1034
  input.level || null,
981
1035
  JSON.stringify(input.permissions || ["*"]),
1036
+ JSON.stringify(input.capabilities || []),
982
1037
  input.reports_to || null,
983
1038
  input.org_id || null,
984
1039
  JSON.stringify(input.metadata || {}),
@@ -1034,6 +1089,10 @@ function updateAgent(id, input, db) {
1034
1089
  sets.push("permissions = ?");
1035
1090
  params.push(JSON.stringify(input.permissions));
1036
1091
  }
1092
+ if (input.capabilities !== undefined) {
1093
+ sets.push("capabilities = ?");
1094
+ params.push(JSON.stringify(input.capabilities));
1095
+ }
1037
1096
  if (input.title !== undefined) {
1038
1097
  sets.push("title = ?");
1039
1098
  params.push(input.title);
@@ -1081,6 +1140,28 @@ function getOrgChart(db) {
1081
1140
  }
1082
1141
  return buildTree(null);
1083
1142
  }
1143
+ function matchCapabilities(agentCapabilities, requiredCapabilities) {
1144
+ if (requiredCapabilities.length === 0)
1145
+ return 1;
1146
+ if (agentCapabilities.length === 0)
1147
+ return 0;
1148
+ const agentSet = new Set(agentCapabilities.map((c) => c.toLowerCase()));
1149
+ let matches = 0;
1150
+ for (const req of requiredCapabilities) {
1151
+ if (agentSet.has(req.toLowerCase()))
1152
+ matches++;
1153
+ }
1154
+ return matches / requiredCapabilities.length;
1155
+ }
1156
+ function getCapableAgents(capabilities, opts, db) {
1157
+ const agents = listAgents(db);
1158
+ const minScore = opts?.min_score ?? 0.1;
1159
+ const scored = agents.map((agent) => ({
1160
+ agent,
1161
+ score: matchCapabilities(agent.capabilities, capabilities)
1162
+ })).filter((entry) => entry.score >= minScore).sort((a, b) => b.score - a.score);
1163
+ return opts?.limit ? scored.slice(0, opts.limit) : scored;
1164
+ }
1084
1165
  var AGENT_ACTIVE_WINDOW_MS;
1085
1166
  var init_agents = __esm(() => {
1086
1167
  init_database();
@@ -1221,6 +1302,584 @@ var init_handoffs = __esm(() => {
1221
1302
  init_database();
1222
1303
  });
1223
1304
 
1305
+ // src/db/task-relationships.ts
1306
+ var exports_task_relationships = {};
1307
+ __export(exports_task_relationships, {
1308
+ removeTaskRelationshipByPair: () => removeTaskRelationshipByPair,
1309
+ removeTaskRelationship: () => removeTaskRelationship,
1310
+ getTaskRelationships: () => getTaskRelationships,
1311
+ getTaskRelationship: () => getTaskRelationship,
1312
+ findRelatedTaskIds: () => findRelatedTaskIds,
1313
+ autoDetectFileRelationships: () => autoDetectFileRelationships,
1314
+ addTaskRelationship: () => addTaskRelationship,
1315
+ RELATIONSHIP_TYPES: () => RELATIONSHIP_TYPES
1316
+ });
1317
+ function rowToRelationship(row) {
1318
+ return {
1319
+ ...row,
1320
+ relationship_type: row.relationship_type,
1321
+ metadata: JSON.parse(row.metadata || "{}")
1322
+ };
1323
+ }
1324
+ function addTaskRelationship(input, db) {
1325
+ const d = db || getDatabase();
1326
+ const id = uuid();
1327
+ const timestamp = now();
1328
+ if (input.source_task_id === input.target_task_id) {
1329
+ throw new Error("Cannot create a relationship between a task and itself");
1330
+ }
1331
+ const symmetric = ["related_to", "conflicts_with", "similar_to", "modifies_same_file"];
1332
+ if (symmetric.includes(input.relationship_type)) {
1333
+ const existing = d.query(`SELECT id FROM task_relationships
1334
+ WHERE relationship_type = ?
1335
+ AND ((source_task_id = ? AND target_task_id = ?) OR (source_task_id = ? AND target_task_id = ?))`).get(input.relationship_type, input.source_task_id, input.target_task_id, input.target_task_id, input.source_task_id);
1336
+ if (existing) {
1337
+ return getTaskRelationship(existing.id, d);
1338
+ }
1339
+ } else {
1340
+ const existing = d.query("SELECT id FROM task_relationships WHERE source_task_id = ? AND target_task_id = ? AND relationship_type = ?").get(input.source_task_id, input.target_task_id, input.relationship_type);
1341
+ if (existing) {
1342
+ return getTaskRelationship(existing.id, d);
1343
+ }
1344
+ }
1345
+ d.run(`INSERT INTO task_relationships (id, source_task_id, target_task_id, relationship_type, metadata, created_by, created_at)
1346
+ VALUES (?, ?, ?, ?, ?, ?, ?)`, [
1347
+ id,
1348
+ input.source_task_id,
1349
+ input.target_task_id,
1350
+ input.relationship_type,
1351
+ JSON.stringify(input.metadata || {}),
1352
+ input.created_by || null,
1353
+ timestamp
1354
+ ]);
1355
+ return getTaskRelationship(id, d);
1356
+ }
1357
+ function getTaskRelationship(id, db) {
1358
+ const d = db || getDatabase();
1359
+ const row = d.query("SELECT * FROM task_relationships WHERE id = ?").get(id);
1360
+ return row ? rowToRelationship(row) : null;
1361
+ }
1362
+ function removeTaskRelationship(id, db) {
1363
+ const d = db || getDatabase();
1364
+ return d.run("DELETE FROM task_relationships WHERE id = ?", [id]).changes > 0;
1365
+ }
1366
+ function removeTaskRelationshipByPair(sourceTaskId, targetTaskId, relationshipType, db) {
1367
+ const d = db || getDatabase();
1368
+ const symmetric = ["related_to", "conflicts_with", "similar_to", "modifies_same_file"];
1369
+ if (symmetric.includes(relationshipType)) {
1370
+ return d.run(`DELETE FROM task_relationships
1371
+ WHERE relationship_type = ?
1372
+ AND ((source_task_id = ? AND target_task_id = ?) OR (source_task_id = ? AND target_task_id = ?))`, [relationshipType, sourceTaskId, targetTaskId, targetTaskId, sourceTaskId]).changes > 0;
1373
+ }
1374
+ return d.run("DELETE FROM task_relationships WHERE source_task_id = ? AND target_task_id = ? AND relationship_type = ?", [sourceTaskId, targetTaskId, relationshipType]).changes > 0;
1375
+ }
1376
+ function getTaskRelationships(taskId, relationshipType, db) {
1377
+ const d = db || getDatabase();
1378
+ let sql = "SELECT * FROM task_relationships WHERE (source_task_id = ? OR target_task_id = ?)";
1379
+ const params = [taskId, taskId];
1380
+ if (relationshipType) {
1381
+ sql += " AND relationship_type = ?";
1382
+ params.push(relationshipType);
1383
+ }
1384
+ sql += " ORDER BY created_at DESC";
1385
+ return d.query(sql).all(...params).map(rowToRelationship);
1386
+ }
1387
+ function findRelatedTaskIds(taskId, relationshipType, db) {
1388
+ const rels = getTaskRelationships(taskId, relationshipType, db);
1389
+ const ids = new Set;
1390
+ for (const rel of rels) {
1391
+ if (rel.source_task_id === taskId)
1392
+ ids.add(rel.target_task_id);
1393
+ else
1394
+ ids.add(rel.source_task_id);
1395
+ }
1396
+ return [...ids];
1397
+ }
1398
+ function autoDetectFileRelationships(taskId, db) {
1399
+ const d = db || getDatabase();
1400
+ const files = d.query("SELECT path FROM task_files WHERE task_id = ? AND status != 'removed'").all(taskId);
1401
+ const created = [];
1402
+ for (const file of files) {
1403
+ const others = d.query("SELECT DISTINCT task_id FROM task_files WHERE path = ? AND task_id != ? AND status != 'removed'").all(file.path, taskId);
1404
+ for (const other of others) {
1405
+ try {
1406
+ const rel = addTaskRelationship({
1407
+ source_task_id: taskId,
1408
+ target_task_id: other.task_id,
1409
+ relationship_type: "modifies_same_file",
1410
+ metadata: { shared_file: file.path }
1411
+ }, d);
1412
+ created.push(rel);
1413
+ } catch {}
1414
+ }
1415
+ }
1416
+ return created;
1417
+ }
1418
+ var RELATIONSHIP_TYPES;
1419
+ var init_task_relationships = __esm(() => {
1420
+ init_database();
1421
+ RELATIONSHIP_TYPES = [
1422
+ "related_to",
1423
+ "conflicts_with",
1424
+ "similar_to",
1425
+ "duplicates",
1426
+ "supersedes",
1427
+ "modifies_same_file"
1428
+ ];
1429
+ });
1430
+
1431
+ // src/db/kg.ts
1432
+ var exports_kg = {};
1433
+ __export(exports_kg, {
1434
+ syncKgEdges: () => syncKgEdges,
1435
+ removeKgEdges: () => removeKgEdges,
1436
+ getRelated: () => getRelated,
1437
+ getImpactAnalysis: () => getImpactAnalysis,
1438
+ getCriticalPath: () => getCriticalPath,
1439
+ findPath: () => findPath,
1440
+ addKgEdge: () => addKgEdge
1441
+ });
1442
+ function rowToEdge(row) {
1443
+ return {
1444
+ ...row,
1445
+ metadata: JSON.parse(row.metadata || "{}")
1446
+ };
1447
+ }
1448
+ function syncKgEdges(db) {
1449
+ const d = db || getDatabase();
1450
+ let synced = 0;
1451
+ const tx = d.transaction(() => {
1452
+ const deps = d.query("SELECT task_id, depends_on FROM task_dependencies").all();
1453
+ for (const dep of deps) {
1454
+ synced += upsertEdge(d, dep.task_id, "task", dep.depends_on, "task", "depends_on");
1455
+ }
1456
+ const assignments = d.query("SELECT id, assigned_to FROM tasks WHERE assigned_to IS NOT NULL").all();
1457
+ for (const a of assignments) {
1458
+ synced += upsertEdge(d, a.id, "task", a.assigned_to, "agent", "assigned_to");
1459
+ }
1460
+ const agents = d.query("SELECT id, reports_to FROM agents WHERE reports_to IS NOT NULL").all();
1461
+ for (const a of agents) {
1462
+ synced += upsertEdge(d, a.id, "agent", a.reports_to, "agent", "reports_to");
1463
+ }
1464
+ const files = d.query("SELECT task_id, path FROM task_files WHERE status != 'removed'").all();
1465
+ for (const f of files) {
1466
+ synced += upsertEdge(d, f.task_id, "task", f.path, "file", "references_file");
1467
+ }
1468
+ const taskProjects = d.query("SELECT id, project_id FROM tasks WHERE project_id IS NOT NULL").all();
1469
+ for (const tp of taskProjects) {
1470
+ synced += upsertEdge(d, tp.id, "task", tp.project_id, "project", "in_project");
1471
+ }
1472
+ const taskPlans = d.query("SELECT id, plan_id FROM tasks WHERE plan_id IS NOT NULL").all();
1473
+ for (const tp of taskPlans) {
1474
+ synced += upsertEdge(d, tp.id, "task", tp.plan_id, "plan", "in_plan");
1475
+ }
1476
+ try {
1477
+ const rels = d.query("SELECT source_task_id, target_task_id, relationship_type FROM task_relationships").all();
1478
+ for (const r of rels) {
1479
+ synced += upsertEdge(d, r.source_task_id, "task", r.target_task_id, "task", r.relationship_type);
1480
+ }
1481
+ } catch {}
1482
+ });
1483
+ tx();
1484
+ return { synced };
1485
+ }
1486
+ function upsertEdge(d, sourceId, sourceType, targetId, targetType, relationType, weight = 1) {
1487
+ try {
1488
+ d.run(`INSERT OR IGNORE INTO kg_edges (id, source_id, source_type, target_id, target_type, relation_type, weight, metadata, created_at)
1489
+ VALUES (?, ?, ?, ?, ?, ?, ?, '{}', ?)`, [uuid(), sourceId, sourceType, targetId, targetType, relationType, weight, now()]);
1490
+ return 1;
1491
+ } catch {
1492
+ return 0;
1493
+ }
1494
+ }
1495
+ function getRelated(entityId, opts, db) {
1496
+ const d = db || getDatabase();
1497
+ const direction = opts?.direction || "both";
1498
+ const conditions = [];
1499
+ const params = [];
1500
+ if (direction === "outgoing" || direction === "both") {
1501
+ conditions.push("source_id = ?");
1502
+ params.push(entityId);
1503
+ }
1504
+ if (direction === "incoming" || direction === "both") {
1505
+ conditions.push("target_id = ?");
1506
+ params.push(entityId);
1507
+ }
1508
+ let sql = `SELECT * FROM kg_edges WHERE (${conditions.join(" OR ")})`;
1509
+ if (opts?.relation_type) {
1510
+ sql += " AND relation_type = ?";
1511
+ params.push(opts.relation_type);
1512
+ }
1513
+ if (opts?.entity_type) {
1514
+ sql += " AND (source_type = ? OR target_type = ?)";
1515
+ params.push(opts.entity_type, opts.entity_type);
1516
+ }
1517
+ sql += " ORDER BY weight DESC, created_at DESC";
1518
+ if (opts?.limit) {
1519
+ sql += " LIMIT ?";
1520
+ params.push(opts.limit);
1521
+ }
1522
+ return d.query(sql).all(...params).map(rowToEdge);
1523
+ }
1524
+ function findPath(sourceId, targetId, opts, db) {
1525
+ const d = db || getDatabase();
1526
+ const maxDepth = opts?.max_depth || 5;
1527
+ const visited = new Set;
1528
+ const queue = [{ id: sourceId, path: [] }];
1529
+ const results = [];
1530
+ visited.add(sourceId);
1531
+ while (queue.length > 0) {
1532
+ const current = queue.shift();
1533
+ if (current.path.length >= maxDepth)
1534
+ continue;
1535
+ let sql = "SELECT * FROM kg_edges WHERE source_id = ?";
1536
+ const params = [current.id];
1537
+ if (opts?.relation_types && opts.relation_types.length > 0) {
1538
+ const placeholders = opts.relation_types.map(() => "?").join(",");
1539
+ sql += ` AND relation_type IN (${placeholders})`;
1540
+ params.push(...opts.relation_types);
1541
+ }
1542
+ const edges = d.query(sql).all(...params).map(rowToEdge);
1543
+ for (const edge of edges) {
1544
+ const nextId = edge.target_id;
1545
+ const newPath = [...current.path, edge];
1546
+ if (nextId === targetId) {
1547
+ results.push(newPath);
1548
+ if (results.length >= 3)
1549
+ return results;
1550
+ continue;
1551
+ }
1552
+ if (!visited.has(nextId)) {
1553
+ visited.add(nextId);
1554
+ queue.push({ id: nextId, path: newPath });
1555
+ }
1556
+ }
1557
+ }
1558
+ return results;
1559
+ }
1560
+ function getImpactAnalysis(entityId, opts, db) {
1561
+ const d = db || getDatabase();
1562
+ const maxDepth = opts?.max_depth || 3;
1563
+ const results = [];
1564
+ const visited = new Set;
1565
+ visited.add(entityId);
1566
+ const queue = [{ id: entityId, depth: 0 }];
1567
+ while (queue.length > 0) {
1568
+ const current = queue.shift();
1569
+ if (current.depth >= maxDepth)
1570
+ continue;
1571
+ let sql = "SELECT * FROM kg_edges WHERE source_id = ?";
1572
+ const params = [current.id];
1573
+ if (opts?.relation_types && opts.relation_types.length > 0) {
1574
+ const placeholders = opts.relation_types.map(() => "?").join(",");
1575
+ sql += ` AND relation_type IN (${placeholders})`;
1576
+ params.push(...opts.relation_types);
1577
+ }
1578
+ const edges = d.query(sql).all(...params).map(rowToEdge);
1579
+ for (const edge of edges) {
1580
+ if (!visited.has(edge.target_id)) {
1581
+ visited.add(edge.target_id);
1582
+ results.push({
1583
+ entity_id: edge.target_id,
1584
+ entity_type: edge.target_type,
1585
+ depth: current.depth + 1,
1586
+ relation: edge.relation_type
1587
+ });
1588
+ queue.push({ id: edge.target_id, depth: current.depth + 1 });
1589
+ }
1590
+ }
1591
+ }
1592
+ return results;
1593
+ }
1594
+ function getCriticalPath(opts, db) {
1595
+ const d = db || getDatabase();
1596
+ let sql = `SELECT source_id, target_id FROM kg_edges WHERE relation_type = 'depends_on'`;
1597
+ const params = [];
1598
+ if (opts?.project_id) {
1599
+ sql += ` AND source_id IN (SELECT id FROM tasks WHERE project_id = ?)`;
1600
+ params.push(opts.project_id);
1601
+ }
1602
+ const edges = d.query(sql).all(...params);
1603
+ const blocks = new Map;
1604
+ for (const e of edges) {
1605
+ if (!blocks.has(e.target_id))
1606
+ blocks.set(e.target_id, new Set);
1607
+ blocks.get(e.target_id).add(e.source_id);
1608
+ }
1609
+ const results = [];
1610
+ for (const [taskId] of blocks) {
1611
+ const visited = new Set;
1612
+ const q = [taskId];
1613
+ let maxDepth = 0;
1614
+ let depth = 0;
1615
+ let levelSize = q.length;
1616
+ while (q.length > 0) {
1617
+ const node = q.shift();
1618
+ levelSize--;
1619
+ const downstream = blocks.get(node);
1620
+ if (downstream) {
1621
+ for (const d2 of downstream) {
1622
+ if (!visited.has(d2)) {
1623
+ visited.add(d2);
1624
+ q.push(d2);
1625
+ }
1626
+ }
1627
+ }
1628
+ if (levelSize === 0) {
1629
+ depth++;
1630
+ maxDepth = Math.max(maxDepth, depth);
1631
+ levelSize = q.length;
1632
+ }
1633
+ }
1634
+ if (visited.size > 0) {
1635
+ results.push({ task_id: taskId, blocking_count: visited.size, depth: maxDepth });
1636
+ }
1637
+ }
1638
+ results.sort((a, b) => b.blocking_count - a.blocking_count);
1639
+ return results.slice(0, opts?.limit || 20);
1640
+ }
1641
+ function addKgEdge(sourceId, sourceType, targetId, targetType, relationType, weight = 1, metadata, db) {
1642
+ const d = db || getDatabase();
1643
+ const id = uuid();
1644
+ const timestamp = now();
1645
+ d.run(`INSERT OR IGNORE INTO kg_edges (id, source_id, source_type, target_id, target_type, relation_type, weight, metadata, created_at)
1646
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [id, sourceId, sourceType, targetId, targetType, relationType, weight, JSON.stringify(metadata || {}), timestamp]);
1647
+ return { id, source_id: sourceId, source_type: sourceType, target_id: targetId, target_type: targetType, relation_type: relationType, weight, metadata: metadata || {}, created_at: timestamp };
1648
+ }
1649
+ function removeKgEdges(sourceId, targetId, relationType, db) {
1650
+ const d = db || getDatabase();
1651
+ if (relationType) {
1652
+ return d.run("DELETE FROM kg_edges WHERE source_id = ? AND target_id = ? AND relation_type = ?", [sourceId, targetId, relationType]).changes;
1653
+ }
1654
+ return d.run("DELETE FROM kg_edges WHERE source_id = ? AND target_id = ?", [sourceId, targetId]).changes;
1655
+ }
1656
+ var init_kg = __esm(() => {
1657
+ init_database();
1658
+ });
1659
+
1660
+ // src/db/patrol.ts
1661
+ var exports_patrol = {};
1662
+ __export(exports_patrol, {
1663
+ patrolTasks: () => patrolTasks,
1664
+ getReviewQueue: () => getReviewQueue
1665
+ });
1666
+ function rowToTask3(row) {
1667
+ return {
1668
+ ...row,
1669
+ status: row.status,
1670
+ priority: row.priority,
1671
+ tags: JSON.parse(row.tags || "[]"),
1672
+ metadata: JSON.parse(row.metadata || "{}"),
1673
+ requires_approval: Boolean(row.requires_approval)
1674
+ };
1675
+ }
1676
+ function patrolTasks(opts, db) {
1677
+ const d = db || getDatabase();
1678
+ const stuckMinutes = opts?.stuck_minutes || 60;
1679
+ const confidenceThreshold = opts?.confidence_threshold || 0.5;
1680
+ const issues = [];
1681
+ let projectFilter = "";
1682
+ const projectParams = [];
1683
+ if (opts?.project_id) {
1684
+ projectFilter = " AND project_id = ?";
1685
+ projectParams.push(opts.project_id);
1686
+ }
1687
+ const stuckCutoff = new Date(Date.now() - stuckMinutes * 60 * 1000).toISOString();
1688
+ const stuckRows = d.query(`SELECT * FROM tasks WHERE status = 'in_progress' AND updated_at < ?${projectFilter} ORDER BY updated_at ASC`).all(stuckCutoff, ...projectParams);
1689
+ for (const row of stuckRows) {
1690
+ const task = rowToTask3(row);
1691
+ const minutesStuck = Math.round((Date.now() - new Date(task.updated_at).getTime()) / 60000);
1692
+ issues.push({
1693
+ type: "stuck",
1694
+ task_id: task.id,
1695
+ task_title: task.title,
1696
+ severity: minutesStuck > 480 ? "critical" : minutesStuck > 120 ? "high" : "medium",
1697
+ detail: `In progress for ${minutesStuck} minutes without update`
1698
+ });
1699
+ }
1700
+ const lowConfRows = d.query(`SELECT * FROM tasks WHERE status = 'completed' AND confidence IS NOT NULL AND confidence < ?${projectFilter} ORDER BY confidence ASC`).all(confidenceThreshold, ...projectParams);
1701
+ for (const row of lowConfRows) {
1702
+ const task = rowToTask3(row);
1703
+ issues.push({
1704
+ type: "low_confidence",
1705
+ task_id: task.id,
1706
+ task_title: task.title,
1707
+ severity: (task.confidence ?? 0) < 0.3 ? "high" : "medium",
1708
+ detail: `Completed with confidence ${task.confidence} (threshold: ${confidenceThreshold})`
1709
+ });
1710
+ }
1711
+ const orphanedRows = d.query(`SELECT * FROM tasks WHERE status = 'pending' AND project_id IS NULL AND agent_id IS NULL AND assigned_to IS NULL ORDER BY created_at ASC`).all();
1712
+ for (const row of orphanedRows) {
1713
+ const task = rowToTask3(row);
1714
+ issues.push({
1715
+ type: "orphaned",
1716
+ task_id: task.id,
1717
+ task_title: task.title,
1718
+ severity: "low",
1719
+ detail: "Pending task with no project, no agent, and no assignee"
1720
+ });
1721
+ }
1722
+ const needsReviewRows = d.query(`SELECT * FROM tasks WHERE status = 'completed' AND requires_approval = 1 AND approved_by IS NULL${projectFilter} ORDER BY completed_at DESC`).all(...projectParams);
1723
+ for (const row of needsReviewRows) {
1724
+ const task = rowToTask3(row);
1725
+ issues.push({
1726
+ type: "needs_review",
1727
+ task_id: task.id,
1728
+ task_title: task.title,
1729
+ severity: "medium",
1730
+ detail: "Completed but requires approval \u2014 not yet reviewed"
1731
+ });
1732
+ }
1733
+ const pendingWithDeps = d.query(`SELECT t.* FROM tasks t
1734
+ WHERE t.status = 'pending'${projectFilter}
1735
+ AND t.id IN (SELECT task_id FROM task_dependencies)`).all(...projectParams);
1736
+ for (const row of pendingWithDeps) {
1737
+ const deps = d.query(`SELECT d.depends_on, t.status FROM task_dependencies d
1738
+ JOIN tasks t ON t.id = d.depends_on
1739
+ WHERE d.task_id = ?`).all(row.id);
1740
+ if (deps.length > 0 && deps.every((dep) => dep.status === "failed" || dep.status === "cancelled")) {
1741
+ const task = rowToTask3(row);
1742
+ issues.push({
1743
+ type: "zombie_blocked",
1744
+ task_id: task.id,
1745
+ task_title: task.title,
1746
+ severity: "high",
1747
+ detail: `Blocked by ${deps.length} task(s) that are all failed/cancelled \u2014 will never unblock`
1748
+ });
1749
+ }
1750
+ }
1751
+ const severityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
1752
+ issues.sort((a, b) => severityOrder[a.severity] - severityOrder[b.severity]);
1753
+ return {
1754
+ issues,
1755
+ total_issues: issues.length,
1756
+ scanned_at: new Date().toISOString()
1757
+ };
1758
+ }
1759
+ function getReviewQueue(opts, db) {
1760
+ const d = db || getDatabase();
1761
+ let sql = `SELECT * FROM tasks WHERE status = 'completed' AND (
1762
+ (requires_approval = 1 AND approved_by IS NULL)
1763
+ OR (confidence IS NOT NULL AND confidence < 0.5)
1764
+ )`;
1765
+ const params = [];
1766
+ if (opts?.project_id) {
1767
+ sql += " AND project_id = ?";
1768
+ params.push(opts.project_id);
1769
+ }
1770
+ sql += " ORDER BY CASE WHEN requires_approval = 1 AND approved_by IS NULL THEN 0 ELSE 1 END, confidence ASC";
1771
+ if (opts?.limit) {
1772
+ sql += " LIMIT ?";
1773
+ params.push(opts.limit);
1774
+ }
1775
+ return d.query(sql).all(...params).map(rowToTask3);
1776
+ }
1777
+ var init_patrol = __esm(() => {
1778
+ init_database();
1779
+ });
1780
+
1781
+ // src/db/agent-metrics.ts
1782
+ var exports_agent_metrics = {};
1783
+ __export(exports_agent_metrics, {
1784
+ scoreTask: () => scoreTask,
1785
+ getLeaderboard: () => getLeaderboard,
1786
+ getAgentMetrics: () => getAgentMetrics
1787
+ });
1788
+ function getAgentMetrics(agentId, opts, db) {
1789
+ const d = db || getDatabase();
1790
+ const agent = d.query("SELECT id, name FROM agents WHERE id = ? OR LOWER(name) = LOWER(?)").get(agentId, agentId);
1791
+ if (!agent)
1792
+ return null;
1793
+ let projectFilter = "";
1794
+ const params = [agent.id, agent.id];
1795
+ if (opts?.project_id) {
1796
+ projectFilter = " AND project_id = ?";
1797
+ params.push(opts.project_id);
1798
+ }
1799
+ const completed = d.query(`SELECT COUNT(*) as count FROM tasks WHERE (agent_id = ? OR assigned_to = ?) AND status = 'completed'${projectFilter}`).get(...params).count;
1800
+ const failed = d.query(`SELECT COUNT(*) as count FROM tasks WHERE (agent_id = ? OR assigned_to = ?) AND status = 'failed'${projectFilter}`).get(...params).count;
1801
+ const inProgress = d.query(`SELECT COUNT(*) as count FROM tasks WHERE (agent_id = ? OR assigned_to = ?) AND status = 'in_progress'${projectFilter}`).get(...params).count;
1802
+ const total = completed + failed;
1803
+ const completionRate = total > 0 ? completed / total : 0;
1804
+ const avgTime = d.query(`SELECT AVG(
1805
+ (julianday(completed_at) - julianday(created_at)) * 24 * 60
1806
+ ) as avg_minutes
1807
+ FROM tasks
1808
+ WHERE (agent_id = ? OR assigned_to = ?) AND status = 'completed' AND completed_at IS NOT NULL${projectFilter}`).get(...params);
1809
+ const avgConf = d.query(`SELECT AVG(confidence) as avg_confidence
1810
+ FROM tasks
1811
+ WHERE (agent_id = ? OR assigned_to = ?) AND status = 'completed' AND confidence IS NOT NULL${projectFilter}`).get(...params);
1812
+ const reviewTasks = d.query(`SELECT metadata FROM tasks
1813
+ WHERE (agent_id = ? OR assigned_to = ?) AND status = 'completed'${projectFilter}
1814
+ AND metadata LIKE '%_review_score%'`).all(...params);
1815
+ let reviewScoreAvg = null;
1816
+ if (reviewTasks.length > 0) {
1817
+ let total2 = 0;
1818
+ let count = 0;
1819
+ for (const row of reviewTasks) {
1820
+ try {
1821
+ const meta = JSON.parse(row.metadata);
1822
+ if (typeof meta._review_score === "number") {
1823
+ total2 += meta._review_score;
1824
+ count++;
1825
+ }
1826
+ } catch {}
1827
+ }
1828
+ if (count > 0)
1829
+ reviewScoreAvg = total2 / count;
1830
+ }
1831
+ const speedScore = avgTime?.avg_minutes != null ? Math.max(0, 1 - avgTime.avg_minutes / (60 * 24)) : 0.5;
1832
+ const confidenceScore = avgConf?.avg_confidence ?? 0.5;
1833
+ const volumeScore = Math.min(1, completed / 50);
1834
+ const compositeScore = completionRate * 0.3 + speedScore * 0.2 + confidenceScore * 0.3 + volumeScore * 0.2;
1835
+ return {
1836
+ agent_id: agent.id,
1837
+ agent_name: agent.name,
1838
+ tasks_completed: completed,
1839
+ tasks_failed: failed,
1840
+ tasks_in_progress: inProgress,
1841
+ completion_rate: Math.round(completionRate * 1000) / 1000,
1842
+ avg_completion_minutes: avgTime?.avg_minutes != null ? Math.round(avgTime.avg_minutes * 10) / 10 : null,
1843
+ avg_confidence: avgConf?.avg_confidence != null ? Math.round(avgConf.avg_confidence * 1000) / 1000 : null,
1844
+ review_score_avg: reviewScoreAvg != null ? Math.round(reviewScoreAvg * 1000) / 1000 : null,
1845
+ composite_score: Math.round(compositeScore * 1000) / 1000
1846
+ };
1847
+ }
1848
+ function getLeaderboard(opts, db) {
1849
+ const d = db || getDatabase();
1850
+ const agents = d.query("SELECT id FROM agents ORDER BY name").all();
1851
+ const entries = [];
1852
+ for (const agent of agents) {
1853
+ const metrics = getAgentMetrics(agent.id, { project_id: opts?.project_id }, d);
1854
+ if (metrics && (metrics.tasks_completed > 0 || metrics.tasks_failed > 0 || metrics.tasks_in_progress > 0)) {
1855
+ entries.push(metrics);
1856
+ }
1857
+ }
1858
+ entries.sort((a, b) => b.composite_score - a.composite_score);
1859
+ const limit = opts?.limit || 20;
1860
+ return entries.slice(0, limit).map((entry, idx) => ({
1861
+ ...entry,
1862
+ rank: idx + 1
1863
+ }));
1864
+ }
1865
+ function scoreTask(taskId, score, reviewerId, db) {
1866
+ const d = db || getDatabase();
1867
+ if (score < 0 || score > 1)
1868
+ throw new Error("Score must be between 0 and 1");
1869
+ const task = d.query("SELECT metadata FROM tasks WHERE id = ?").get(taskId);
1870
+ if (!task)
1871
+ throw new Error(`Task not found: ${taskId}`);
1872
+ const metadata = JSON.parse(task.metadata || "{}");
1873
+ metadata._review_score = score;
1874
+ if (reviewerId)
1875
+ metadata._reviewed_by = reviewerId;
1876
+ metadata._reviewed_at = now();
1877
+ d.run("UPDATE tasks SET metadata = ?, updated_at = ? WHERE id = ?", [JSON.stringify(metadata), now(), taskId]);
1878
+ }
1879
+ var init_agent_metrics = __esm(() => {
1880
+ init_database();
1881
+ });
1882
+
1224
1883
  // src/mcp/index.ts
1225
1884
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
1226
1885
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -5458,23 +6117,6 @@ function appendSyncConflict(metadata, conflict, limit = 5) {
5458
6117
  }
5459
6118
 
5460
6119
  // src/lib/config.ts
5461
- var DEFAULT_AGENT_POOL = [
5462
- "maximus",
5463
- "cassius",
5464
- "aurelius",
5465
- "brutus",
5466
- "titus",
5467
- "nero",
5468
- "cicero",
5469
- "seneca",
5470
- "cato",
5471
- "julius",
5472
- "marcus",
5473
- "lucius",
5474
- "quintus",
5475
- "gaius",
5476
- "publius"
5477
- ];
5478
6120
  function getConfigPath() {
5479
6121
  return join3(process.env["HOME"] || HOME, ".todos", "config.json");
5480
6122
  }
@@ -5539,7 +6181,7 @@ function getAgentPoolForProject(workingDir) {
5539
6181
  return config.project_pools[bestKey];
5540
6182
  }
5541
6183
  }
5542
- return config.agent_pool || DEFAULT_AGENT_POOL;
6184
+ return config.agent_pool || null;
5543
6185
  }
5544
6186
  function getCompletionGuardConfig(projectPath) {
5545
6187
  const config = loadConfig();
@@ -8551,25 +9193,28 @@ if (shouldRegisterTool("unfocus")) {
8551
9193
  });
8552
9194
  }
8553
9195
  if (shouldRegisterTool("register_agent")) {
8554
- server.tool("register_agent", "Register an agent. Name must be from the project's configured pool. Returns a conflict error with available name suggestions if the name is taken or not allowed.", {
8555
- name: exports_external.string().describe("Agent name \u2014 must be from the project's allowed pool (Roman names by default). Use suggest_agent_name first if unsure."),
9196
+ server.tool("register_agent", "Register an agent. Any name is allowed \u2014 the configured pool is advisory, not enforced. Returns a conflict error if the name is held by a recently-active agent.", {
9197
+ name: exports_external.string().describe("Agent name \u2014 any name is allowed. Use suggest_agent_name to see pool suggestions and avoid conflicts."),
8556
9198
  description: exports_external.string().optional(),
9199
+ capabilities: exports_external.array(exports_external.string()).optional().describe("Agent capabilities/skills for task routing (e.g. ['typescript', 'testing', 'devops'])"),
8557
9200
  session_id: exports_external.string().optional().describe("Unique ID for this coding session (e.g. process PID + timestamp, or env var). Used to detect name collisions across sessions. Store it and pass on every register_agent call."),
8558
9201
  working_dir: exports_external.string().optional().describe("Working directory of this session \u2014 used to look up the project's agent pool and identify who holds the name in a conflict")
8559
- }, async ({ name, description, session_id, working_dir }) => {
9202
+ }, async ({ name, description, capabilities, session_id, working_dir }) => {
8560
9203
  try {
8561
9204
  const pool = getAgentPoolForProject(working_dir);
8562
- const result = registerAgent({ name, description, session_id, working_dir, pool });
9205
+ const result = registerAgent({ name, description, capabilities, session_id, working_dir, pool: pool || undefined });
8563
9206
  if (isAgentConflict(result)) {
8564
9207
  const suggestLine = result.suggestions && result.suggestions.length > 0 ? `
8565
9208
  Available names: ${result.suggestions.join(", ")}` : "";
8566
- const hint = result.pool_violation ? `POOL_VIOLATION: ${result.message}${suggestLine}` : `CONFLICT: ${result.message}${suggestLine}`;
9209
+ const hint = `CONFLICT: ${result.message}${suggestLine}`;
8567
9210
  return {
8568
9211
  content: [{ type: "text", text: hint }],
8569
9212
  isError: true
8570
9213
  };
8571
9214
  }
8572
9215
  const agent = result;
9216
+ const poolLine = pool ? `
9217
+ Pool: [${pool.join(", ")}]` : "";
8573
9218
  return {
8574
9219
  content: [{
8575
9220
  type: "text",
@@ -8577,8 +9222,7 @@ Available names: ${result.suggestions.join(", ")}` : "";
8577
9222
  ID: ${agent.id}
8578
9223
  Name: ${agent.name}${agent.description ? `
8579
9224
  Description: ${agent.description}` : ""}
8580
- Session: ${agent.session_id ?? "unbound"}
8581
- Pool: [${pool.join(", ")}]
9225
+ Session: ${agent.session_id ?? "unbound"}${poolLine}
8582
9226
  Created: ${agent.created_at}
8583
9227
  Last seen: ${agent.last_seen_at}`
8584
9228
  }]
@@ -8589,21 +9233,32 @@ Last seen: ${agent.last_seen_at}`
8589
9233
  });
8590
9234
  }
8591
9235
  if (shouldRegisterTool("suggest_agent_name")) {
8592
- server.tool("suggest_agent_name", "Get available agent names for a project. Call this before register_agent to avoid conflicts.", {
8593
- working_dir: exports_external.string().optional().describe("Your working directory \u2014 used to look up the project's allowed name pool")
9236
+ server.tool("suggest_agent_name", "Get available agent names for a project. Shows configured pool, active agents, and suggestions. If no pool is configured, any name is allowed.", {
9237
+ working_dir: exports_external.string().optional().describe("Your working directory \u2014 used to look up the project's allowed name pool from config")
8594
9238
  }, async ({ working_dir }) => {
8595
9239
  try {
8596
9240
  const pool = getAgentPoolForProject(working_dir);
8597
- const available = getAvailableNamesFromPool(pool, getDatabase());
8598
9241
  const cutoff = new Date(Date.now() - 30 * 60 * 1000).toISOString();
8599
- const active = listAgents().filter((a) => a.last_seen_at > cutoff && pool.map((n) => n.toLowerCase()).includes(a.name));
9242
+ const allActive = listAgents().filter((a) => a.last_seen_at > cutoff);
9243
+ if (!pool) {
9244
+ const lines2 = [
9245
+ "No agent pool configured \u2014 any name is allowed.",
9246
+ allActive.length > 0 ? `Active agents (avoid these names): ${allActive.map((a) => `${a.name} (seen ${Math.round((Date.now() - new Date(a.last_seen_at).getTime()) / 60000)}m ago)`).join(", ")}` : "No active agents.",
9247
+ `
9248
+ To restrict names, configure agent_pool or project_pools in ~/.todos/config.json`
9249
+ ];
9250
+ return { content: [{ type: "text", text: lines2.join(`
9251
+ `) }] };
9252
+ }
9253
+ const available = getAvailableNamesFromPool(pool, getDatabase());
9254
+ const activeInPool = allActive.filter((a) => pool.map((n) => n.toLowerCase()).includes(a.name));
8600
9255
  const lines = [
8601
9256
  `Project pool: ${pool.join(", ")}`,
8602
9257
  `Available now (${available.length}): ${available.length > 0 ? available.join(", ") : "none \u2014 all names in use"}`,
8603
- active.length > 0 ? `Active agents: ${active.map((a) => `${a.name} (seen ${Math.round((Date.now() - new Date(a.last_seen_at).getTime()) / 60000)}m ago)`).join(", ")}` : "Active agents: none",
9258
+ activeInPool.length > 0 ? `Active agents: ${activeInPool.map((a) => `${a.name} (seen ${Math.round((Date.now() - new Date(a.last_seen_at).getTime()) / 60000)}m ago)`).join(", ")}` : "Active agents: none",
8604
9259
  available.length > 0 ? `
8605
9260
  Suggested: ${available[0]}` : `
8606
- No names available yet. Wait for an active agent to go stale (30min timeout).`
9261
+ No names available. Wait for an active agent to go stale (30min timeout).`
8607
9262
  ];
8608
9263
  return { content: [{ type: "text", text: lines.join(`
8609
9264
  `) }] };
@@ -9946,12 +10601,12 @@ if (shouldRegisterTool("describe_tools")) {
9946
10601
  delete_plan: `Delete a plan. Tasks in the plan are orphaned, not deleted.
9947
10602
  Params: id(string, req)
9948
10603
  Example: {id: 'a1b2c3d4'}`,
9949
- suggest_agent_name: `Get available agent names for your project before registering. Shows the pool, which names are active, and the best suggestion.
9950
- Params: working_dir(string \u2014 your working directory, used to look up project pool)
10604
+ suggest_agent_name: `Check available agent names before registering. Shows active agents and, if a pool is configured, which pool names are free.
10605
+ Params: working_dir(string \u2014 your working directory, used to look up project pool from config)
9951
10606
  Example: {working_dir: '/workspace/platform'}`,
9952
- register_agent: `Register an agent. Name must be from the project's pool (call suggest_agent_name first). Returns CONFLICT or POOL_VIOLATION with suggestions if name is taken or not allowed.
9953
- Params: name(string, req), description(string), session_id(string \u2014 unique per session, e.g. PID+timestamp), working_dir(string, req \u2014 used to determine project pool)
9954
- Example: {name: 'cassius', session_id: 'abc123-1741952000', working_dir: '/workspace/platform'}`,
10607
+ register_agent: `Register an agent. Any name is allowed \u2014 pool is advisory. Returns CONFLICT if name is held by a recently-active agent.
10608
+ Params: name(string, req), description(string), capabilities(string[]), session_id(string \u2014 unique per session), working_dir(string \u2014 used to determine project pool)
10609
+ Example: {name: 'my-agent', session_id: 'abc123-1741952000', working_dir: '/workspace/platform'}`,
9955
10610
  list_agents: "List all registered agents with IDs, names, and last seen timestamps. No params.",
9956
10611
  get_agent: `Get agent details by ID or name. Provide one of id or name.
9957
10612
  Params: id(string), name(string)
@@ -10209,6 +10864,328 @@ if (shouldRegisterTool("get_latest_handoff")) {
10209
10864
  }
10210
10865
  });
10211
10866
  }
10867
+ if (shouldRegisterTool("add_task_relationship")) {
10868
+ server.tool("add_task_relationship", "Create a semantic relationship between two tasks (related_to, conflicts_with, similar_to, duplicates, supersedes, modifies_same_file).", {
10869
+ source_task_id: exports_external.string().describe("Source task ID"),
10870
+ target_task_id: exports_external.string().describe("Target task ID"),
10871
+ relationship_type: exports_external.enum(["related_to", "conflicts_with", "similar_to", "duplicates", "supersedes", "modifies_same_file"]).describe("Type of relationship"),
10872
+ created_by: exports_external.string().optional().describe("Agent ID who created this relationship")
10873
+ }, async ({ source_task_id, target_task_id, relationship_type, created_by }) => {
10874
+ try {
10875
+ const { addTaskRelationship: addTaskRelationship2 } = (init_task_relationships(), __toCommonJS(exports_task_relationships));
10876
+ const rel = addTaskRelationship2({
10877
+ source_task_id: resolveId(source_task_id),
10878
+ target_task_id: resolveId(target_task_id),
10879
+ relationship_type,
10880
+ created_by
10881
+ });
10882
+ return { content: [{ type: "text", text: `Relationship created: ${rel.source_task_id.slice(0, 8)} --[${rel.relationship_type}]--> ${rel.target_task_id.slice(0, 8)}` }] };
10883
+ } catch (e) {
10884
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
10885
+ }
10886
+ });
10887
+ }
10888
+ if (shouldRegisterTool("remove_task_relationship")) {
10889
+ server.tool("remove_task_relationship", "Remove a semantic relationship between tasks by ID or by source+target+type.", {
10890
+ id: exports_external.string().optional().describe("Relationship ID to remove"),
10891
+ source_task_id: exports_external.string().optional().describe("Source task ID (use with target_task_id + type)"),
10892
+ target_task_id: exports_external.string().optional().describe("Target task ID"),
10893
+ relationship_type: exports_external.enum(["related_to", "conflicts_with", "similar_to", "duplicates", "supersedes", "modifies_same_file"]).optional()
10894
+ }, async ({ id, source_task_id, target_task_id, relationship_type }) => {
10895
+ try {
10896
+ const { removeTaskRelationship: removeTaskRelationship2, removeTaskRelationshipByPair: removeTaskRelationshipByPair2 } = (init_task_relationships(), __toCommonJS(exports_task_relationships));
10897
+ let removed = false;
10898
+ if (id) {
10899
+ removed = removeTaskRelationship2(id);
10900
+ } else if (source_task_id && target_task_id && relationship_type) {
10901
+ removed = removeTaskRelationshipByPair2(resolveId(source_task_id), resolveId(target_task_id), relationship_type);
10902
+ } else {
10903
+ return { content: [{ type: "text", text: "Provide either 'id' or 'source_task_id + target_task_id + relationship_type'" }], isError: true };
10904
+ }
10905
+ return { content: [{ type: "text", text: removed ? "Relationship removed." : "Relationship not found." }] };
10906
+ } catch (e) {
10907
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
10908
+ }
10909
+ });
10910
+ }
10911
+ if (shouldRegisterTool("get_task_relationships")) {
10912
+ server.tool("get_task_relationships", "Get all semantic relationships for a task.", {
10913
+ task_id: exports_external.string().describe("Task ID"),
10914
+ relationship_type: exports_external.enum(["related_to", "conflicts_with", "similar_to", "duplicates", "supersedes", "modifies_same_file"]).optional()
10915
+ }, async ({ task_id, relationship_type }) => {
10916
+ try {
10917
+ const { getTaskRelationships: getTaskRelationships2 } = (init_task_relationships(), __toCommonJS(exports_task_relationships));
10918
+ const rels = getTaskRelationships2(resolveId(task_id), relationship_type);
10919
+ if (rels.length === 0)
10920
+ return { content: [{ type: "text", text: "No relationships found." }] };
10921
+ const lines = rels.map((r) => `${r.source_task_id.slice(0, 8)} --[${r.relationship_type}]--> ${r.target_task_id.slice(0, 8)}${r.metadata && Object.keys(r.metadata).length > 0 ? ` (${JSON.stringify(r.metadata)})` : ""}`);
10922
+ return { content: [{ type: "text", text: lines.join(`
10923
+ `) }] };
10924
+ } catch (e) {
10925
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
10926
+ }
10927
+ });
10928
+ }
10929
+ if (shouldRegisterTool("detect_file_relationships")) {
10930
+ server.tool("detect_file_relationships", "Auto-detect tasks that modify the same files and create modifies_same_file relationships.", {
10931
+ task_id: exports_external.string().describe("Task ID to detect file relationships for")
10932
+ }, async ({ task_id }) => {
10933
+ try {
10934
+ const { autoDetectFileRelationships: autoDetectFileRelationships2 } = (init_task_relationships(), __toCommonJS(exports_task_relationships));
10935
+ const created = autoDetectFileRelationships2(resolveId(task_id));
10936
+ return { content: [{ type: "text", text: created.length > 0 ? `Created ${created.length} file relationship(s).` : "No file overlaps detected." }] };
10937
+ } catch (e) {
10938
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
10939
+ }
10940
+ });
10941
+ }
10942
+ if (shouldRegisterTool("sync_kg")) {
10943
+ server.tool("sync_kg", "Sync all existing relationships into the knowledge graph edges table. Idempotent.", {}, async () => {
10944
+ try {
10945
+ const { syncKgEdges: syncKgEdges2 } = (init_kg(), __toCommonJS(exports_kg));
10946
+ const result = syncKgEdges2();
10947
+ return { content: [{ type: "text", text: `Knowledge graph synced: ${result.synced} edge(s) processed.` }] };
10948
+ } catch (e) {
10949
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
10950
+ }
10951
+ });
10952
+ }
10953
+ if (shouldRegisterTool("get_related_entities")) {
10954
+ server.tool("get_related_entities", "Get entities related to a given entity in the knowledge graph.", {
10955
+ entity_id: exports_external.string().describe("Entity ID (task, agent, project, file path)"),
10956
+ relation_type: exports_external.string().optional().describe("Filter by relation type (depends_on, assigned_to, reports_to, references_file, in_project, in_plan, etc.)"),
10957
+ entity_type: exports_external.string().optional().describe("Filter by entity type (task, agent, project, file, plan)"),
10958
+ direction: exports_external.enum(["outgoing", "incoming", "both"]).optional().describe("Edge direction"),
10959
+ limit: exports_external.number().optional().describe("Max results")
10960
+ }, async ({ entity_id, relation_type, entity_type, direction, limit }) => {
10961
+ try {
10962
+ const { getRelated: getRelated2 } = (init_kg(), __toCommonJS(exports_kg));
10963
+ const edges = getRelated2(entity_id, { relation_type, entity_type, direction, limit });
10964
+ if (edges.length === 0)
10965
+ return { content: [{ type: "text", text: "No related entities found." }] };
10966
+ const lines = edges.map((e) => `${e.source_id.slice(0, 12)}(${e.source_type}) --[${e.relation_type}]--> ${e.target_id.slice(0, 12)}(${e.target_type})`);
10967
+ return { content: [{ type: "text", text: lines.join(`
10968
+ `) }] };
10969
+ } catch (e) {
10970
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
10971
+ }
10972
+ });
10973
+ }
10974
+ if (shouldRegisterTool("find_path")) {
10975
+ server.tool("find_path", "Find paths between two entities in the knowledge graph.", {
10976
+ source_id: exports_external.string().describe("Starting entity ID"),
10977
+ target_id: exports_external.string().describe("Target entity ID"),
10978
+ max_depth: exports_external.number().optional().describe("Maximum path depth (default: 5)"),
10979
+ relation_types: exports_external.array(exports_external.string()).optional().describe("Filter by relation types")
10980
+ }, async ({ source_id, target_id, max_depth, relation_types }) => {
10981
+ try {
10982
+ const { findPath: findPath2 } = (init_kg(), __toCommonJS(exports_kg));
10983
+ const paths = findPath2(source_id, target_id, { max_depth, relation_types });
10984
+ if (paths.length === 0)
10985
+ return { content: [{ type: "text", text: "No path found." }] };
10986
+ const lines = paths.map((path, i) => {
10987
+ const steps = path.map((e) => `${e.source_id.slice(0, 8)} --[${e.relation_type}]--> ${e.target_id.slice(0, 8)}`);
10988
+ return `Path ${i + 1} (${path.length} hops):
10989
+ ${steps.join(`
10990
+ `)}`;
10991
+ });
10992
+ return { content: [{ type: "text", text: lines.join(`
10993
+
10994
+ `) }] };
10995
+ } catch (e) {
10996
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
10997
+ }
10998
+ });
10999
+ }
11000
+ if (shouldRegisterTool("get_impact_analysis")) {
11001
+ server.tool("get_impact_analysis", "Analyze what entities are affected if a given entity changes. Traverses the knowledge graph.", {
11002
+ entity_id: exports_external.string().describe("Entity ID to analyze impact for"),
11003
+ max_depth: exports_external.number().optional().describe("Maximum traversal depth (default: 3)"),
11004
+ relation_types: exports_external.array(exports_external.string()).optional().describe("Filter by relation types")
11005
+ }, async ({ entity_id, max_depth, relation_types }) => {
11006
+ try {
11007
+ const { getImpactAnalysis: getImpactAnalysis2 } = (init_kg(), __toCommonJS(exports_kg));
11008
+ const impact = getImpactAnalysis2(entity_id, { max_depth, relation_types });
11009
+ if (impact.length === 0)
11010
+ return { content: [{ type: "text", text: "No downstream impact detected." }] };
11011
+ const byDepth = new Map;
11012
+ for (const i of impact) {
11013
+ if (!byDepth.has(i.depth))
11014
+ byDepth.set(i.depth, []);
11015
+ byDepth.get(i.depth).push(i);
11016
+ }
11017
+ const lines = [`Impact analysis: ${impact.length} affected entities`];
11018
+ for (const [depth, entities] of [...byDepth.entries()].sort((a, b) => a[0] - b[0])) {
11019
+ lines.push(`
11020
+ Depth ${depth}:`);
11021
+ for (const e of entities) {
11022
+ lines.push(` ${e.entity_id.slice(0, 12)} (${e.entity_type}) via ${e.relation}`);
11023
+ }
11024
+ }
11025
+ return { content: [{ type: "text", text: lines.join(`
11026
+ `) }] };
11027
+ } catch (e) {
11028
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
11029
+ }
11030
+ });
11031
+ }
11032
+ if (shouldRegisterTool("get_critical_path")) {
11033
+ server.tool("get_critical_path", "Find tasks that block the most downstream work (critical path analysis).", {
11034
+ project_id: exports_external.string().optional().describe("Filter by project"),
11035
+ limit: exports_external.number().optional().describe("Max results (default: 20)")
11036
+ }, async ({ project_id, limit }) => {
11037
+ try {
11038
+ const { getCriticalPath: getCriticalPath2 } = (init_kg(), __toCommonJS(exports_kg));
11039
+ const result = getCriticalPath2({ project_id: project_id ? resolveId(project_id, "projects") : undefined, limit });
11040
+ if (result.length === 0)
11041
+ return { content: [{ type: "text", text: "No critical path data. Run sync_kg first to populate the knowledge graph." }] };
11042
+ const lines = result.map((r, i) => `${i + 1}. ${r.task_id.slice(0, 8)} blocks ${r.blocking_count} task(s), max depth ${r.depth}`);
11043
+ return { content: [{ type: "text", text: `Critical path:
11044
+ ${lines.join(`
11045
+ `)}` }] };
11046
+ } catch (e) {
11047
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
11048
+ }
11049
+ });
11050
+ }
11051
+ if (shouldRegisterTool("get_capable_agents")) {
11052
+ server.tool("get_capable_agents", "Find agents that match given capabilities, sorted by match score.", {
11053
+ capabilities: exports_external.array(exports_external.string()).describe("Required capabilities to match against"),
11054
+ min_score: exports_external.number().optional().describe("Minimum match score 0.0-1.0 (default: 0.1)"),
11055
+ limit: exports_external.number().optional().describe("Max results")
11056
+ }, async ({ capabilities, min_score, limit }) => {
11057
+ try {
11058
+ const { getCapableAgents: getCapableAgents2 } = (init_agents(), __toCommonJS(exports_agents));
11059
+ const results = getCapableAgents2(capabilities, { min_score, limit });
11060
+ if (results.length === 0)
11061
+ return { content: [{ type: "text", text: "No agents match the given capabilities." }] };
11062
+ const lines = results.map((r) => `${r.agent.name} (${r.agent.id}) score:${(r.score * 100).toFixed(0)}% caps:[${r.agent.capabilities.join(",")}]`);
11063
+ return { content: [{ type: "text", text: lines.join(`
11064
+ `) }] };
11065
+ } catch (e) {
11066
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
11067
+ }
11068
+ });
11069
+ }
11070
+ if (shouldRegisterTool("patrol_tasks")) {
11071
+ server.tool("patrol_tasks", "Scan for task issues: stuck tasks, low-confidence completions, orphaned tasks, zombie-blocked tasks, and pending reviews.", {
11072
+ stuck_minutes: exports_external.number().optional().describe("Minutes threshold for stuck detection (default: 60)"),
11073
+ confidence_threshold: exports_external.number().optional().describe("Confidence threshold for low-confidence detection (default: 0.5)"),
11074
+ project_id: exports_external.string().optional().describe("Filter by project")
11075
+ }, async ({ stuck_minutes, confidence_threshold, project_id }) => {
11076
+ try {
11077
+ const { patrolTasks: patrolTasks2 } = (init_patrol(), __toCommonJS(exports_patrol));
11078
+ const result = patrolTasks2({
11079
+ stuck_minutes,
11080
+ confidence_threshold,
11081
+ project_id: project_id ? resolveId(project_id, "projects") : undefined
11082
+ });
11083
+ if (result.total_issues === 0)
11084
+ return { content: [{ type: "text", text: "All clear \u2014 no issues detected." }] };
11085
+ const lines = [`Found ${result.total_issues} issue(s):
11086
+ `];
11087
+ for (const issue of result.issues) {
11088
+ lines.push(`[${issue.severity.toUpperCase()}] ${issue.type}: ${issue.task_title.slice(0, 60)} (${issue.task_id.slice(0, 8)})`);
11089
+ lines.push(` ${issue.detail}`);
11090
+ }
11091
+ return { content: [{ type: "text", text: lines.join(`
11092
+ `) }] };
11093
+ } catch (e) {
11094
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
11095
+ }
11096
+ });
11097
+ }
11098
+ if (shouldRegisterTool("get_review_queue")) {
11099
+ server.tool("get_review_queue", "Get tasks that need review: requires_approval but unapproved, or low confidence completions.", {
11100
+ project_id: exports_external.string().optional().describe("Filter by project"),
11101
+ limit: exports_external.number().optional().describe("Max results (default: all)")
11102
+ }, async ({ project_id, limit }) => {
11103
+ try {
11104
+ const { getReviewQueue: getReviewQueue2 } = (init_patrol(), __toCommonJS(exports_patrol));
11105
+ const tasks = getReviewQueue2({
11106
+ project_id: project_id ? resolveId(project_id, "projects") : undefined,
11107
+ limit
11108
+ });
11109
+ if (tasks.length === 0)
11110
+ return { content: [{ type: "text", text: "Review queue is empty." }] };
11111
+ const lines = tasks.map((t) => {
11112
+ const conf = t.confidence != null ? ` confidence:${t.confidence}` : "";
11113
+ const approval = t.requires_approval && !t.approved_by ? " [needs approval]" : "";
11114
+ return `${t.short_id || t.id.slice(0, 8)} ${t.title.slice(0, 60)}${conf}${approval}`;
11115
+ });
11116
+ return { content: [{ type: "text", text: `Review queue (${tasks.length}):
11117
+ ${lines.join(`
11118
+ `)}` }] };
11119
+ } catch (e) {
11120
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
11121
+ }
11122
+ });
11123
+ }
11124
+ if (shouldRegisterTool("score_task")) {
11125
+ server.tool("score_task", "Score a completed task's quality (0.0-1.0). Stores in task metadata for agent performance tracking.", {
11126
+ task_id: exports_external.string().describe("Task ID to score"),
11127
+ score: exports_external.number().min(0).max(1).describe("Quality score 0.0-1.0"),
11128
+ reviewer_id: exports_external.string().optional().describe("Agent ID of reviewer")
11129
+ }, async ({ task_id, score, reviewer_id }) => {
11130
+ try {
11131
+ const { scoreTask: scoreTask2 } = (init_agent_metrics(), __toCommonJS(exports_agent_metrics));
11132
+ scoreTask2(resolveId(task_id), score, reviewer_id);
11133
+ return { content: [{ type: "text", text: `Task ${task_id.slice(0, 8)} scored: ${score}` }] };
11134
+ } catch (e) {
11135
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
11136
+ }
11137
+ });
11138
+ }
11139
+ if (shouldRegisterTool("get_agent_metrics")) {
11140
+ server.tool("get_agent_metrics", "Get performance metrics for an agent: completion rate, speed, confidence, review scores.", {
11141
+ agent_id: exports_external.string().describe("Agent ID or name"),
11142
+ project_id: exports_external.string().optional().describe("Filter by project")
11143
+ }, async ({ agent_id, project_id }) => {
11144
+ try {
11145
+ const { getAgentMetrics: getAgentMetrics2 } = (init_agent_metrics(), __toCommonJS(exports_agent_metrics));
11146
+ const metrics = getAgentMetrics2(agent_id, {
11147
+ project_id: project_id ? resolveId(project_id, "projects") : undefined
11148
+ });
11149
+ if (!metrics)
11150
+ return { content: [{ type: "text", text: `Agent not found: ${agent_id}` }], isError: true };
11151
+ const lines = [
11152
+ `Agent: ${metrics.agent_name} (${metrics.agent_id})`,
11153
+ `Completed: ${metrics.tasks_completed} | Failed: ${metrics.tasks_failed} | In Progress: ${metrics.tasks_in_progress}`,
11154
+ `Completion Rate: ${(metrics.completion_rate * 100).toFixed(1)}%`,
11155
+ metrics.avg_completion_minutes != null ? `Avg Completion Time: ${metrics.avg_completion_minutes} min` : null,
11156
+ metrics.avg_confidence != null ? `Avg Confidence: ${(metrics.avg_confidence * 100).toFixed(1)}%` : null,
11157
+ metrics.review_score_avg != null ? `Avg Review Score: ${(metrics.review_score_avg * 100).toFixed(1)}%` : null,
11158
+ `Composite Score: ${(metrics.composite_score * 100).toFixed(1)}%`
11159
+ ].filter(Boolean);
11160
+ return { content: [{ type: "text", text: lines.join(`
11161
+ `) }] };
11162
+ } catch (e) {
11163
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
11164
+ }
11165
+ });
11166
+ }
11167
+ if (shouldRegisterTool("get_leaderboard")) {
11168
+ server.tool("get_leaderboard", "Get agent leaderboard ranked by composite performance score.", {
11169
+ project_id: exports_external.string().optional().describe("Filter by project"),
11170
+ limit: exports_external.number().optional().describe("Max entries (default: 20)")
11171
+ }, async ({ project_id, limit }) => {
11172
+ try {
11173
+ const { getLeaderboard: getLeaderboard2 } = (init_agent_metrics(), __toCommonJS(exports_agent_metrics));
11174
+ const entries = getLeaderboard2({
11175
+ project_id: project_id ? resolveId(project_id, "projects") : undefined,
11176
+ limit
11177
+ });
11178
+ if (entries.length === 0)
11179
+ return { content: [{ type: "text", text: "No agents with task activity found." }] };
11180
+ const lines = entries.map((e) => `#${e.rank} ${e.agent_name.padEnd(15)} score:${(e.composite_score * 100).toFixed(0).padStart(3)}% done:${String(e.tasks_completed).padStart(3)} rate:${(e.completion_rate * 100).toFixed(0)}%`);
11181
+ return { content: [{ type: "text", text: `Leaderboard:
11182
+ ${lines.join(`
11183
+ `)}` }] };
11184
+ } catch (e) {
11185
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
11186
+ }
11187
+ });
11188
+ }
10212
11189
  server.resource("task-lists", "todos://task-lists", { description: "All task lists", mimeType: "application/json" }, async () => {
10213
11190
  const lists = listTaskLists();
10214
11191
  return { contents: [{ uri: "todos://task-lists", text: JSON.stringify(lists, null, 2), mimeType: "application/json" }] };