@hasna/todos 0.9.82 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,14 +954,22 @@ __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,
963
+ getAvailableNamesFromPool: () => getAvailableNamesFromPool,
892
964
  getAgentByName: () => getAgentByName,
893
965
  getAgent: () => getAgent,
894
966
  deleteAgent: () => deleteAgent
895
967
  });
968
+ function getAvailableNamesFromPool(pool, db) {
969
+ const cutoff = new Date(Date.now() - AGENT_ACTIVE_WINDOW_MS).toISOString();
970
+ const activeNames = new Set(db.query("SELECT name FROM agents WHERE last_seen_at > ?").all(cutoff).map((r) => r.name.toLowerCase()));
971
+ return pool.filter((name) => !activeNames.has(name.toLowerCase()));
972
+ }
896
973
  function shortUuid() {
897
974
  return crypto.randomUUID().slice(0, 8);
898
975
  }
@@ -900,12 +977,31 @@ function rowToAgent(row) {
900
977
  return {
901
978
  ...row,
902
979
  permissions: JSON.parse(row.permissions || '["*"]'),
980
+ capabilities: JSON.parse(row.capabilities || "[]"),
903
981
  metadata: JSON.parse(row.metadata || "{}")
904
982
  };
905
983
  }
906
984
  function registerAgent(input, db) {
907
985
  const d = db || getDatabase();
908
986
  const normalizedName = input.name.trim().toLowerCase();
987
+ if (input.pool && input.pool.length > 0) {
988
+ const poolLower = input.pool.map((n) => n.toLowerCase());
989
+ if (!poolLower.includes(normalizedName)) {
990
+ const available = getAvailableNamesFromPool(input.pool, d);
991
+ const suggestion = available.length > 0 ? available[0] : null;
992
+ return {
993
+ conflict: true,
994
+ pool_violation: true,
995
+ existing_id: "",
996
+ existing_name: normalizedName,
997
+ last_seen_at: "",
998
+ session_hint: null,
999
+ working_dir: input.working_dir || null,
1000
+ suggestions: available.slice(0, 5),
1001
+ 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}` : ""}`
1002
+ };
1003
+ }
1004
+ }
909
1005
  const existing = getAgentByName(normalizedName, d);
910
1006
  if (existing) {
911
1007
  const lastSeenMs = new Date(existing.last_seen_at).getTime();
@@ -914,6 +1010,7 @@ function registerAgent(input, db) {
914
1010
  const differentSession = input.session_id && existing.session_id && input.session_id !== existing.session_id;
915
1011
  if (isActive && differentSession) {
916
1012
  const minutesAgo = Math.round((Date.now() - lastSeenMs) / 60000);
1013
+ const suggestions = input.pool ? getAvailableNamesFromPool(input.pool, d) : [];
917
1014
  return {
918
1015
  conflict: true,
919
1016
  existing_id: existing.id,
@@ -921,7 +1018,8 @@ function registerAgent(input, db) {
921
1018
  last_seen_at: existing.last_seen_at,
922
1019
  session_hint: existing.session_id ? existing.session_id.slice(0, 8) : null,
923
1020
  working_dir: existing.working_dir,
924
- message: `Agent "${normalizedName}" is already active (last seen ${minutesAgo}m ago, session ${existing.session_id?.slice(0, 8)}\u2026, dir: ${existing.working_dir ?? "unknown"}). Are you that agent? If so, pass session_id="${existing.session_id}" to reclaim it. Otherwise choose a different name.`
1021
+ suggestions: suggestions.slice(0, 5),
1022
+ message: `Agent "${normalizedName}" is already active (last seen ${minutesAgo}m ago, session ${existing.session_id?.slice(0, 8)}\u2026, dir: ${existing.working_dir ?? "unknown"}). Are you that agent? If so, pass session_id="${existing.session_id}" to reclaim it. Otherwise choose a different name.${suggestions.length > 0 ? ` Available: ${suggestions.slice(0, 3).join(", ")}` : ""}`
925
1023
  };
926
1024
  }
927
1025
  const updates = ["last_seen_at = ?"];
@@ -944,8 +1042,8 @@ function registerAgent(input, db) {
944
1042
  }
945
1043
  const id = shortUuid();
946
1044
  const timestamp = now();
947
- 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)
948
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
1045
+ 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)
1046
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
949
1047
  id,
950
1048
  normalizedName,
951
1049
  input.description || null,
@@ -953,6 +1051,7 @@ function registerAgent(input, db) {
953
1051
  input.title || null,
954
1052
  input.level || null,
955
1053
  JSON.stringify(input.permissions || ["*"]),
1054
+ JSON.stringify(input.capabilities || []),
956
1055
  input.reports_to || null,
957
1056
  input.org_id || null,
958
1057
  JSON.stringify(input.metadata || {}),
@@ -1008,6 +1107,10 @@ function updateAgent(id, input, db) {
1008
1107
  sets.push("permissions = ?");
1009
1108
  params.push(JSON.stringify(input.permissions));
1010
1109
  }
1110
+ if (input.capabilities !== undefined) {
1111
+ sets.push("capabilities = ?");
1112
+ params.push(JSON.stringify(input.capabilities));
1113
+ }
1011
1114
  if (input.title !== undefined) {
1012
1115
  sets.push("title = ?");
1013
1116
  params.push(input.title);
@@ -1055,6 +1158,28 @@ function getOrgChart(db) {
1055
1158
  }
1056
1159
  return buildTree(null);
1057
1160
  }
1161
+ function matchCapabilities(agentCapabilities, requiredCapabilities) {
1162
+ if (requiredCapabilities.length === 0)
1163
+ return 1;
1164
+ if (agentCapabilities.length === 0)
1165
+ return 0;
1166
+ const agentSet = new Set(agentCapabilities.map((c) => c.toLowerCase()));
1167
+ let matches = 0;
1168
+ for (const req of requiredCapabilities) {
1169
+ if (agentSet.has(req.toLowerCase()))
1170
+ matches++;
1171
+ }
1172
+ return matches / requiredCapabilities.length;
1173
+ }
1174
+ function getCapableAgents(capabilities, opts, db) {
1175
+ const agents = listAgents(db);
1176
+ const minScore = opts?.min_score ?? 0.1;
1177
+ const scored = agents.map((agent) => ({
1178
+ agent,
1179
+ score: matchCapabilities(agent.capabilities, capabilities)
1180
+ })).filter((entry) => entry.score >= minScore).sort((a, b) => b.score - a.score);
1181
+ return opts?.limit ? scored.slice(0, opts.limit) : scored;
1182
+ }
1058
1183
  var AGENT_ACTIVE_WINDOW_MS;
1059
1184
  var init_agents = __esm(() => {
1060
1185
  init_database();
@@ -1195,6 +1320,584 @@ var init_handoffs = __esm(() => {
1195
1320
  init_database();
1196
1321
  });
1197
1322
 
1323
+ // src/db/task-relationships.ts
1324
+ var exports_task_relationships = {};
1325
+ __export(exports_task_relationships, {
1326
+ removeTaskRelationshipByPair: () => removeTaskRelationshipByPair,
1327
+ removeTaskRelationship: () => removeTaskRelationship,
1328
+ getTaskRelationships: () => getTaskRelationships,
1329
+ getTaskRelationship: () => getTaskRelationship,
1330
+ findRelatedTaskIds: () => findRelatedTaskIds,
1331
+ autoDetectFileRelationships: () => autoDetectFileRelationships,
1332
+ addTaskRelationship: () => addTaskRelationship,
1333
+ RELATIONSHIP_TYPES: () => RELATIONSHIP_TYPES
1334
+ });
1335
+ function rowToRelationship(row) {
1336
+ return {
1337
+ ...row,
1338
+ relationship_type: row.relationship_type,
1339
+ metadata: JSON.parse(row.metadata || "{}")
1340
+ };
1341
+ }
1342
+ function addTaskRelationship(input, db) {
1343
+ const d = db || getDatabase();
1344
+ const id = uuid();
1345
+ const timestamp = now();
1346
+ if (input.source_task_id === input.target_task_id) {
1347
+ throw new Error("Cannot create a relationship between a task and itself");
1348
+ }
1349
+ const symmetric = ["related_to", "conflicts_with", "similar_to", "modifies_same_file"];
1350
+ if (symmetric.includes(input.relationship_type)) {
1351
+ const existing = d.query(`SELECT id FROM task_relationships
1352
+ WHERE relationship_type = ?
1353
+ 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);
1354
+ if (existing) {
1355
+ return getTaskRelationship(existing.id, d);
1356
+ }
1357
+ } else {
1358
+ 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);
1359
+ if (existing) {
1360
+ return getTaskRelationship(existing.id, d);
1361
+ }
1362
+ }
1363
+ d.run(`INSERT INTO task_relationships (id, source_task_id, target_task_id, relationship_type, metadata, created_by, created_at)
1364
+ VALUES (?, ?, ?, ?, ?, ?, ?)`, [
1365
+ id,
1366
+ input.source_task_id,
1367
+ input.target_task_id,
1368
+ input.relationship_type,
1369
+ JSON.stringify(input.metadata || {}),
1370
+ input.created_by || null,
1371
+ timestamp
1372
+ ]);
1373
+ return getTaskRelationship(id, d);
1374
+ }
1375
+ function getTaskRelationship(id, db) {
1376
+ const d = db || getDatabase();
1377
+ const row = d.query("SELECT * FROM task_relationships WHERE id = ?").get(id);
1378
+ return row ? rowToRelationship(row) : null;
1379
+ }
1380
+ function removeTaskRelationship(id, db) {
1381
+ const d = db || getDatabase();
1382
+ return d.run("DELETE FROM task_relationships WHERE id = ?", [id]).changes > 0;
1383
+ }
1384
+ function removeTaskRelationshipByPair(sourceTaskId, targetTaskId, relationshipType, db) {
1385
+ const d = db || getDatabase();
1386
+ const symmetric = ["related_to", "conflicts_with", "similar_to", "modifies_same_file"];
1387
+ if (symmetric.includes(relationshipType)) {
1388
+ return d.run(`DELETE FROM task_relationships
1389
+ WHERE relationship_type = ?
1390
+ AND ((source_task_id = ? AND target_task_id = ?) OR (source_task_id = ? AND target_task_id = ?))`, [relationshipType, sourceTaskId, targetTaskId, targetTaskId, sourceTaskId]).changes > 0;
1391
+ }
1392
+ return d.run("DELETE FROM task_relationships WHERE source_task_id = ? AND target_task_id = ? AND relationship_type = ?", [sourceTaskId, targetTaskId, relationshipType]).changes > 0;
1393
+ }
1394
+ function getTaskRelationships(taskId, relationshipType, db) {
1395
+ const d = db || getDatabase();
1396
+ let sql = "SELECT * FROM task_relationships WHERE (source_task_id = ? OR target_task_id = ?)";
1397
+ const params = [taskId, taskId];
1398
+ if (relationshipType) {
1399
+ sql += " AND relationship_type = ?";
1400
+ params.push(relationshipType);
1401
+ }
1402
+ sql += " ORDER BY created_at DESC";
1403
+ return d.query(sql).all(...params).map(rowToRelationship);
1404
+ }
1405
+ function findRelatedTaskIds(taskId, relationshipType, db) {
1406
+ const rels = getTaskRelationships(taskId, relationshipType, db);
1407
+ const ids = new Set;
1408
+ for (const rel of rels) {
1409
+ if (rel.source_task_id === taskId)
1410
+ ids.add(rel.target_task_id);
1411
+ else
1412
+ ids.add(rel.source_task_id);
1413
+ }
1414
+ return [...ids];
1415
+ }
1416
+ function autoDetectFileRelationships(taskId, db) {
1417
+ const d = db || getDatabase();
1418
+ const files = d.query("SELECT path FROM task_files WHERE task_id = ? AND status != 'removed'").all(taskId);
1419
+ const created = [];
1420
+ for (const file of files) {
1421
+ const others = d.query("SELECT DISTINCT task_id FROM task_files WHERE path = ? AND task_id != ? AND status != 'removed'").all(file.path, taskId);
1422
+ for (const other of others) {
1423
+ try {
1424
+ const rel = addTaskRelationship({
1425
+ source_task_id: taskId,
1426
+ target_task_id: other.task_id,
1427
+ relationship_type: "modifies_same_file",
1428
+ metadata: { shared_file: file.path }
1429
+ }, d);
1430
+ created.push(rel);
1431
+ } catch {}
1432
+ }
1433
+ }
1434
+ return created;
1435
+ }
1436
+ var RELATIONSHIP_TYPES;
1437
+ var init_task_relationships = __esm(() => {
1438
+ init_database();
1439
+ RELATIONSHIP_TYPES = [
1440
+ "related_to",
1441
+ "conflicts_with",
1442
+ "similar_to",
1443
+ "duplicates",
1444
+ "supersedes",
1445
+ "modifies_same_file"
1446
+ ];
1447
+ });
1448
+
1449
+ // src/db/kg.ts
1450
+ var exports_kg = {};
1451
+ __export(exports_kg, {
1452
+ syncKgEdges: () => syncKgEdges,
1453
+ removeKgEdges: () => removeKgEdges,
1454
+ getRelated: () => getRelated,
1455
+ getImpactAnalysis: () => getImpactAnalysis,
1456
+ getCriticalPath: () => getCriticalPath,
1457
+ findPath: () => findPath,
1458
+ addKgEdge: () => addKgEdge
1459
+ });
1460
+ function rowToEdge(row) {
1461
+ return {
1462
+ ...row,
1463
+ metadata: JSON.parse(row.metadata || "{}")
1464
+ };
1465
+ }
1466
+ function syncKgEdges(db) {
1467
+ const d = db || getDatabase();
1468
+ let synced = 0;
1469
+ const tx = d.transaction(() => {
1470
+ const deps = d.query("SELECT task_id, depends_on FROM task_dependencies").all();
1471
+ for (const dep of deps) {
1472
+ synced += upsertEdge(d, dep.task_id, "task", dep.depends_on, "task", "depends_on");
1473
+ }
1474
+ const assignments = d.query("SELECT id, assigned_to FROM tasks WHERE assigned_to IS NOT NULL").all();
1475
+ for (const a of assignments) {
1476
+ synced += upsertEdge(d, a.id, "task", a.assigned_to, "agent", "assigned_to");
1477
+ }
1478
+ const agents = d.query("SELECT id, reports_to FROM agents WHERE reports_to IS NOT NULL").all();
1479
+ for (const a of agents) {
1480
+ synced += upsertEdge(d, a.id, "agent", a.reports_to, "agent", "reports_to");
1481
+ }
1482
+ const files = d.query("SELECT task_id, path FROM task_files WHERE status != 'removed'").all();
1483
+ for (const f of files) {
1484
+ synced += upsertEdge(d, f.task_id, "task", f.path, "file", "references_file");
1485
+ }
1486
+ const taskProjects = d.query("SELECT id, project_id FROM tasks WHERE project_id IS NOT NULL").all();
1487
+ for (const tp of taskProjects) {
1488
+ synced += upsertEdge(d, tp.id, "task", tp.project_id, "project", "in_project");
1489
+ }
1490
+ const taskPlans = d.query("SELECT id, plan_id FROM tasks WHERE plan_id IS NOT NULL").all();
1491
+ for (const tp of taskPlans) {
1492
+ synced += upsertEdge(d, tp.id, "task", tp.plan_id, "plan", "in_plan");
1493
+ }
1494
+ try {
1495
+ const rels = d.query("SELECT source_task_id, target_task_id, relationship_type FROM task_relationships").all();
1496
+ for (const r of rels) {
1497
+ synced += upsertEdge(d, r.source_task_id, "task", r.target_task_id, "task", r.relationship_type);
1498
+ }
1499
+ } catch {}
1500
+ });
1501
+ tx();
1502
+ return { synced };
1503
+ }
1504
+ function upsertEdge(d, sourceId, sourceType, targetId, targetType, relationType, weight = 1) {
1505
+ try {
1506
+ d.run(`INSERT OR IGNORE INTO kg_edges (id, source_id, source_type, target_id, target_type, relation_type, weight, metadata, created_at)
1507
+ VALUES (?, ?, ?, ?, ?, ?, ?, '{}', ?)`, [uuid(), sourceId, sourceType, targetId, targetType, relationType, weight, now()]);
1508
+ return 1;
1509
+ } catch {
1510
+ return 0;
1511
+ }
1512
+ }
1513
+ function getRelated(entityId, opts, db) {
1514
+ const d = db || getDatabase();
1515
+ const direction = opts?.direction || "both";
1516
+ const conditions = [];
1517
+ const params = [];
1518
+ if (direction === "outgoing" || direction === "both") {
1519
+ conditions.push("source_id = ?");
1520
+ params.push(entityId);
1521
+ }
1522
+ if (direction === "incoming" || direction === "both") {
1523
+ conditions.push("target_id = ?");
1524
+ params.push(entityId);
1525
+ }
1526
+ let sql = `SELECT * FROM kg_edges WHERE (${conditions.join(" OR ")})`;
1527
+ if (opts?.relation_type) {
1528
+ sql += " AND relation_type = ?";
1529
+ params.push(opts.relation_type);
1530
+ }
1531
+ if (opts?.entity_type) {
1532
+ sql += " AND (source_type = ? OR target_type = ?)";
1533
+ params.push(opts.entity_type, opts.entity_type);
1534
+ }
1535
+ sql += " ORDER BY weight DESC, created_at DESC";
1536
+ if (opts?.limit) {
1537
+ sql += " LIMIT ?";
1538
+ params.push(opts.limit);
1539
+ }
1540
+ return d.query(sql).all(...params).map(rowToEdge);
1541
+ }
1542
+ function findPath(sourceId, targetId, opts, db) {
1543
+ const d = db || getDatabase();
1544
+ const maxDepth = opts?.max_depth || 5;
1545
+ const visited = new Set;
1546
+ const queue = [{ id: sourceId, path: [] }];
1547
+ const results = [];
1548
+ visited.add(sourceId);
1549
+ while (queue.length > 0) {
1550
+ const current = queue.shift();
1551
+ if (current.path.length >= maxDepth)
1552
+ continue;
1553
+ let sql = "SELECT * FROM kg_edges WHERE source_id = ?";
1554
+ const params = [current.id];
1555
+ if (opts?.relation_types && opts.relation_types.length > 0) {
1556
+ const placeholders = opts.relation_types.map(() => "?").join(",");
1557
+ sql += ` AND relation_type IN (${placeholders})`;
1558
+ params.push(...opts.relation_types);
1559
+ }
1560
+ const edges = d.query(sql).all(...params).map(rowToEdge);
1561
+ for (const edge of edges) {
1562
+ const nextId = edge.target_id;
1563
+ const newPath = [...current.path, edge];
1564
+ if (nextId === targetId) {
1565
+ results.push(newPath);
1566
+ if (results.length >= 3)
1567
+ return results;
1568
+ continue;
1569
+ }
1570
+ if (!visited.has(nextId)) {
1571
+ visited.add(nextId);
1572
+ queue.push({ id: nextId, path: newPath });
1573
+ }
1574
+ }
1575
+ }
1576
+ return results;
1577
+ }
1578
+ function getImpactAnalysis(entityId, opts, db) {
1579
+ const d = db || getDatabase();
1580
+ const maxDepth = opts?.max_depth || 3;
1581
+ const results = [];
1582
+ const visited = new Set;
1583
+ visited.add(entityId);
1584
+ const queue = [{ id: entityId, depth: 0 }];
1585
+ while (queue.length > 0) {
1586
+ const current = queue.shift();
1587
+ if (current.depth >= maxDepth)
1588
+ continue;
1589
+ let sql = "SELECT * FROM kg_edges WHERE source_id = ?";
1590
+ const params = [current.id];
1591
+ if (opts?.relation_types && opts.relation_types.length > 0) {
1592
+ const placeholders = opts.relation_types.map(() => "?").join(",");
1593
+ sql += ` AND relation_type IN (${placeholders})`;
1594
+ params.push(...opts.relation_types);
1595
+ }
1596
+ const edges = d.query(sql).all(...params).map(rowToEdge);
1597
+ for (const edge of edges) {
1598
+ if (!visited.has(edge.target_id)) {
1599
+ visited.add(edge.target_id);
1600
+ results.push({
1601
+ entity_id: edge.target_id,
1602
+ entity_type: edge.target_type,
1603
+ depth: current.depth + 1,
1604
+ relation: edge.relation_type
1605
+ });
1606
+ queue.push({ id: edge.target_id, depth: current.depth + 1 });
1607
+ }
1608
+ }
1609
+ }
1610
+ return results;
1611
+ }
1612
+ function getCriticalPath(opts, db) {
1613
+ const d = db || getDatabase();
1614
+ let sql = `SELECT source_id, target_id FROM kg_edges WHERE relation_type = 'depends_on'`;
1615
+ const params = [];
1616
+ if (opts?.project_id) {
1617
+ sql += ` AND source_id IN (SELECT id FROM tasks WHERE project_id = ?)`;
1618
+ params.push(opts.project_id);
1619
+ }
1620
+ const edges = d.query(sql).all(...params);
1621
+ const blocks = new Map;
1622
+ for (const e of edges) {
1623
+ if (!blocks.has(e.target_id))
1624
+ blocks.set(e.target_id, new Set);
1625
+ blocks.get(e.target_id).add(e.source_id);
1626
+ }
1627
+ const results = [];
1628
+ for (const [taskId] of blocks) {
1629
+ const visited = new Set;
1630
+ const q = [taskId];
1631
+ let maxDepth = 0;
1632
+ let depth = 0;
1633
+ let levelSize = q.length;
1634
+ while (q.length > 0) {
1635
+ const node = q.shift();
1636
+ levelSize--;
1637
+ const downstream = blocks.get(node);
1638
+ if (downstream) {
1639
+ for (const d2 of downstream) {
1640
+ if (!visited.has(d2)) {
1641
+ visited.add(d2);
1642
+ q.push(d2);
1643
+ }
1644
+ }
1645
+ }
1646
+ if (levelSize === 0) {
1647
+ depth++;
1648
+ maxDepth = Math.max(maxDepth, depth);
1649
+ levelSize = q.length;
1650
+ }
1651
+ }
1652
+ if (visited.size > 0) {
1653
+ results.push({ task_id: taskId, blocking_count: visited.size, depth: maxDepth });
1654
+ }
1655
+ }
1656
+ results.sort((a, b) => b.blocking_count - a.blocking_count);
1657
+ return results.slice(0, opts?.limit || 20);
1658
+ }
1659
+ function addKgEdge(sourceId, sourceType, targetId, targetType, relationType, weight = 1, metadata, db) {
1660
+ const d = db || getDatabase();
1661
+ const id = uuid();
1662
+ const timestamp = now();
1663
+ d.run(`INSERT OR IGNORE INTO kg_edges (id, source_id, source_type, target_id, target_type, relation_type, weight, metadata, created_at)
1664
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [id, sourceId, sourceType, targetId, targetType, relationType, weight, JSON.stringify(metadata || {}), timestamp]);
1665
+ return { id, source_id: sourceId, source_type: sourceType, target_id: targetId, target_type: targetType, relation_type: relationType, weight, metadata: metadata || {}, created_at: timestamp };
1666
+ }
1667
+ function removeKgEdges(sourceId, targetId, relationType, db) {
1668
+ const d = db || getDatabase();
1669
+ if (relationType) {
1670
+ return d.run("DELETE FROM kg_edges WHERE source_id = ? AND target_id = ? AND relation_type = ?", [sourceId, targetId, relationType]).changes;
1671
+ }
1672
+ return d.run("DELETE FROM kg_edges WHERE source_id = ? AND target_id = ?", [sourceId, targetId]).changes;
1673
+ }
1674
+ var init_kg = __esm(() => {
1675
+ init_database();
1676
+ });
1677
+
1678
+ // src/db/patrol.ts
1679
+ var exports_patrol = {};
1680
+ __export(exports_patrol, {
1681
+ patrolTasks: () => patrolTasks,
1682
+ getReviewQueue: () => getReviewQueue
1683
+ });
1684
+ function rowToTask3(row) {
1685
+ return {
1686
+ ...row,
1687
+ status: row.status,
1688
+ priority: row.priority,
1689
+ tags: JSON.parse(row.tags || "[]"),
1690
+ metadata: JSON.parse(row.metadata || "{}"),
1691
+ requires_approval: Boolean(row.requires_approval)
1692
+ };
1693
+ }
1694
+ function patrolTasks(opts, db) {
1695
+ const d = db || getDatabase();
1696
+ const stuckMinutes = opts?.stuck_minutes || 60;
1697
+ const confidenceThreshold = opts?.confidence_threshold || 0.5;
1698
+ const issues = [];
1699
+ let projectFilter = "";
1700
+ const projectParams = [];
1701
+ if (opts?.project_id) {
1702
+ projectFilter = " AND project_id = ?";
1703
+ projectParams.push(opts.project_id);
1704
+ }
1705
+ const stuckCutoff = new Date(Date.now() - stuckMinutes * 60 * 1000).toISOString();
1706
+ const stuckRows = d.query(`SELECT * FROM tasks WHERE status = 'in_progress' AND updated_at < ?${projectFilter} ORDER BY updated_at ASC`).all(stuckCutoff, ...projectParams);
1707
+ for (const row of stuckRows) {
1708
+ const task = rowToTask3(row);
1709
+ const minutesStuck = Math.round((Date.now() - new Date(task.updated_at).getTime()) / 60000);
1710
+ issues.push({
1711
+ type: "stuck",
1712
+ task_id: task.id,
1713
+ task_title: task.title,
1714
+ severity: minutesStuck > 480 ? "critical" : minutesStuck > 120 ? "high" : "medium",
1715
+ detail: `In progress for ${minutesStuck} minutes without update`
1716
+ });
1717
+ }
1718
+ 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);
1719
+ for (const row of lowConfRows) {
1720
+ const task = rowToTask3(row);
1721
+ issues.push({
1722
+ type: "low_confidence",
1723
+ task_id: task.id,
1724
+ task_title: task.title,
1725
+ severity: (task.confidence ?? 0) < 0.3 ? "high" : "medium",
1726
+ detail: `Completed with confidence ${task.confidence} (threshold: ${confidenceThreshold})`
1727
+ });
1728
+ }
1729
+ 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();
1730
+ for (const row of orphanedRows) {
1731
+ const task = rowToTask3(row);
1732
+ issues.push({
1733
+ type: "orphaned",
1734
+ task_id: task.id,
1735
+ task_title: task.title,
1736
+ severity: "low",
1737
+ detail: "Pending task with no project, no agent, and no assignee"
1738
+ });
1739
+ }
1740
+ 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);
1741
+ for (const row of needsReviewRows) {
1742
+ const task = rowToTask3(row);
1743
+ issues.push({
1744
+ type: "needs_review",
1745
+ task_id: task.id,
1746
+ task_title: task.title,
1747
+ severity: "medium",
1748
+ detail: "Completed but requires approval \u2014 not yet reviewed"
1749
+ });
1750
+ }
1751
+ const pendingWithDeps = d.query(`SELECT t.* FROM tasks t
1752
+ WHERE t.status = 'pending'${projectFilter}
1753
+ AND t.id IN (SELECT task_id FROM task_dependencies)`).all(...projectParams);
1754
+ for (const row of pendingWithDeps) {
1755
+ const deps = d.query(`SELECT d.depends_on, t.status FROM task_dependencies d
1756
+ JOIN tasks t ON t.id = d.depends_on
1757
+ WHERE d.task_id = ?`).all(row.id);
1758
+ if (deps.length > 0 && deps.every((dep) => dep.status === "failed" || dep.status === "cancelled")) {
1759
+ const task = rowToTask3(row);
1760
+ issues.push({
1761
+ type: "zombie_blocked",
1762
+ task_id: task.id,
1763
+ task_title: task.title,
1764
+ severity: "high",
1765
+ detail: `Blocked by ${deps.length} task(s) that are all failed/cancelled \u2014 will never unblock`
1766
+ });
1767
+ }
1768
+ }
1769
+ const severityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
1770
+ issues.sort((a, b) => severityOrder[a.severity] - severityOrder[b.severity]);
1771
+ return {
1772
+ issues,
1773
+ total_issues: issues.length,
1774
+ scanned_at: new Date().toISOString()
1775
+ };
1776
+ }
1777
+ function getReviewQueue(opts, db) {
1778
+ const d = db || getDatabase();
1779
+ let sql = `SELECT * FROM tasks WHERE status = 'completed' AND (
1780
+ (requires_approval = 1 AND approved_by IS NULL)
1781
+ OR (confidence IS NOT NULL AND confidence < 0.5)
1782
+ )`;
1783
+ const params = [];
1784
+ if (opts?.project_id) {
1785
+ sql += " AND project_id = ?";
1786
+ params.push(opts.project_id);
1787
+ }
1788
+ sql += " ORDER BY CASE WHEN requires_approval = 1 AND approved_by IS NULL THEN 0 ELSE 1 END, confidence ASC";
1789
+ if (opts?.limit) {
1790
+ sql += " LIMIT ?";
1791
+ params.push(opts.limit);
1792
+ }
1793
+ return d.query(sql).all(...params).map(rowToTask3);
1794
+ }
1795
+ var init_patrol = __esm(() => {
1796
+ init_database();
1797
+ });
1798
+
1799
+ // src/db/agent-metrics.ts
1800
+ var exports_agent_metrics = {};
1801
+ __export(exports_agent_metrics, {
1802
+ scoreTask: () => scoreTask,
1803
+ getLeaderboard: () => getLeaderboard,
1804
+ getAgentMetrics: () => getAgentMetrics
1805
+ });
1806
+ function getAgentMetrics(agentId, opts, db) {
1807
+ const d = db || getDatabase();
1808
+ const agent = d.query("SELECT id, name FROM agents WHERE id = ? OR LOWER(name) = LOWER(?)").get(agentId, agentId);
1809
+ if (!agent)
1810
+ return null;
1811
+ let projectFilter = "";
1812
+ const params = [agent.id, agent.id];
1813
+ if (opts?.project_id) {
1814
+ projectFilter = " AND project_id = ?";
1815
+ params.push(opts.project_id);
1816
+ }
1817
+ const completed = d.query(`SELECT COUNT(*) as count FROM tasks WHERE (agent_id = ? OR assigned_to = ?) AND status = 'completed'${projectFilter}`).get(...params).count;
1818
+ const failed = d.query(`SELECT COUNT(*) as count FROM tasks WHERE (agent_id = ? OR assigned_to = ?) AND status = 'failed'${projectFilter}`).get(...params).count;
1819
+ const inProgress = d.query(`SELECT COUNT(*) as count FROM tasks WHERE (agent_id = ? OR assigned_to = ?) AND status = 'in_progress'${projectFilter}`).get(...params).count;
1820
+ const total = completed + failed;
1821
+ const completionRate = total > 0 ? completed / total : 0;
1822
+ const avgTime = d.query(`SELECT AVG(
1823
+ (julianday(completed_at) - julianday(created_at)) * 24 * 60
1824
+ ) as avg_minutes
1825
+ FROM tasks
1826
+ WHERE (agent_id = ? OR assigned_to = ?) AND status = 'completed' AND completed_at IS NOT NULL${projectFilter}`).get(...params);
1827
+ const avgConf = d.query(`SELECT AVG(confidence) as avg_confidence
1828
+ FROM tasks
1829
+ WHERE (agent_id = ? OR assigned_to = ?) AND status = 'completed' AND confidence IS NOT NULL${projectFilter}`).get(...params);
1830
+ const reviewTasks = d.query(`SELECT metadata FROM tasks
1831
+ WHERE (agent_id = ? OR assigned_to = ?) AND status = 'completed'${projectFilter}
1832
+ AND metadata LIKE '%_review_score%'`).all(...params);
1833
+ let reviewScoreAvg = null;
1834
+ if (reviewTasks.length > 0) {
1835
+ let total2 = 0;
1836
+ let count = 0;
1837
+ for (const row of reviewTasks) {
1838
+ try {
1839
+ const meta = JSON.parse(row.metadata);
1840
+ if (typeof meta._review_score === "number") {
1841
+ total2 += meta._review_score;
1842
+ count++;
1843
+ }
1844
+ } catch {}
1845
+ }
1846
+ if (count > 0)
1847
+ reviewScoreAvg = total2 / count;
1848
+ }
1849
+ const speedScore = avgTime?.avg_minutes != null ? Math.max(0, 1 - avgTime.avg_minutes / (60 * 24)) : 0.5;
1850
+ const confidenceScore = avgConf?.avg_confidence ?? 0.5;
1851
+ const volumeScore = Math.min(1, completed / 50);
1852
+ const compositeScore = completionRate * 0.3 + speedScore * 0.2 + confidenceScore * 0.3 + volumeScore * 0.2;
1853
+ return {
1854
+ agent_id: agent.id,
1855
+ agent_name: agent.name,
1856
+ tasks_completed: completed,
1857
+ tasks_failed: failed,
1858
+ tasks_in_progress: inProgress,
1859
+ completion_rate: Math.round(completionRate * 1000) / 1000,
1860
+ avg_completion_minutes: avgTime?.avg_minutes != null ? Math.round(avgTime.avg_minutes * 10) / 10 : null,
1861
+ avg_confidence: avgConf?.avg_confidence != null ? Math.round(avgConf.avg_confidence * 1000) / 1000 : null,
1862
+ review_score_avg: reviewScoreAvg != null ? Math.round(reviewScoreAvg * 1000) / 1000 : null,
1863
+ composite_score: Math.round(compositeScore * 1000) / 1000
1864
+ };
1865
+ }
1866
+ function getLeaderboard(opts, db) {
1867
+ const d = db || getDatabase();
1868
+ const agents = d.query("SELECT id FROM agents ORDER BY name").all();
1869
+ const entries = [];
1870
+ for (const agent of agents) {
1871
+ const metrics = getAgentMetrics(agent.id, { project_id: opts?.project_id }, d);
1872
+ if (metrics && (metrics.tasks_completed > 0 || metrics.tasks_failed > 0 || metrics.tasks_in_progress > 0)) {
1873
+ entries.push(metrics);
1874
+ }
1875
+ }
1876
+ entries.sort((a, b) => b.composite_score - a.composite_score);
1877
+ const limit = opts?.limit || 20;
1878
+ return entries.slice(0, limit).map((entry, idx) => ({
1879
+ ...entry,
1880
+ rank: idx + 1
1881
+ }));
1882
+ }
1883
+ function scoreTask(taskId, score, reviewerId, db) {
1884
+ const d = db || getDatabase();
1885
+ if (score < 0 || score > 1)
1886
+ throw new Error("Score must be between 0 and 1");
1887
+ const task = d.query("SELECT metadata FROM tasks WHERE id = ?").get(taskId);
1888
+ if (!task)
1889
+ throw new Error(`Task not found: ${taskId}`);
1890
+ const metadata = JSON.parse(task.metadata || "{}");
1891
+ metadata._review_score = score;
1892
+ if (reviewerId)
1893
+ metadata._reviewed_by = reviewerId;
1894
+ metadata._reviewed_at = now();
1895
+ d.run("UPDATE tasks SET metadata = ?, updated_at = ? WHERE id = ?", [JSON.stringify(metadata), now(), taskId]);
1896
+ }
1897
+ var init_agent_metrics = __esm(() => {
1898
+ init_database();
1899
+ });
1900
+
1198
1901
  // src/mcp/index.ts
1199
1902
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
1200
1903
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -5432,6 +6135,23 @@ function appendSyncConflict(metadata, conflict, limit = 5) {
5432
6135
  }
5433
6136
 
5434
6137
  // src/lib/config.ts
6138
+ var DEFAULT_AGENT_POOL = [
6139
+ "maximus",
6140
+ "cassius",
6141
+ "aurelius",
6142
+ "brutus",
6143
+ "titus",
6144
+ "nero",
6145
+ "cicero",
6146
+ "seneca",
6147
+ "cato",
6148
+ "julius",
6149
+ "marcus",
6150
+ "lucius",
6151
+ "quintus",
6152
+ "gaius",
6153
+ "publius"
6154
+ ];
5435
6155
  function getConfigPath() {
5436
6156
  return join3(process.env["HOME"] || HOME, ".todos", "config.json");
5437
6157
  }
@@ -5481,6 +6201,23 @@ var GUARD_DEFAULTS = {
5481
6201
  window_minutes: 10,
5482
6202
  cooldown_seconds: 60
5483
6203
  };
6204
+ function getAgentPoolForProject(workingDir) {
6205
+ const config = loadConfig();
6206
+ if (workingDir && config.project_pools) {
6207
+ let bestKey = null;
6208
+ let bestLen = 0;
6209
+ for (const key of Object.keys(config.project_pools)) {
6210
+ if (workingDir.startsWith(key) && key.length > bestLen) {
6211
+ bestKey = key;
6212
+ bestLen = key.length;
6213
+ }
6214
+ }
6215
+ if (bestKey && config.project_pools[bestKey]) {
6216
+ return config.project_pools[bestKey];
6217
+ }
6218
+ }
6219
+ return config.agent_pool || DEFAULT_AGENT_POOL;
6220
+ }
5484
6221
  function getCompletionGuardConfig(projectPath) {
5485
6222
  const config = loadConfig();
5486
6223
  const global = { ...GUARD_DEFAULTS, ...config.completion_guard };
@@ -8491,17 +9228,22 @@ if (shouldRegisterTool("unfocus")) {
8491
9228
  });
8492
9229
  }
8493
9230
  if (shouldRegisterTool("register_agent")) {
8494
- server.tool("register_agent", "Register an agent. Pass session_id (unique per coding session) to prevent name conflicts. Returns conflict error if name is taken by an active agent in a different session.", {
8495
- name: exports_external.string(),
9231
+ 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.", {
9232
+ 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."),
8496
9233
  description: exports_external.string().optional(),
9234
+ capabilities: exports_external.array(exports_external.string()).optional().describe("Agent capabilities/skills for task routing (e.g. ['typescript', 'testing', 'devops'])"),
8497
9235
  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."),
8498
- working_dir: exports_external.string().optional().describe("Working directory of this session \u2014 helps identify who holds the name in a conflict")
8499
- }, async ({ name, description, session_id, working_dir }) => {
9236
+ 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")
9237
+ }, async ({ name, description, capabilities, session_id, working_dir }) => {
8500
9238
  try {
8501
- const result = registerAgent({ name, description, session_id, working_dir });
9239
+ const pool = getAgentPoolForProject(working_dir);
9240
+ const result = registerAgent({ name, description, capabilities, session_id, working_dir, pool });
8502
9241
  if (isAgentConflict(result)) {
9242
+ const suggestLine = result.suggestions && result.suggestions.length > 0 ? `
9243
+ Available names: ${result.suggestions.join(", ")}` : "";
9244
+ const hint = result.pool_violation ? `POOL_VIOLATION: ${result.message}${suggestLine}` : `CONFLICT: ${result.message}${suggestLine}`;
8503
9245
  return {
8504
- content: [{ type: "text", text: `CONFLICT: ${result.message}` }],
9246
+ content: [{ type: "text", text: hint }],
8505
9247
  isError: true
8506
9248
  };
8507
9249
  }
@@ -8514,6 +9256,7 @@ ID: ${agent.id}
8514
9256
  Name: ${agent.name}${agent.description ? `
8515
9257
  Description: ${agent.description}` : ""}
8516
9258
  Session: ${agent.session_id ?? "unbound"}
9259
+ Pool: [${pool.join(", ")}]
8517
9260
  Created: ${agent.created_at}
8518
9261
  Last seen: ${agent.last_seen_at}`
8519
9262
  }]
@@ -8523,6 +9266,30 @@ Last seen: ${agent.last_seen_at}`
8523
9266
  }
8524
9267
  });
8525
9268
  }
9269
+ if (shouldRegisterTool("suggest_agent_name")) {
9270
+ server.tool("suggest_agent_name", "Get available agent names for a project. Call this before register_agent to avoid conflicts.", {
9271
+ working_dir: exports_external.string().optional().describe("Your working directory \u2014 used to look up the project's allowed name pool")
9272
+ }, async ({ working_dir }) => {
9273
+ try {
9274
+ const pool = getAgentPoolForProject(working_dir);
9275
+ const available = getAvailableNamesFromPool(pool, getDatabase());
9276
+ const cutoff = new Date(Date.now() - 30 * 60 * 1000).toISOString();
9277
+ const active = listAgents().filter((a) => a.last_seen_at > cutoff && pool.map((n) => n.toLowerCase()).includes(a.name));
9278
+ const lines = [
9279
+ `Project pool: ${pool.join(", ")}`,
9280
+ `Available now (${available.length}): ${available.length > 0 ? available.join(", ") : "none \u2014 all names in use"}`,
9281
+ 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",
9282
+ available.length > 0 ? `
9283
+ Suggested: ${available[0]}` : `
9284
+ No names available yet. Wait for an active agent to go stale (30min timeout).`
9285
+ ];
9286
+ return { content: [{ type: "text", text: lines.join(`
9287
+ `) }] };
9288
+ } catch (e) {
9289
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
9290
+ }
9291
+ });
9292
+ }
8526
9293
  if (shouldRegisterTool("list_agents")) {
8527
9294
  server.tool("list_agents", "List all registered agents", {}, async () => {
8528
9295
  try {
@@ -9715,6 +10482,7 @@ if (shouldRegisterTool("search_tools")) {
9715
10482
  "update_plan",
9716
10483
  "delete_plan",
9717
10484
  "register_agent",
10485
+ "suggest_agent_name",
9718
10486
  "list_agents",
9719
10487
  "get_agent",
9720
10488
  "rename_agent",
@@ -9856,9 +10624,12 @@ if (shouldRegisterTool("describe_tools")) {
9856
10624
  delete_plan: `Delete a plan. Tasks in the plan are orphaned, not deleted.
9857
10625
  Params: id(string, req)
9858
10626
  Example: {id: 'a1b2c3d4'}`,
9859
- register_agent: `Register an agent. ALWAYS pass session_id (unique per session) to prevent name conflicts. Returns CONFLICT error if name is active in another session \u2014 pick a different name or reclaim with matching session_id.
9860
- Params: name(string, req), description(string), session_id(string \u2014 unique per session, e.g. PID+timestamp), working_dir(string)
9861
- Example: {name: 'maximus', session_id: 'abc123-1741952000', working_dir: '/workspace/platform'}`,
10627
+ suggest_agent_name: `Get available agent names for your project before registering. Shows the pool, which names are active, and the best suggestion.
10628
+ Params: working_dir(string \u2014 your working directory, used to look up project pool)
10629
+ Example: {working_dir: '/workspace/platform'}`,
10630
+ 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.
10631
+ 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)
10632
+ Example: {name: 'cassius', session_id: 'abc123-1741952000', working_dir: '/workspace/platform'}`,
9862
10633
  list_agents: "List all registered agents with IDs, names, and last seen timestamps. No params.",
9863
10634
  get_agent: `Get agent details by ID or name. Provide one of id or name.
9864
10635
  Params: id(string), name(string)
@@ -10116,6 +10887,328 @@ if (shouldRegisterTool("get_latest_handoff")) {
10116
10887
  }
10117
10888
  });
10118
10889
  }
10890
+ if (shouldRegisterTool("add_task_relationship")) {
10891
+ server.tool("add_task_relationship", "Create a semantic relationship between two tasks (related_to, conflicts_with, similar_to, duplicates, supersedes, modifies_same_file).", {
10892
+ source_task_id: exports_external.string().describe("Source task ID"),
10893
+ target_task_id: exports_external.string().describe("Target task ID"),
10894
+ relationship_type: exports_external.enum(["related_to", "conflicts_with", "similar_to", "duplicates", "supersedes", "modifies_same_file"]).describe("Type of relationship"),
10895
+ created_by: exports_external.string().optional().describe("Agent ID who created this relationship")
10896
+ }, async ({ source_task_id, target_task_id, relationship_type, created_by }) => {
10897
+ try {
10898
+ const { addTaskRelationship: addTaskRelationship2 } = (init_task_relationships(), __toCommonJS(exports_task_relationships));
10899
+ const rel = addTaskRelationship2({
10900
+ source_task_id: resolveId(source_task_id),
10901
+ target_task_id: resolveId(target_task_id),
10902
+ relationship_type,
10903
+ created_by
10904
+ });
10905
+ return { content: [{ type: "text", text: `Relationship created: ${rel.source_task_id.slice(0, 8)} --[${rel.relationship_type}]--> ${rel.target_task_id.slice(0, 8)}` }] };
10906
+ } catch (e) {
10907
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
10908
+ }
10909
+ });
10910
+ }
10911
+ if (shouldRegisterTool("remove_task_relationship")) {
10912
+ server.tool("remove_task_relationship", "Remove a semantic relationship between tasks by ID or by source+target+type.", {
10913
+ id: exports_external.string().optional().describe("Relationship ID to remove"),
10914
+ source_task_id: exports_external.string().optional().describe("Source task ID (use with target_task_id + type)"),
10915
+ target_task_id: exports_external.string().optional().describe("Target task ID"),
10916
+ relationship_type: exports_external.enum(["related_to", "conflicts_with", "similar_to", "duplicates", "supersedes", "modifies_same_file"]).optional()
10917
+ }, async ({ id, source_task_id, target_task_id, relationship_type }) => {
10918
+ try {
10919
+ const { removeTaskRelationship: removeTaskRelationship2, removeTaskRelationshipByPair: removeTaskRelationshipByPair2 } = (init_task_relationships(), __toCommonJS(exports_task_relationships));
10920
+ let removed = false;
10921
+ if (id) {
10922
+ removed = removeTaskRelationship2(id);
10923
+ } else if (source_task_id && target_task_id && relationship_type) {
10924
+ removed = removeTaskRelationshipByPair2(resolveId(source_task_id), resolveId(target_task_id), relationship_type);
10925
+ } else {
10926
+ return { content: [{ type: "text", text: "Provide either 'id' or 'source_task_id + target_task_id + relationship_type'" }], isError: true };
10927
+ }
10928
+ return { content: [{ type: "text", text: removed ? "Relationship removed." : "Relationship not found." }] };
10929
+ } catch (e) {
10930
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
10931
+ }
10932
+ });
10933
+ }
10934
+ if (shouldRegisterTool("get_task_relationships")) {
10935
+ server.tool("get_task_relationships", "Get all semantic relationships for a task.", {
10936
+ task_id: exports_external.string().describe("Task ID"),
10937
+ relationship_type: exports_external.enum(["related_to", "conflicts_with", "similar_to", "duplicates", "supersedes", "modifies_same_file"]).optional()
10938
+ }, async ({ task_id, relationship_type }) => {
10939
+ try {
10940
+ const { getTaskRelationships: getTaskRelationships2 } = (init_task_relationships(), __toCommonJS(exports_task_relationships));
10941
+ const rels = getTaskRelationships2(resolveId(task_id), relationship_type);
10942
+ if (rels.length === 0)
10943
+ return { content: [{ type: "text", text: "No relationships found." }] };
10944
+ 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)})` : ""}`);
10945
+ return { content: [{ type: "text", text: lines.join(`
10946
+ `) }] };
10947
+ } catch (e) {
10948
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
10949
+ }
10950
+ });
10951
+ }
10952
+ if (shouldRegisterTool("detect_file_relationships")) {
10953
+ server.tool("detect_file_relationships", "Auto-detect tasks that modify the same files and create modifies_same_file relationships.", {
10954
+ task_id: exports_external.string().describe("Task ID to detect file relationships for")
10955
+ }, async ({ task_id }) => {
10956
+ try {
10957
+ const { autoDetectFileRelationships: autoDetectFileRelationships2 } = (init_task_relationships(), __toCommonJS(exports_task_relationships));
10958
+ const created = autoDetectFileRelationships2(resolveId(task_id));
10959
+ return { content: [{ type: "text", text: created.length > 0 ? `Created ${created.length} file relationship(s).` : "No file overlaps detected." }] };
10960
+ } catch (e) {
10961
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
10962
+ }
10963
+ });
10964
+ }
10965
+ if (shouldRegisterTool("sync_kg")) {
10966
+ server.tool("sync_kg", "Sync all existing relationships into the knowledge graph edges table. Idempotent.", {}, async () => {
10967
+ try {
10968
+ const { syncKgEdges: syncKgEdges2 } = (init_kg(), __toCommonJS(exports_kg));
10969
+ const result = syncKgEdges2();
10970
+ return { content: [{ type: "text", text: `Knowledge graph synced: ${result.synced} edge(s) processed.` }] };
10971
+ } catch (e) {
10972
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
10973
+ }
10974
+ });
10975
+ }
10976
+ if (shouldRegisterTool("get_related_entities")) {
10977
+ server.tool("get_related_entities", "Get entities related to a given entity in the knowledge graph.", {
10978
+ entity_id: exports_external.string().describe("Entity ID (task, agent, project, file path)"),
10979
+ relation_type: exports_external.string().optional().describe("Filter by relation type (depends_on, assigned_to, reports_to, references_file, in_project, in_plan, etc.)"),
10980
+ entity_type: exports_external.string().optional().describe("Filter by entity type (task, agent, project, file, plan)"),
10981
+ direction: exports_external.enum(["outgoing", "incoming", "both"]).optional().describe("Edge direction"),
10982
+ limit: exports_external.number().optional().describe("Max results")
10983
+ }, async ({ entity_id, relation_type, entity_type, direction, limit }) => {
10984
+ try {
10985
+ const { getRelated: getRelated2 } = (init_kg(), __toCommonJS(exports_kg));
10986
+ const edges = getRelated2(entity_id, { relation_type, entity_type, direction, limit });
10987
+ if (edges.length === 0)
10988
+ return { content: [{ type: "text", text: "No related entities found." }] };
10989
+ 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})`);
10990
+ return { content: [{ type: "text", text: lines.join(`
10991
+ `) }] };
10992
+ } catch (e) {
10993
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
10994
+ }
10995
+ });
10996
+ }
10997
+ if (shouldRegisterTool("find_path")) {
10998
+ server.tool("find_path", "Find paths between two entities in the knowledge graph.", {
10999
+ source_id: exports_external.string().describe("Starting entity ID"),
11000
+ target_id: exports_external.string().describe("Target entity ID"),
11001
+ max_depth: exports_external.number().optional().describe("Maximum path depth (default: 5)"),
11002
+ relation_types: exports_external.array(exports_external.string()).optional().describe("Filter by relation types")
11003
+ }, async ({ source_id, target_id, max_depth, relation_types }) => {
11004
+ try {
11005
+ const { findPath: findPath2 } = (init_kg(), __toCommonJS(exports_kg));
11006
+ const paths = findPath2(source_id, target_id, { max_depth, relation_types });
11007
+ if (paths.length === 0)
11008
+ return { content: [{ type: "text", text: "No path found." }] };
11009
+ const lines = paths.map((path, i) => {
11010
+ const steps = path.map((e) => `${e.source_id.slice(0, 8)} --[${e.relation_type}]--> ${e.target_id.slice(0, 8)}`);
11011
+ return `Path ${i + 1} (${path.length} hops):
11012
+ ${steps.join(`
11013
+ `)}`;
11014
+ });
11015
+ return { content: [{ type: "text", text: lines.join(`
11016
+
11017
+ `) }] };
11018
+ } catch (e) {
11019
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
11020
+ }
11021
+ });
11022
+ }
11023
+ if (shouldRegisterTool("get_impact_analysis")) {
11024
+ server.tool("get_impact_analysis", "Analyze what entities are affected if a given entity changes. Traverses the knowledge graph.", {
11025
+ entity_id: exports_external.string().describe("Entity ID to analyze impact for"),
11026
+ max_depth: exports_external.number().optional().describe("Maximum traversal depth (default: 3)"),
11027
+ relation_types: exports_external.array(exports_external.string()).optional().describe("Filter by relation types")
11028
+ }, async ({ entity_id, max_depth, relation_types }) => {
11029
+ try {
11030
+ const { getImpactAnalysis: getImpactAnalysis2 } = (init_kg(), __toCommonJS(exports_kg));
11031
+ const impact = getImpactAnalysis2(entity_id, { max_depth, relation_types });
11032
+ if (impact.length === 0)
11033
+ return { content: [{ type: "text", text: "No downstream impact detected." }] };
11034
+ const byDepth = new Map;
11035
+ for (const i of impact) {
11036
+ if (!byDepth.has(i.depth))
11037
+ byDepth.set(i.depth, []);
11038
+ byDepth.get(i.depth).push(i);
11039
+ }
11040
+ const lines = [`Impact analysis: ${impact.length} affected entities`];
11041
+ for (const [depth, entities] of [...byDepth.entries()].sort((a, b) => a[0] - b[0])) {
11042
+ lines.push(`
11043
+ Depth ${depth}:`);
11044
+ for (const e of entities) {
11045
+ lines.push(` ${e.entity_id.slice(0, 12)} (${e.entity_type}) via ${e.relation}`);
11046
+ }
11047
+ }
11048
+ return { content: [{ type: "text", text: lines.join(`
11049
+ `) }] };
11050
+ } catch (e) {
11051
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
11052
+ }
11053
+ });
11054
+ }
11055
+ if (shouldRegisterTool("get_critical_path")) {
11056
+ server.tool("get_critical_path", "Find tasks that block the most downstream work (critical path analysis).", {
11057
+ project_id: exports_external.string().optional().describe("Filter by project"),
11058
+ limit: exports_external.number().optional().describe("Max results (default: 20)")
11059
+ }, async ({ project_id, limit }) => {
11060
+ try {
11061
+ const { getCriticalPath: getCriticalPath2 } = (init_kg(), __toCommonJS(exports_kg));
11062
+ const result = getCriticalPath2({ project_id: project_id ? resolveId(project_id, "projects") : undefined, limit });
11063
+ if (result.length === 0)
11064
+ return { content: [{ type: "text", text: "No critical path data. Run sync_kg first to populate the knowledge graph." }] };
11065
+ const lines = result.map((r, i) => `${i + 1}. ${r.task_id.slice(0, 8)} blocks ${r.blocking_count} task(s), max depth ${r.depth}`);
11066
+ return { content: [{ type: "text", text: `Critical path:
11067
+ ${lines.join(`
11068
+ `)}` }] };
11069
+ } catch (e) {
11070
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
11071
+ }
11072
+ });
11073
+ }
11074
+ if (shouldRegisterTool("get_capable_agents")) {
11075
+ server.tool("get_capable_agents", "Find agents that match given capabilities, sorted by match score.", {
11076
+ capabilities: exports_external.array(exports_external.string()).describe("Required capabilities to match against"),
11077
+ min_score: exports_external.number().optional().describe("Minimum match score 0.0-1.0 (default: 0.1)"),
11078
+ limit: exports_external.number().optional().describe("Max results")
11079
+ }, async ({ capabilities, min_score, limit }) => {
11080
+ try {
11081
+ const { getCapableAgents: getCapableAgents2 } = (init_agents(), __toCommonJS(exports_agents));
11082
+ const results = getCapableAgents2(capabilities, { min_score, limit });
11083
+ if (results.length === 0)
11084
+ return { content: [{ type: "text", text: "No agents match the given capabilities." }] };
11085
+ const lines = results.map((r) => `${r.agent.name} (${r.agent.id}) score:${(r.score * 100).toFixed(0)}% caps:[${r.agent.capabilities.join(",")}]`);
11086
+ return { content: [{ type: "text", text: lines.join(`
11087
+ `) }] };
11088
+ } catch (e) {
11089
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
11090
+ }
11091
+ });
11092
+ }
11093
+ if (shouldRegisterTool("patrol_tasks")) {
11094
+ server.tool("patrol_tasks", "Scan for task issues: stuck tasks, low-confidence completions, orphaned tasks, zombie-blocked tasks, and pending reviews.", {
11095
+ stuck_minutes: exports_external.number().optional().describe("Minutes threshold for stuck detection (default: 60)"),
11096
+ confidence_threshold: exports_external.number().optional().describe("Confidence threshold for low-confidence detection (default: 0.5)"),
11097
+ project_id: exports_external.string().optional().describe("Filter by project")
11098
+ }, async ({ stuck_minutes, confidence_threshold, project_id }) => {
11099
+ try {
11100
+ const { patrolTasks: patrolTasks2 } = (init_patrol(), __toCommonJS(exports_patrol));
11101
+ const result = patrolTasks2({
11102
+ stuck_minutes,
11103
+ confidence_threshold,
11104
+ project_id: project_id ? resolveId(project_id, "projects") : undefined
11105
+ });
11106
+ if (result.total_issues === 0)
11107
+ return { content: [{ type: "text", text: "All clear \u2014 no issues detected." }] };
11108
+ const lines = [`Found ${result.total_issues} issue(s):
11109
+ `];
11110
+ for (const issue of result.issues) {
11111
+ lines.push(`[${issue.severity.toUpperCase()}] ${issue.type}: ${issue.task_title.slice(0, 60)} (${issue.task_id.slice(0, 8)})`);
11112
+ lines.push(` ${issue.detail}`);
11113
+ }
11114
+ return { content: [{ type: "text", text: lines.join(`
11115
+ `) }] };
11116
+ } catch (e) {
11117
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
11118
+ }
11119
+ });
11120
+ }
11121
+ if (shouldRegisterTool("get_review_queue")) {
11122
+ server.tool("get_review_queue", "Get tasks that need review: requires_approval but unapproved, or low confidence completions.", {
11123
+ project_id: exports_external.string().optional().describe("Filter by project"),
11124
+ limit: exports_external.number().optional().describe("Max results (default: all)")
11125
+ }, async ({ project_id, limit }) => {
11126
+ try {
11127
+ const { getReviewQueue: getReviewQueue2 } = (init_patrol(), __toCommonJS(exports_patrol));
11128
+ const tasks = getReviewQueue2({
11129
+ project_id: project_id ? resolveId(project_id, "projects") : undefined,
11130
+ limit
11131
+ });
11132
+ if (tasks.length === 0)
11133
+ return { content: [{ type: "text", text: "Review queue is empty." }] };
11134
+ const lines = tasks.map((t) => {
11135
+ const conf = t.confidence != null ? ` confidence:${t.confidence}` : "";
11136
+ const approval = t.requires_approval && !t.approved_by ? " [needs approval]" : "";
11137
+ return `${t.short_id || t.id.slice(0, 8)} ${t.title.slice(0, 60)}${conf}${approval}`;
11138
+ });
11139
+ return { content: [{ type: "text", text: `Review queue (${tasks.length}):
11140
+ ${lines.join(`
11141
+ `)}` }] };
11142
+ } catch (e) {
11143
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
11144
+ }
11145
+ });
11146
+ }
11147
+ if (shouldRegisterTool("score_task")) {
11148
+ server.tool("score_task", "Score a completed task's quality (0.0-1.0). Stores in task metadata for agent performance tracking.", {
11149
+ task_id: exports_external.string().describe("Task ID to score"),
11150
+ score: exports_external.number().min(0).max(1).describe("Quality score 0.0-1.0"),
11151
+ reviewer_id: exports_external.string().optional().describe("Agent ID of reviewer")
11152
+ }, async ({ task_id, score, reviewer_id }) => {
11153
+ try {
11154
+ const { scoreTask: scoreTask2 } = (init_agent_metrics(), __toCommonJS(exports_agent_metrics));
11155
+ scoreTask2(resolveId(task_id), score, reviewer_id);
11156
+ return { content: [{ type: "text", text: `Task ${task_id.slice(0, 8)} scored: ${score}` }] };
11157
+ } catch (e) {
11158
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
11159
+ }
11160
+ });
11161
+ }
11162
+ if (shouldRegisterTool("get_agent_metrics")) {
11163
+ server.tool("get_agent_metrics", "Get performance metrics for an agent: completion rate, speed, confidence, review scores.", {
11164
+ agent_id: exports_external.string().describe("Agent ID or name"),
11165
+ project_id: exports_external.string().optional().describe("Filter by project")
11166
+ }, async ({ agent_id, project_id }) => {
11167
+ try {
11168
+ const { getAgentMetrics: getAgentMetrics2 } = (init_agent_metrics(), __toCommonJS(exports_agent_metrics));
11169
+ const metrics = getAgentMetrics2(agent_id, {
11170
+ project_id: project_id ? resolveId(project_id, "projects") : undefined
11171
+ });
11172
+ if (!metrics)
11173
+ return { content: [{ type: "text", text: `Agent not found: ${agent_id}` }], isError: true };
11174
+ const lines = [
11175
+ `Agent: ${metrics.agent_name} (${metrics.agent_id})`,
11176
+ `Completed: ${metrics.tasks_completed} | Failed: ${metrics.tasks_failed} | In Progress: ${metrics.tasks_in_progress}`,
11177
+ `Completion Rate: ${(metrics.completion_rate * 100).toFixed(1)}%`,
11178
+ metrics.avg_completion_minutes != null ? `Avg Completion Time: ${metrics.avg_completion_minutes} min` : null,
11179
+ metrics.avg_confidence != null ? `Avg Confidence: ${(metrics.avg_confidence * 100).toFixed(1)}%` : null,
11180
+ metrics.review_score_avg != null ? `Avg Review Score: ${(metrics.review_score_avg * 100).toFixed(1)}%` : null,
11181
+ `Composite Score: ${(metrics.composite_score * 100).toFixed(1)}%`
11182
+ ].filter(Boolean);
11183
+ return { content: [{ type: "text", text: lines.join(`
11184
+ `) }] };
11185
+ } catch (e) {
11186
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
11187
+ }
11188
+ });
11189
+ }
11190
+ if (shouldRegisterTool("get_leaderboard")) {
11191
+ server.tool("get_leaderboard", "Get agent leaderboard ranked by composite performance score.", {
11192
+ project_id: exports_external.string().optional().describe("Filter by project"),
11193
+ limit: exports_external.number().optional().describe("Max entries (default: 20)")
11194
+ }, async ({ project_id, limit }) => {
11195
+ try {
11196
+ const { getLeaderboard: getLeaderboard2 } = (init_agent_metrics(), __toCommonJS(exports_agent_metrics));
11197
+ const entries = getLeaderboard2({
11198
+ project_id: project_id ? resolveId(project_id, "projects") : undefined,
11199
+ limit
11200
+ });
11201
+ if (entries.length === 0)
11202
+ return { content: [{ type: "text", text: "No agents with task activity found." }] };
11203
+ 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)}%`);
11204
+ return { content: [{ type: "text", text: `Leaderboard:
11205
+ ${lines.join(`
11206
+ `)}` }] };
11207
+ } catch (e) {
11208
+ return { content: [{ type: "text", text: formatError(e) }], isError: true };
11209
+ }
11210
+ });
11211
+ }
10119
11212
  server.resource("task-lists", "todos://task-lists", { description: "All task lists", mimeType: "application/json" }, async () => {
10120
11213
  const lists = listTaskLists();
10121
11214
  return { contents: [{ uri: "todos://task-lists", text: JSON.stringify(lists, null, 2), mimeType: "application/json" }] };