@askexenow/exe-os 0.8.41 → 0.8.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/bin/backfill-conversations.js +805 -642
  2. package/dist/bin/backfill-responses.js +804 -641
  3. package/dist/bin/backfill-vectors.js +791 -634
  4. package/dist/bin/cleanup-stale-review-tasks.js +788 -631
  5. package/dist/bin/cli.js +1345 -660
  6. package/dist/bin/exe-agent.js +20 -1
  7. package/dist/bin/exe-assign.js +1503 -1343
  8. package/dist/bin/exe-boot.js +2518 -1798
  9. package/dist/bin/exe-call.js +39 -1
  10. package/dist/bin/exe-cloud.js +15 -1
  11. package/dist/bin/exe-dispatch.js +39 -2
  12. package/dist/bin/exe-doctor.js +790 -633
  13. package/dist/bin/exe-export-behaviors.js +792 -637
  14. package/dist/bin/exe-forget.js +145 -0
  15. package/dist/bin/exe-gateway.js +2500 -1877
  16. package/dist/bin/exe-heartbeat.js +147 -1
  17. package/dist/bin/exe-kill.js +795 -640
  18. package/dist/bin/exe-launch-agent.js +2168 -2008
  19. package/dist/bin/exe-link.js +28 -2
  20. package/dist/bin/exe-new-employee.js +25 -3
  21. package/dist/bin/exe-pending-messages.js +146 -1
  22. package/dist/bin/exe-pending-notifications.js +788 -631
  23. package/dist/bin/exe-pending-reviews.js +147 -1
  24. package/dist/bin/exe-rename.js +23 -0
  25. package/dist/bin/exe-review.js +490 -327
  26. package/dist/bin/exe-search.js +154 -3
  27. package/dist/bin/exe-session-cleanup.js +2466 -413
  28. package/dist/bin/exe-status.js +474 -317
  29. package/dist/bin/exe-team.js +474 -317
  30. package/dist/bin/git-sweep.js +2690 -150
  31. package/dist/bin/graph-backfill.js +794 -637
  32. package/dist/bin/graph-export.js +798 -641
  33. package/dist/bin/scan-tasks.js +2951 -44
  34. package/dist/bin/setup.js +62 -26
  35. package/dist/bin/shard-migrate.js +792 -637
  36. package/dist/bin/wiki-sync.js +794 -637
  37. package/dist/gateway/index.js +2504 -1895
  38. package/dist/hooks/bug-report-worker.js +2118 -576
  39. package/dist/hooks/commit-complete.js +2689 -149
  40. package/dist/hooks/error-recall.js +154 -3
  41. package/dist/hooks/ingest-worker.js +1439 -815
  42. package/dist/hooks/instructions-loaded.js +151 -0
  43. package/dist/hooks/notification.js +153 -2
  44. package/dist/hooks/post-compact.js +164 -0
  45. package/dist/hooks/pre-compact.js +3073 -101
  46. package/dist/hooks/pre-tool-use.js +151 -0
  47. package/dist/hooks/prompt-ingest-worker.js +1714 -1537
  48. package/dist/hooks/prompt-submit.js +2658 -1113
  49. package/dist/hooks/response-ingest-worker.js +170 -6
  50. package/dist/hooks/session-end.js +153 -2
  51. package/dist/hooks/session-start.js +154 -3
  52. package/dist/hooks/stop.js +151 -0
  53. package/dist/hooks/subagent-stop.js +151 -0
  54. package/dist/hooks/summary-worker.js +179 -7
  55. package/dist/index.js +278 -100
  56. package/dist/lib/cloud-sync.js +28 -2
  57. package/dist/lib/consolidation.js +69 -2
  58. package/dist/lib/database.js +19 -0
  59. package/dist/lib/device-registry.js +19 -0
  60. package/dist/lib/employee-templates.js +20 -1
  61. package/dist/lib/exe-daemon.js +236 -16
  62. package/dist/lib/hybrid-search.js +154 -3
  63. package/dist/lib/license.js +15 -1
  64. package/dist/lib/messaging.js +39 -2
  65. package/dist/lib/schedules.js +792 -637
  66. package/dist/lib/store.js +796 -636
  67. package/dist/lib/tasks.js +1614 -1091
  68. package/dist/lib/tmux-routing.js +149 -9
  69. package/dist/mcp/server.js +1825 -1138
  70. package/dist/mcp/tools/create-task.js +2280 -828
  71. package/dist/mcp/tools/list-tasks.js +2788 -159
  72. package/dist/mcp/tools/send-message.js +39 -2
  73. package/dist/mcp/tools/update-task.js +64 -0
  74. package/dist/runtime/index.js +235 -67
  75. package/dist/tui/App.js +1452 -644
  76. package/package.json +3 -2
@@ -312,6 +312,13 @@ async function ensureSchema() {
312
312
  });
313
313
  } catch {
314
314
  }
315
+ try {
316
+ await client.execute({
317
+ sql: `ALTER TABLE tasks ADD COLUMN session_scope TEXT`,
318
+ args: []
319
+ });
320
+ } catch {
321
+ }
315
322
  try {
316
323
  await client.execute({
317
324
  sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
@@ -758,6 +765,18 @@ async function ensureSchema() {
758
765
  CREATE INDEX IF NOT EXISTS idx_session_kills_agent
759
766
  ON session_kills(agent_id);
760
767
  `);
768
+ await client.execute(`
769
+ CREATE TABLE IF NOT EXISTS global_procedures (
770
+ id TEXT PRIMARY KEY,
771
+ title TEXT NOT NULL,
772
+ content TEXT NOT NULL,
773
+ priority TEXT NOT NULL DEFAULT 'p0',
774
+ domain TEXT,
775
+ active INTEGER NOT NULL DEFAULT 1,
776
+ created_at TEXT NOT NULL,
777
+ updated_at TEXT NOT NULL
778
+ )
779
+ `);
761
780
  await client.executeMultiple(`
762
781
  CREATE TABLE IF NOT EXISTS conversations (
763
782
  id TEXT PRIMARY KEY,
@@ -1096,6 +1115,61 @@ var init_config = __esm({
1096
1115
  }
1097
1116
  });
1098
1117
 
1118
+ // src/lib/state-bus.ts
1119
+ var StateBus, orgBus;
1120
+ var init_state_bus = __esm({
1121
+ "src/lib/state-bus.ts"() {
1122
+ "use strict";
1123
+ StateBus = class {
1124
+ handlers = /* @__PURE__ */ new Map();
1125
+ globalHandlers = /* @__PURE__ */ new Set();
1126
+ /** Emit an event to all subscribers */
1127
+ emit(event) {
1128
+ const typeHandlers = this.handlers.get(event.type);
1129
+ if (typeHandlers) {
1130
+ for (const handler of typeHandlers) {
1131
+ try {
1132
+ handler(event);
1133
+ } catch {
1134
+ }
1135
+ }
1136
+ }
1137
+ for (const handler of this.globalHandlers) {
1138
+ try {
1139
+ handler(event);
1140
+ } catch {
1141
+ }
1142
+ }
1143
+ }
1144
+ /** Subscribe to a specific event type */
1145
+ on(type, handler) {
1146
+ if (!this.handlers.has(type)) {
1147
+ this.handlers.set(type, /* @__PURE__ */ new Set());
1148
+ }
1149
+ this.handlers.get(type).add(handler);
1150
+ }
1151
+ /** Subscribe to ALL events */
1152
+ onAny(handler) {
1153
+ this.globalHandlers.add(handler);
1154
+ }
1155
+ /** Unsubscribe from a specific event type */
1156
+ off(type, handler) {
1157
+ this.handlers.get(type)?.delete(handler);
1158
+ }
1159
+ /** Unsubscribe from ALL events */
1160
+ offAny(handler) {
1161
+ this.globalHandlers.delete(handler);
1162
+ }
1163
+ /** Remove all listeners */
1164
+ clear() {
1165
+ this.handlers.clear();
1166
+ this.globalHandlers.clear();
1167
+ }
1168
+ };
1169
+ orgBus = new StateBus();
1170
+ }
1171
+ });
1172
+
1099
1173
  // src/lib/shard-manager.ts
1100
1174
  var shard_manager_exports = {};
1101
1175
  __export(shard_manager_exports, {
@@ -1337,6 +1411,71 @@ var init_shard_manager = __esm({
1337
1411
  }
1338
1412
  });
1339
1413
 
1414
+ // src/lib/global-procedures.ts
1415
+ var global_procedures_exports = {};
1416
+ __export(global_procedures_exports, {
1417
+ deactivateGlobalProcedure: () => deactivateGlobalProcedure,
1418
+ getGlobalProceduresBlock: () => getGlobalProceduresBlock,
1419
+ loadGlobalProcedures: () => loadGlobalProcedures,
1420
+ storeGlobalProcedure: () => storeGlobalProcedure
1421
+ });
1422
+ import { randomUUID } from "crypto";
1423
+ async function loadGlobalProcedures() {
1424
+ const client = getClient();
1425
+ const result = await client.execute({
1426
+ sql: "SELECT * FROM global_procedures WHERE active = 1 ORDER BY priority ASC, created_at ASC",
1427
+ args: []
1428
+ });
1429
+ const procedures = result.rows;
1430
+ if (procedures.length > 0) {
1431
+ _cache = procedures.map((p) => `### ${p.title}
1432
+ ${p.content}`).join("\n\n");
1433
+ } else {
1434
+ _cache = "";
1435
+ }
1436
+ _cacheLoaded = true;
1437
+ return procedures;
1438
+ }
1439
+ function getGlobalProceduresBlock() {
1440
+ if (!_cacheLoaded) return "";
1441
+ if (!_cache) return "";
1442
+ return `## Organization-Wide Procedures (MANDATORY \u2014 supersedes all other rules)
1443
+
1444
+ ${_cache}
1445
+ `;
1446
+ }
1447
+ async function storeGlobalProcedure(input) {
1448
+ const id = randomUUID();
1449
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1450
+ const client = getClient();
1451
+ await client.execute({
1452
+ sql: `INSERT INTO global_procedures (id, title, content, priority, domain, active, created_at, updated_at)
1453
+ VALUES (?, ?, ?, ?, ?, 1, ?, ?)`,
1454
+ args: [id, input.title, input.content, input.priority ?? "p0", input.domain ?? null, now, now]
1455
+ });
1456
+ await loadGlobalProcedures();
1457
+ return id;
1458
+ }
1459
+ async function deactivateGlobalProcedure(id) {
1460
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1461
+ const client = getClient();
1462
+ const result = await client.execute({
1463
+ sql: "UPDATE global_procedures SET active = 0, updated_at = ? WHERE id = ?",
1464
+ args: [now, id]
1465
+ });
1466
+ await loadGlobalProcedures();
1467
+ return result.rowsAffected > 0;
1468
+ }
1469
+ var _cache, _cacheLoaded;
1470
+ var init_global_procedures = __esm({
1471
+ "src/lib/global-procedures.ts"() {
1472
+ "use strict";
1473
+ init_database();
1474
+ _cache = "";
1475
+ _cacheLoaded = false;
1476
+ }
1477
+ });
1478
+
1340
1479
  // src/lib/notifications.ts
1341
1480
  import crypto2 from "crypto";
1342
1481
  import path4 from "path";
@@ -1348,6 +1487,40 @@ import {
1348
1487
  existsSync as existsSync4,
1349
1488
  rmdirSync
1350
1489
  } from "fs";
1490
+ async function writeNotification(notification) {
1491
+ try {
1492
+ const client = getClient();
1493
+ const id = crypto2.randomUUID();
1494
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1495
+ await client.execute({
1496
+ sql: `INSERT INTO notifications (id, agent_id, agent_role, event, project, summary, task_file, read, created_at)
1497
+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)`,
1498
+ args: [
1499
+ id,
1500
+ notification.agentId,
1501
+ notification.agentRole,
1502
+ notification.event,
1503
+ notification.project,
1504
+ notification.summary,
1505
+ notification.taskFile ?? null,
1506
+ now
1507
+ ]
1508
+ });
1509
+ } catch (err) {
1510
+ process.stderr.write(`[notifications] WRITE FAILED: ${err instanceof Error ? err.message : String(err)}
1511
+ `);
1512
+ }
1513
+ }
1514
+ async function markAsReadByTaskFile(taskFile) {
1515
+ try {
1516
+ const client = getClient();
1517
+ await client.execute({
1518
+ sql: "UPDATE notifications SET read = 1 WHERE task_file = ? AND read = 0",
1519
+ args: [taskFile]
1520
+ });
1521
+ } catch {
1522
+ }
1523
+ }
1351
1524
  var init_notifications = __esm({
1352
1525
  "src/lib/notifications.ts"() {
1353
1526
  "use strict";
@@ -1355,414 +1528,66 @@ var init_notifications = __esm({
1355
1528
  }
1356
1529
  });
1357
1530
 
1358
- // src/lib/tasks-crud.ts
1359
- import crypto3 from "crypto";
1531
+ // src/lib/session-registry.ts
1532
+ import { readFileSync as readFileSync3, writeFileSync, mkdirSync as mkdirSync2, existsSync as existsSync5 } from "fs";
1360
1533
  import path5 from "path";
1361
- import { execSync } from "child_process";
1362
- import { mkdir as mkdir3, writeFile as writeFile3, appendFile } from "fs/promises";
1363
- import { existsSync as existsSync5, readFileSync as readFileSync3 } from "fs";
1364
- function extractParentFromContext(contextBody) {
1365
- if (!contextBody) return null;
1366
- const match = contextBody.match(
1367
- /Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
1368
- );
1369
- return match ? match[1].toLowerCase() : null;
1370
- }
1371
- function slugify(title) {
1372
- return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
1373
- }
1374
- async function resolveTask(client, identifier) {
1375
- let result = await client.execute({
1376
- sql: "SELECT * FROM tasks WHERE id = ?",
1377
- args: [identifier]
1378
- });
1379
- if (result.rows.length === 1) return result.rows[0];
1380
- result = await client.execute({
1381
- sql: "SELECT * FROM tasks WHERE task_file LIKE ?",
1382
- args: [`%${identifier}%`]
1383
- });
1384
- if (result.rows.length === 1) return result.rows[0];
1385
- if (result.rows.length > 1) {
1386
- const exact = result.rows.filter(
1387
- (r) => String(r.task_file).endsWith(`/${identifier}.md`)
1388
- );
1389
- if (exact.length === 1) return exact[0];
1390
- const candidates = exact.length > 1 ? exact : result.rows;
1391
- const active = candidates.filter(
1392
- (r) => !["done", "cancelled"].includes(String(r.status))
1393
- );
1394
- if (active.length === 1) return active[0];
1395
- const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
1396
- throw new Error(
1397
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
1398
- );
1534
+ import os4 from "os";
1535
+ function registerSession(entry) {
1536
+ const dir = path5.dirname(REGISTRY_PATH);
1537
+ if (!existsSync5(dir)) {
1538
+ mkdirSync2(dir, { recursive: true });
1399
1539
  }
1400
- result = await client.execute({
1401
- sql: "SELECT * FROM tasks WHERE title LIKE ?",
1402
- args: [`%${identifier}%`]
1403
- });
1404
- if (result.rows.length === 1) return result.rows[0];
1405
- if (result.rows.length > 1) {
1406
- const active = result.rows.filter(
1407
- (r) => !["done", "cancelled"].includes(String(r.status))
1408
- );
1409
- if (active.length === 1) return active[0];
1410
- const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
1411
- throw new Error(
1412
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
1413
- );
1540
+ const sessions = listSessions();
1541
+ const idx = sessions.findIndex((s) => s.windowName === entry.windowName);
1542
+ if (idx >= 0) {
1543
+ sessions[idx] = entry;
1544
+ } else {
1545
+ sessions.push(entry);
1414
1546
  }
1415
- throw new Error(`Task not found: ${identifier}`);
1547
+ writeFileSync(REGISTRY_PATH, JSON.stringify(sessions, null, 2));
1416
1548
  }
1417
- async function createTaskCore(input) {
1418
- const client = getClient();
1419
- const id = crypto3.randomUUID();
1420
- const now = (/* @__PURE__ */ new Date()).toISOString();
1421
- const slug = slugify(input.title);
1422
- const taskFile = input.taskFile ?? `exe/${input.assignedTo}/${slug}.md`;
1423
- let blockedById = null;
1424
- const initialStatus = input.blockedBy ? "blocked" : "open";
1425
- if (input.blockedBy) {
1426
- const blocker = await resolveTask(client, input.blockedBy);
1427
- blockedById = String(blocker.id);
1549
+ function listSessions() {
1550
+ try {
1551
+ const raw = readFileSync3(REGISTRY_PATH, "utf8");
1552
+ return JSON.parse(raw);
1553
+ } catch {
1554
+ return [];
1428
1555
  }
1429
- let parentTaskId = null;
1430
- let parentRef = input.parentTaskId;
1431
- if (!parentRef) {
1432
- const extracted = extractParentFromContext(input.context);
1433
- if (extracted) {
1434
- parentRef = extracted;
1435
- process.stderr.write(
1436
- "[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
1437
- );
1438
- }
1556
+ }
1557
+ var REGISTRY_PATH;
1558
+ var init_session_registry = __esm({
1559
+ "src/lib/session-registry.ts"() {
1560
+ "use strict";
1561
+ REGISTRY_PATH = path5.join(os4.homedir(), ".exe-os", "session-registry.json");
1439
1562
  }
1440
- if (parentRef) {
1563
+ });
1564
+
1565
+ // src/lib/session-key.ts
1566
+ import { execSync } from "child_process";
1567
+ function getSessionKey() {
1568
+ if (_cached) return _cached;
1569
+ let pid = process.ppid;
1570
+ for (let i = 0; i < 10; i++) {
1441
1571
  try {
1442
- const parent = await resolveTask(client, parentRef);
1443
- parentTaskId = String(parent.id);
1444
- } catch (err) {
1445
- if (!input.parentTaskId) {
1446
- throw new Error(
1447
- `create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
1448
- );
1572
+ const info = execSync(`ps -p ${pid} -o ppid=,comm=`, {
1573
+ encoding: "utf8",
1574
+ timeout: 2e3
1575
+ }).trim();
1576
+ const match = info.match(/^\s*(\d+)\s+(.+)$/);
1577
+ if (!match) break;
1578
+ const [, ppid, cmd] = match;
1579
+ if (cmd === "claude" || cmd.endsWith("/claude")) {
1580
+ _cached = String(pid);
1581
+ return _cached;
1449
1582
  }
1450
- throw err;
1451
- }
1452
- }
1453
- let warning;
1454
- const dupCheck = await client.execute({
1455
- sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
1456
- args: [input.title, input.assignedTo]
1457
- });
1458
- if (dupCheck.rows.length > 0) {
1459
- warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
1460
- }
1461
- if (input.baseDir) {
1462
- try {
1463
- await mkdir3(path5.join(input.baseDir, "exe", "output"), { recursive: true });
1464
- await mkdir3(path5.join(input.baseDir, "exe", "research"), { recursive: true });
1465
- await ensureArchitectureDoc(input.baseDir, input.projectName);
1466
- await ensureGitignoreExe(input.baseDir);
1583
+ pid = parseInt(ppid, 10);
1584
+ if (pid <= 1) break;
1467
1585
  } catch {
1586
+ break;
1468
1587
  }
1469
1588
  }
1470
- const complexity = input.complexity ?? "standard";
1471
- await client.execute({
1472
- sql: `INSERT INTO tasks (id, title, assigned_to, assigned_by, project_name, priority, status, task_file, blocked_by, parent_task_id, reviewer, context, complexity, budget_tokens, budget_fallback_model, tokens_used, tokens_warned_at, created_at, updated_at)
1473
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1474
- args: [
1475
- id,
1476
- input.title,
1477
- input.assignedTo,
1478
- input.assignedBy,
1479
- input.projectName,
1480
- input.priority,
1481
- initialStatus,
1482
- taskFile,
1483
- blockedById,
1484
- parentTaskId,
1485
- input.reviewer ?? null,
1486
- input.context,
1487
- complexity,
1488
- input.budgetTokens ?? null,
1489
- input.budgetFallbackModel ?? null,
1490
- 0,
1491
- null,
1492
- now,
1493
- now
1494
- ]
1495
- });
1496
- return {
1497
- id,
1498
- title: input.title,
1499
- assignedTo: input.assignedTo,
1500
- assignedBy: input.assignedBy,
1501
- projectName: input.projectName,
1502
- priority: input.priority,
1503
- status: initialStatus,
1504
- taskFile,
1505
- createdAt: now,
1506
- updatedAt: now,
1507
- warning,
1508
- budgetTokens: input.budgetTokens ?? null,
1509
- budgetFallbackModel: input.budgetFallbackModel ?? null,
1510
- tokensUsed: 0,
1511
- tokensWarnedAt: null
1512
- };
1513
- }
1514
- async function ensureArchitectureDoc(baseDir, projectName) {
1515
- const archPath = path5.join(baseDir, "exe", "ARCHITECTURE.md");
1516
- try {
1517
- if (existsSync5(archPath)) return;
1518
- const template = [
1519
- `# ${projectName} \u2014 System Architecture`,
1520
- "",
1521
- "> Employees: read this before every task. Update it when you change system structure.",
1522
- `> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
1523
- "",
1524
- "## Overview",
1525
- "",
1526
- "<!-- Describe what this system does, its main components, and how they connect. -->",
1527
- "",
1528
- "## Key Components",
1529
- "",
1530
- "<!-- List the major modules, services, or subsystems. -->",
1531
- "",
1532
- "## Data Flow",
1533
- "",
1534
- "<!-- How does data move through the system? What writes where? -->",
1535
- "",
1536
- "## Invariants",
1537
- "",
1538
- "<!-- Rules that must never be violated. What breaks if these are wrong? -->",
1539
- "",
1540
- "## Dependencies",
1541
- "",
1542
- "<!-- What depends on what? If I change X, what else is affected? -->",
1543
- ""
1544
- ].join("\n");
1545
- await writeFile3(archPath, template, "utf-8");
1546
- } catch {
1547
- }
1548
- }
1549
- async function ensureGitignoreExe(baseDir) {
1550
- const gitignorePath = path5.join(baseDir, ".gitignore");
1551
- try {
1552
- if (existsSync5(gitignorePath)) {
1553
- const content = readFileSync3(gitignorePath, "utf-8");
1554
- if (/^\/?exe\/?$/m.test(content)) return;
1555
- await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
1556
- } else {
1557
- await writeFile3(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
1558
- }
1559
- } catch {
1560
- }
1561
- }
1562
- var init_tasks_crud = __esm({
1563
- "src/lib/tasks-crud.ts"() {
1564
- "use strict";
1565
- init_database();
1566
- }
1567
- });
1568
-
1569
- // src/lib/employees.ts
1570
- var employees_exports = {};
1571
- __export(employees_exports, {
1572
- EMPLOYEES_PATH: () => EMPLOYEES_PATH,
1573
- addEmployee: () => addEmployee,
1574
- getEmployee: () => getEmployee,
1575
- getEmployeeByRole: () => getEmployeeByRole,
1576
- getEmployeeNamesByRole: () => getEmployeeNamesByRole,
1577
- hasRole: () => hasRole,
1578
- isMultiInstance: () => isMultiInstance,
1579
- loadEmployees: () => loadEmployees,
1580
- loadEmployeesSync: () => loadEmployeesSync,
1581
- registerBinSymlinks: () => registerBinSymlinks,
1582
- saveEmployees: () => saveEmployees,
1583
- validateEmployeeName: () => validateEmployeeName
1584
- });
1585
- import { readFile as readFile3, writeFile as writeFile4, mkdir as mkdir4 } from "fs/promises";
1586
- import { existsSync as existsSync6, symlinkSync, readlinkSync, readFileSync as readFileSync4 } from "fs";
1587
- import { execSync as execSync2 } from "child_process";
1588
- import path6 from "path";
1589
- function validateEmployeeName(name) {
1590
- if (!name) {
1591
- return { valid: false, error: "Name is required" };
1592
- }
1593
- if (name.length > 32) {
1594
- return { valid: false, error: "Name must be 32 characters or fewer" };
1595
- }
1596
- if (!/^[a-z][a-z0-9]*$/.test(name)) {
1597
- return {
1598
- valid: false,
1599
- error: "Name must start with a letter and contain only lowercase alphanumeric characters"
1600
- };
1601
- }
1602
- return { valid: true };
1603
- }
1604
- async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
1605
- if (!existsSync6(employeesPath)) {
1606
- return [];
1607
- }
1608
- const raw = await readFile3(employeesPath, "utf-8");
1609
- try {
1610
- return JSON.parse(raw);
1611
- } catch {
1612
- return [];
1613
- }
1614
- }
1615
- async function saveEmployees(employees, employeesPath = EMPLOYEES_PATH) {
1616
- await mkdir4(path6.dirname(employeesPath), { recursive: true });
1617
- await writeFile4(employeesPath, JSON.stringify(employees, null, 2) + "\n", "utf-8");
1618
- }
1619
- function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
1620
- if (!existsSync6(employeesPath)) return [];
1621
- try {
1622
- return JSON.parse(readFileSync4(employeesPath, "utf-8"));
1623
- } catch {
1624
- return [];
1625
- }
1626
- }
1627
- function getEmployee(employees, name) {
1628
- return employees.find((e) => e.name.toLowerCase() === name.toLowerCase());
1629
- }
1630
- function getEmployeeByRole(employees, role) {
1631
- const lower = role.toLowerCase();
1632
- return employees.find((e) => e.role.toLowerCase() === lower);
1633
- }
1634
- function getEmployeeNamesByRole(employees, role) {
1635
- const lower = role.toLowerCase();
1636
- return employees.filter((e) => e.role.toLowerCase() === lower).map((e) => e.name);
1637
- }
1638
- function hasRole(agentName, role) {
1639
- const employees = loadEmployeesSync();
1640
- const emp = getEmployee(employees, agentName);
1641
- return emp ? emp.role.toLowerCase() === role.toLowerCase() : false;
1642
- }
1643
- function isMultiInstance(agentName, employees) {
1644
- const roster = employees ?? loadEmployeesSync();
1645
- const emp = getEmployee(roster, agentName);
1646
- if (!emp) return false;
1647
- return MULTI_INSTANCE_ROLES.has(emp.role.toLowerCase());
1648
- }
1649
- function addEmployee(employees, employee) {
1650
- const normalized = { ...employee, name: employee.name.toLowerCase() };
1651
- if (employees.some((e) => e.name.toLowerCase() === normalized.name)) {
1652
- throw new Error(`Employee '${normalized.name}' already exists`);
1653
- }
1654
- return [...employees, normalized];
1655
- }
1656
- function findExeBin() {
1657
- try {
1658
- return execSync2(process.platform === "win32" ? "where exe-os" : "which exe-os", { encoding: "utf8" }).trim();
1659
- } catch {
1660
- return null;
1661
- }
1662
- }
1663
- function registerBinSymlinks(name) {
1664
- const created = [];
1665
- const skipped = [];
1666
- const errors = [];
1667
- const exeBinPath = findExeBin();
1668
- if (!exeBinPath) {
1669
- errors.push("Could not find 'exe-os' in PATH");
1670
- return { created, skipped, errors };
1671
- }
1672
- const binDir = path6.dirname(exeBinPath);
1673
- let target;
1674
- try {
1675
- target = readlinkSync(exeBinPath);
1676
- } catch {
1677
- errors.push("Could not read 'exe' symlink");
1678
- return { created, skipped, errors };
1679
- }
1680
- for (const suffix of ["", "-opencode"]) {
1681
- const linkName = `${name}${suffix}`;
1682
- const linkPath = path6.join(binDir, linkName);
1683
- if (existsSync6(linkPath)) {
1684
- skipped.push(linkName);
1685
- continue;
1686
- }
1687
- try {
1688
- symlinkSync(target, linkPath);
1689
- created.push(linkName);
1690
- } catch (err) {
1691
- errors.push(`${linkName}: ${err instanceof Error ? err.message : String(err)}`);
1692
- }
1693
- }
1694
- return { created, skipped, errors };
1695
- }
1696
- var EMPLOYEES_PATH, MULTI_INSTANCE_ROLES;
1697
- var init_employees = __esm({
1698
- "src/lib/employees.ts"() {
1699
- "use strict";
1700
- init_config();
1701
- EMPLOYEES_PATH = path6.join(EXE_AI_DIR, "exe-employees.json");
1702
- MULTI_INSTANCE_ROLES = /* @__PURE__ */ new Set(["principal engineer", "content production specialist", "staff code reviewer"]);
1703
- }
1704
- });
1705
-
1706
- // src/lib/session-registry.ts
1707
- import { readFileSync as readFileSync5, writeFileSync, mkdirSync as mkdirSync2, existsSync as existsSync7 } from "fs";
1708
- import path7 from "path";
1709
- import os4 from "os";
1710
- function registerSession(entry) {
1711
- const dir = path7.dirname(REGISTRY_PATH);
1712
- if (!existsSync7(dir)) {
1713
- mkdirSync2(dir, { recursive: true });
1714
- }
1715
- const sessions = listSessions();
1716
- const idx = sessions.findIndex((s) => s.windowName === entry.windowName);
1717
- if (idx >= 0) {
1718
- sessions[idx] = entry;
1719
- } else {
1720
- sessions.push(entry);
1721
- }
1722
- writeFileSync(REGISTRY_PATH, JSON.stringify(sessions, null, 2));
1723
- }
1724
- function listSessions() {
1725
- try {
1726
- const raw = readFileSync5(REGISTRY_PATH, "utf8");
1727
- return JSON.parse(raw);
1728
- } catch {
1729
- return [];
1730
- }
1731
- }
1732
- var REGISTRY_PATH;
1733
- var init_session_registry = __esm({
1734
- "src/lib/session-registry.ts"() {
1735
- "use strict";
1736
- REGISTRY_PATH = path7.join(os4.homedir(), ".exe-os", "session-registry.json");
1737
- }
1738
- });
1739
-
1740
- // src/lib/session-key.ts
1741
- import { execSync as execSync3 } from "child_process";
1742
- function getSessionKey() {
1743
- if (_cached) return _cached;
1744
- let pid = process.ppid;
1745
- for (let i = 0; i < 10; i++) {
1746
- try {
1747
- const info = execSync3(`ps -p ${pid} -o ppid=,comm=`, {
1748
- encoding: "utf8",
1749
- timeout: 2e3
1750
- }).trim();
1751
- const match = info.match(/^\s*(\d+)\s+(.+)$/);
1752
- if (!match) break;
1753
- const [, ppid, cmd] = match;
1754
- if (cmd === "claude" || cmd.endsWith("/claude")) {
1755
- _cached = String(pid);
1756
- return _cached;
1757
- }
1758
- pid = parseInt(ppid, 10);
1759
- if (pid <= 1) break;
1760
- } catch {
1761
- break;
1762
- }
1763
- }
1764
- _cached = process.env.CLAUDE_CODE_SSE_PORT ?? String(process.ppid);
1765
- return _cached;
1589
+ _cached = process.env.CLAUDE_CODE_SSE_PORT ?? String(process.ppid);
1590
+ return _cached;
1766
1591
  }
1767
1592
  var _cached;
1768
1593
  var init_session_key = __esm({
@@ -1880,14 +1705,14 @@ var init_transport = __esm({
1880
1705
  });
1881
1706
 
1882
1707
  // src/lib/cc-agent-support.ts
1883
- import { execSync as execSync4 } from "child_process";
1708
+ import { execSync as execSync2 } from "child_process";
1884
1709
  function _resetCcAgentSupportCache() {
1885
1710
  _cachedSupport = null;
1886
1711
  }
1887
1712
  function claudeSupportsAgentFlag() {
1888
1713
  if (_cachedSupport !== null) return _cachedSupport;
1889
1714
  try {
1890
- const helpOutput = execSync4("claude --help 2>&1", {
1715
+ const helpOutput = execSync2("claude --help 2>&1", {
1891
1716
  encoding: "utf-8",
1892
1717
  timeout: 5e3
1893
1718
  });
@@ -1953,17 +1778,17 @@ var init_provider_table = __esm({
1953
1778
  });
1954
1779
 
1955
1780
  // src/lib/intercom-queue.ts
1956
- import { readFileSync as readFileSync6, writeFileSync as writeFileSync2, renameSync as renameSync2, existsSync as existsSync8, mkdirSync as mkdirSync3 } from "fs";
1957
- import path8 from "path";
1781
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync2, renameSync as renameSync2, existsSync as existsSync6, mkdirSync as mkdirSync3 } from "fs";
1782
+ import path6 from "path";
1958
1783
  import os5 from "os";
1959
1784
  function ensureDir() {
1960
- const dir = path8.dirname(QUEUE_PATH);
1961
- if (!existsSync8(dir)) mkdirSync3(dir, { recursive: true });
1785
+ const dir = path6.dirname(QUEUE_PATH);
1786
+ if (!existsSync6(dir)) mkdirSync3(dir, { recursive: true });
1962
1787
  }
1963
1788
  function readQueue() {
1964
1789
  try {
1965
- if (!existsSync8(QUEUE_PATH)) return [];
1966
- return JSON.parse(readFileSync6(QUEUE_PATH, "utf8"));
1790
+ if (!existsSync6(QUEUE_PATH)) return [];
1791
+ return JSON.parse(readFileSync4(QUEUE_PATH, "utf8"));
1967
1792
  } catch {
1968
1793
  return [];
1969
1794
  }
@@ -1995,47 +1820,184 @@ var QUEUE_PATH, TTL_MS, INTERCOM_LOG;
1995
1820
  var init_intercom_queue = __esm({
1996
1821
  "src/lib/intercom-queue.ts"() {
1997
1822
  "use strict";
1998
- QUEUE_PATH = path8.join(os5.homedir(), ".exe-os", "intercom-queue.json");
1823
+ QUEUE_PATH = path6.join(os5.homedir(), ".exe-os", "intercom-queue.json");
1999
1824
  TTL_MS = 60 * 60 * 1e3;
2000
- INTERCOM_LOG = path8.join(os5.homedir(), ".exe-os", "intercom.log");
1825
+ INTERCOM_LOG = path6.join(os5.homedir(), ".exe-os", "intercom.log");
2001
1826
  }
2002
1827
  });
2003
1828
 
2004
- // src/lib/license.ts
2005
- import { readFileSync as readFileSync7, writeFileSync as writeFileSync3, existsSync as existsSync9, mkdirSync as mkdirSync4 } from "fs";
2006
- import { randomUUID } from "crypto";
2007
- import path9 from "path";
2008
- import { jwtVerify, importSPKI } from "jose";
2009
- var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH, PLAN_LIMITS;
2010
- var init_license = __esm({
2011
- "src/lib/license.ts"() {
2012
- "use strict";
2013
- init_config();
2014
- LICENSE_PATH = path9.join(EXE_AI_DIR, "license.key");
2015
- CACHE_PATH = path9.join(EXE_AI_DIR, "license-cache.json");
2016
- DEVICE_ID_PATH = path9.join(EXE_AI_DIR, "device-id");
2017
- PLAN_LIMITS = {
2018
- free: { devices: 1, employees: 1, memories: 5e3 },
2019
- pro: { devices: 2, employees: 5, memories: 1e5 },
2020
- team: { devices: 10, employees: 20, memories: 1e6 },
2021
- agency: { devices: 50, employees: 100, memories: 1e7 },
2022
- enterprise: { devices: -1, employees: -1, memories: -1 }
2023
- };
2024
- }
1829
+ // src/lib/employees.ts
1830
+ var employees_exports = {};
1831
+ __export(employees_exports, {
1832
+ EMPLOYEES_PATH: () => EMPLOYEES_PATH,
1833
+ addEmployee: () => addEmployee,
1834
+ getEmployee: () => getEmployee,
1835
+ getEmployeeByRole: () => getEmployeeByRole,
1836
+ getEmployeeNamesByRole: () => getEmployeeNamesByRole,
1837
+ hasRole: () => hasRole,
1838
+ isMultiInstance: () => isMultiInstance,
1839
+ loadEmployees: () => loadEmployees,
1840
+ loadEmployeesSync: () => loadEmployeesSync,
1841
+ registerBinSymlinks: () => registerBinSymlinks,
1842
+ saveEmployees: () => saveEmployees,
1843
+ validateEmployeeName: () => validateEmployeeName
2025
1844
  });
2026
-
2027
- // src/lib/plan-limits.ts
2028
- import { readFileSync as readFileSync8, existsSync as existsSync10 } from "fs";
2029
- import path10 from "path";
2030
- function getLicenseSync() {
2031
- try {
2032
- if (!existsSync10(CACHE_PATH2)) return freeLicense();
2033
- const raw = JSON.parse(readFileSync8(CACHE_PATH2, "utf8"));
2034
- if (!raw.token || typeof raw.token !== "string") return freeLicense();
2035
- const parts = raw.token.split(".");
2036
- if (parts.length !== 3) return freeLicense();
2037
- const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
2038
- const plan = payload.plan ?? "free";
1845
+ import { readFile as readFile3, writeFile as writeFile3, mkdir as mkdir3 } from "fs/promises";
1846
+ import { existsSync as existsSync7, symlinkSync, readlinkSync, readFileSync as readFileSync5 } from "fs";
1847
+ import { execSync as execSync3 } from "child_process";
1848
+ import path7 from "path";
1849
+ function validateEmployeeName(name) {
1850
+ if (!name) {
1851
+ return { valid: false, error: "Name is required" };
1852
+ }
1853
+ if (name.length > 32) {
1854
+ return { valid: false, error: "Name must be 32 characters or fewer" };
1855
+ }
1856
+ if (!/^[a-z][a-z0-9]*$/.test(name)) {
1857
+ return {
1858
+ valid: false,
1859
+ error: "Name must start with a letter and contain only lowercase alphanumeric characters"
1860
+ };
1861
+ }
1862
+ return { valid: true };
1863
+ }
1864
+ async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
1865
+ if (!existsSync7(employeesPath)) {
1866
+ return [];
1867
+ }
1868
+ const raw = await readFile3(employeesPath, "utf-8");
1869
+ try {
1870
+ return JSON.parse(raw);
1871
+ } catch {
1872
+ return [];
1873
+ }
1874
+ }
1875
+ async function saveEmployees(employees, employeesPath = EMPLOYEES_PATH) {
1876
+ await mkdir3(path7.dirname(employeesPath), { recursive: true });
1877
+ await writeFile3(employeesPath, JSON.stringify(employees, null, 2) + "\n", "utf-8");
1878
+ }
1879
+ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
1880
+ if (!existsSync7(employeesPath)) return [];
1881
+ try {
1882
+ return JSON.parse(readFileSync5(employeesPath, "utf-8"));
1883
+ } catch {
1884
+ return [];
1885
+ }
1886
+ }
1887
+ function getEmployee(employees, name) {
1888
+ return employees.find((e) => e.name.toLowerCase() === name.toLowerCase());
1889
+ }
1890
+ function getEmployeeByRole(employees, role) {
1891
+ const lower = role.toLowerCase();
1892
+ return employees.find((e) => e.role.toLowerCase() === lower);
1893
+ }
1894
+ function getEmployeeNamesByRole(employees, role) {
1895
+ const lower = role.toLowerCase();
1896
+ return employees.filter((e) => e.role.toLowerCase() === lower).map((e) => e.name);
1897
+ }
1898
+ function hasRole(agentName, role) {
1899
+ const employees = loadEmployeesSync();
1900
+ const emp = getEmployee(employees, agentName);
1901
+ return emp ? emp.role.toLowerCase() === role.toLowerCase() : false;
1902
+ }
1903
+ function isMultiInstance(agentName, employees) {
1904
+ const roster = employees ?? loadEmployeesSync();
1905
+ const emp = getEmployee(roster, agentName);
1906
+ if (!emp) return false;
1907
+ return MULTI_INSTANCE_ROLES.has(emp.role.toLowerCase());
1908
+ }
1909
+ function addEmployee(employees, employee) {
1910
+ const normalized = { ...employee, name: employee.name.toLowerCase() };
1911
+ if (employees.some((e) => e.name.toLowerCase() === normalized.name)) {
1912
+ throw new Error(`Employee '${normalized.name}' already exists`);
1913
+ }
1914
+ return [...employees, normalized];
1915
+ }
1916
+ function findExeBin() {
1917
+ try {
1918
+ return execSync3(process.platform === "win32" ? "where exe-os" : "which exe-os", { encoding: "utf8" }).trim();
1919
+ } catch {
1920
+ return null;
1921
+ }
1922
+ }
1923
+ function registerBinSymlinks(name) {
1924
+ const created = [];
1925
+ const skipped = [];
1926
+ const errors = [];
1927
+ const exeBinPath = findExeBin();
1928
+ if (!exeBinPath) {
1929
+ errors.push("Could not find 'exe-os' in PATH");
1930
+ return { created, skipped, errors };
1931
+ }
1932
+ const binDir = path7.dirname(exeBinPath);
1933
+ let target;
1934
+ try {
1935
+ target = readlinkSync(exeBinPath);
1936
+ } catch {
1937
+ errors.push("Could not read 'exe' symlink");
1938
+ return { created, skipped, errors };
1939
+ }
1940
+ for (const suffix of ["", "-opencode"]) {
1941
+ const linkName = `${name}${suffix}`;
1942
+ const linkPath = path7.join(binDir, linkName);
1943
+ if (existsSync7(linkPath)) {
1944
+ skipped.push(linkName);
1945
+ continue;
1946
+ }
1947
+ try {
1948
+ symlinkSync(target, linkPath);
1949
+ created.push(linkName);
1950
+ } catch (err) {
1951
+ errors.push(`${linkName}: ${err instanceof Error ? err.message : String(err)}`);
1952
+ }
1953
+ }
1954
+ return { created, skipped, errors };
1955
+ }
1956
+ var EMPLOYEES_PATH, MULTI_INSTANCE_ROLES;
1957
+ var init_employees = __esm({
1958
+ "src/lib/employees.ts"() {
1959
+ "use strict";
1960
+ init_config();
1961
+ EMPLOYEES_PATH = path7.join(EXE_AI_DIR, "exe-employees.json");
1962
+ MULTI_INSTANCE_ROLES = /* @__PURE__ */ new Set(["principal engineer", "content production specialist", "staff code reviewer"]);
1963
+ }
1964
+ });
1965
+
1966
+ // src/lib/license.ts
1967
+ import { readFileSync as readFileSync6, writeFileSync as writeFileSync3, existsSync as existsSync8, mkdirSync as mkdirSync4 } from "fs";
1968
+ import { randomUUID as randomUUID2 } from "crypto";
1969
+ import path8 from "path";
1970
+ import { jwtVerify, importSPKI } from "jose";
1971
+ var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH, PLAN_LIMITS;
1972
+ var init_license = __esm({
1973
+ "src/lib/license.ts"() {
1974
+ "use strict";
1975
+ init_config();
1976
+ LICENSE_PATH = path8.join(EXE_AI_DIR, "license.key");
1977
+ CACHE_PATH = path8.join(EXE_AI_DIR, "license-cache.json");
1978
+ DEVICE_ID_PATH = path8.join(EXE_AI_DIR, "device-id");
1979
+ PLAN_LIMITS = {
1980
+ free: { devices: 1, employees: 1, memories: 5e3 },
1981
+ pro: { devices: 2, employees: 5, memories: 1e5 },
1982
+ team: { devices: 10, employees: 20, memories: 1e6 },
1983
+ agency: { devices: 50, employees: 100, memories: 1e7 },
1984
+ enterprise: { devices: -1, employees: -1, memories: -1 }
1985
+ };
1986
+ }
1987
+ });
1988
+
1989
+ // src/lib/plan-limits.ts
1990
+ import { readFileSync as readFileSync7, existsSync as existsSync9 } from "fs";
1991
+ import path9 from "path";
1992
+ function getLicenseSync() {
1993
+ try {
1994
+ if (!existsSync9(CACHE_PATH2)) return freeLicense();
1995
+ const raw = JSON.parse(readFileSync7(CACHE_PATH2, "utf8"));
1996
+ if (!raw.token || typeof raw.token !== "string") return freeLicense();
1997
+ const parts = raw.token.split(".");
1998
+ if (parts.length !== 3) return freeLicense();
1999
+ const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
2000
+ const plan = payload.plan ?? "free";
2039
2001
  const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
2040
2002
  return {
2041
2003
  valid: true,
@@ -2068,8 +2030,8 @@ function assertEmployeeLimitSync(rosterPath) {
2068
2030
  const filePath = rosterPath ?? EMPLOYEES_PATH;
2069
2031
  let count = 0;
2070
2032
  try {
2071
- if (existsSync10(filePath)) {
2072
- const raw = readFileSync8(filePath, "utf8");
2033
+ if (existsSync9(filePath)) {
2034
+ const raw = readFileSync7(filePath, "utf8");
2073
2035
  const employees = JSON.parse(raw);
2074
2036
  count = Array.isArray(employees) ? employees.length : 0;
2075
2037
  }
@@ -2098,19 +2060,356 @@ var init_plan_limits = __esm({
2098
2060
  this.name = "PlanLimitError";
2099
2061
  }
2100
2062
  };
2101
- CACHE_PATH2 = path10.join(EXE_AI_DIR, "license-cache.json");
2063
+ CACHE_PATH2 = path9.join(EXE_AI_DIR, "license-cache.json");
2064
+ }
2065
+ });
2066
+
2067
+ // src/lib/session-kill-telemetry.ts
2068
+ import crypto3 from "crypto";
2069
+ async function recordSessionKill(input) {
2070
+ try {
2071
+ const client = getClient();
2072
+ await client.execute({
2073
+ sql: `INSERT INTO session_kills
2074
+ (id, session_name, agent_id, killed_at, reason,
2075
+ ticks_idle, estimated_tokens_saved)
2076
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
2077
+ args: [
2078
+ crypto3.randomUUID(),
2079
+ input.sessionName,
2080
+ input.agentId,
2081
+ (/* @__PURE__ */ new Date()).toISOString(),
2082
+ input.reason,
2083
+ input.ticksIdle ?? null,
2084
+ input.estimatedTokensSaved ?? null
2085
+ ]
2086
+ });
2087
+ } catch (err) {
2088
+ process.stderr.write(
2089
+ `[session-kill-telemetry] write failed: ${err instanceof Error ? err.message : String(err)}
2090
+ `
2091
+ );
2092
+ }
2093
+ }
2094
+ var init_session_kill_telemetry = __esm({
2095
+ "src/lib/session-kill-telemetry.ts"() {
2096
+ "use strict";
2097
+ init_database();
2098
+ }
2099
+ });
2100
+
2101
+ // src/lib/capacity-monitor.ts
2102
+ var capacity_monitor_exports = {};
2103
+ __export(capacity_monitor_exports, {
2104
+ CTX_FLOOR_PERCENT: () => CTX_FLOOR_PERCENT,
2105
+ _resetLastRelaunchCache: () => _resetLastRelaunchCache,
2106
+ _resetPendingCapacityKills: () => _resetPendingCapacityKills,
2107
+ confirmCapacityKill: () => confirmCapacityKill,
2108
+ createOrRefreshResumeTask: () => createOrRefreshResumeTask,
2109
+ extractContextPercent: () => extractContextPercent,
2110
+ isAtCapacity: () => isAtCapacity,
2111
+ isWithinRelaunchCooldown: () => isWithinRelaunchCooldown,
2112
+ pollCapacityDead: () => pollCapacityDead
2113
+ });
2114
+ function resumeTaskTitle(agentId) {
2115
+ return `${RESUME_TITLE_PREFIX} ${agentId} hit context capacity \u2014 continue open tasks`;
2116
+ }
2117
+ function buildResumeContext(agentId, openTasks) {
2118
+ const taskList = openTasks.map(
2119
+ (r, i) => `${i + 1}. [${String(r.priority).toUpperCase()}] ${String(r.title)} (${String(r.task_file)})`
2120
+ ).join("\n");
2121
+ return [
2122
+ "## Context",
2123
+ "",
2124
+ `${agentId} hit context capacity and was auto-relaunched by the capacity monitor.`,
2125
+ "Call recall_my_memory first \u2014 search for 'CONTEXT CHECKPOINT'. Pick up where the previous session stopped.",
2126
+ "",
2127
+ `You have ${openTasks.length} open task(s). Work through them in priority order:`,
2128
+ "",
2129
+ taskList,
2130
+ "",
2131
+ "Read each task file and chain through them. Build and commit after each one."
2132
+ ].join("\n");
2133
+ }
2134
+ function filterPaneContent(paneOutput) {
2135
+ return paneOutput.split("\n").filter((line) => {
2136
+ if (CONTENT_LINE_PREFIX.test(line)) return false;
2137
+ for (const marker of CONTENT_LINE_MARKERS) {
2138
+ if (line.includes(marker)) return false;
2139
+ }
2140
+ for (const re of SOURCE_CODE_MARKERS) {
2141
+ if (re.test(line)) return false;
2142
+ }
2143
+ return true;
2144
+ }).join("\n");
2145
+ }
2146
+ function extractContextPercent(paneOutput) {
2147
+ const match = paneOutput.match(CC_CONTEXT_BAR_RE);
2148
+ if (!match) return null;
2149
+ const parsed = Number.parseInt(match[2], 10);
2150
+ return Number.isFinite(parsed) ? parsed : null;
2151
+ }
2152
+ function isAtCapacity(paneOutput) {
2153
+ const filtered = filterPaneContent(paneOutput);
2154
+ return CAPACITY_PATTERNS.some((p) => p.test(filtered));
2155
+ }
2156
+ function confirmCapacityKill(agentId, now = Date.now()) {
2157
+ const pendingSince = _pendingCapacityKill.get(agentId);
2158
+ if (pendingSince === void 0) {
2159
+ _pendingCapacityKill.set(agentId, now);
2160
+ return false;
2161
+ }
2162
+ if (now - pendingSince > CONFIRMATION_WINDOW_MS) {
2163
+ _pendingCapacityKill.set(agentId, now);
2164
+ return false;
2165
+ }
2166
+ _pendingCapacityKill.delete(agentId);
2167
+ return true;
2168
+ }
2169
+ function _resetPendingCapacityKills() {
2170
+ _pendingCapacityKill.clear();
2171
+ }
2172
+ function _resetLastRelaunchCache() {
2173
+ _lastRelaunch.clear();
2174
+ }
2175
+ async function lastResumeCreatedAtMs(agentId) {
2176
+ const client = getClient();
2177
+ const result = await client.execute({
2178
+ sql: `SELECT MAX(created_at) AS last_created_at
2179
+ FROM tasks
2180
+ WHERE assigned_to = ? AND title LIKE ?`,
2181
+ args: [agentId, `${RESUME_TITLE_PREFIX} %`]
2182
+ });
2183
+ const raw = result.rows[0]?.last_created_at;
2184
+ if (raw === null || raw === void 0) return null;
2185
+ const parsed = Date.parse(String(raw));
2186
+ return Number.isNaN(parsed) ? null : parsed;
2187
+ }
2188
+ async function isWithinRelaunchCooldown(agentId, now = Date.now()) {
2189
+ const cached = _lastRelaunch.get(agentId);
2190
+ if (cached !== void 0) return now - cached < RELAUNCH_COOLDOWN_MS;
2191
+ const persisted = await lastResumeCreatedAtMs(agentId);
2192
+ if (persisted === null) return false;
2193
+ if (now - persisted >= RELAUNCH_COOLDOWN_MS) return false;
2194
+ _lastRelaunch.set(agentId, persisted);
2195
+ return true;
2196
+ }
2197
+ async function createOrRefreshResumeTask(agentId, projectDir, openTasks) {
2198
+ const client = getClient();
2199
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2200
+ const context = buildResumeContext(agentId, openTasks);
2201
+ const existing = await client.execute({
2202
+ sql: `SELECT id FROM tasks
2203
+ WHERE assigned_to = ?
2204
+ AND title LIKE ?
2205
+ AND status IN (${RESUME_ACTIVE_STATUSES.map(() => "?").join(", ")})
2206
+ ORDER BY created_at DESC
2207
+ LIMIT 1`,
2208
+ args: [agentId, RESUME_TITLE_LIKE_PATTERN, ...RESUME_ACTIVE_STATUSES]
2209
+ });
2210
+ if (existing.rows.length > 0) {
2211
+ const taskId = String(existing.rows[0].id);
2212
+ await client.execute({
2213
+ sql: `UPDATE tasks SET context = ?, updated_at = ? WHERE id = ?`,
2214
+ args: [context, now, taskId]
2215
+ });
2216
+ return { created: false, taskId };
2217
+ }
2218
+ const { createTask: createTask2 } = await Promise.resolve().then(() => (init_tasks(), tasks_exports));
2219
+ const task = await createTask2({
2220
+ title: resumeTaskTitle(agentId),
2221
+ assignedTo: agentId,
2222
+ assignedBy: "system",
2223
+ projectName: projectDir.split("/").pop() ?? "unknown",
2224
+ priority: "p0",
2225
+ context,
2226
+ baseDir: projectDir
2227
+ });
2228
+ return { created: true, taskId: task.id };
2229
+ }
2230
+ async function pollCapacityDead() {
2231
+ const transport = getTransport();
2232
+ const relaunched = [];
2233
+ const registered = listSessions().filter(
2234
+ (s) => s.agentId !== "exe"
2235
+ );
2236
+ if (registered.length === 0) return [];
2237
+ let liveSessions;
2238
+ try {
2239
+ liveSessions = transport.listSessions();
2240
+ } catch {
2241
+ return [];
2242
+ }
2243
+ for (const entry of registered) {
2244
+ const { windowName, agentId, projectDir } = entry;
2245
+ if (!liveSessions.includes(windowName)) continue;
2246
+ if (await isWithinRelaunchCooldown(agentId)) continue;
2247
+ let pane;
2248
+ try {
2249
+ pane = transport.capturePane(windowName, 15);
2250
+ } catch {
2251
+ continue;
2252
+ }
2253
+ if (!isAtCapacity(pane)) continue;
2254
+ const ctxPct = extractContextPercent(pane);
2255
+ if (ctxPct !== null && ctxPct < CTX_FLOOR_PERCENT) {
2256
+ process.stderr.write(
2257
+ `[capacity-monitor] ctx-floor: ${agentId} at ${ctxPct}% in ${windowName} \u2014 below ${CTX_FLOOR_PERCENT}%. Skipping capacity kill (likely self-referential content or false positive).
2258
+ `
2259
+ );
2260
+ continue;
2261
+ }
2262
+ if (!confirmCapacityKill(agentId)) {
2263
+ process.stderr.write(
2264
+ `[capacity-monitor] ${agentId} matched capacity pattern once in ${windowName}. Awaiting confirmation on next tick.
2265
+ `
2266
+ );
2267
+ continue;
2268
+ }
2269
+ const verify = await verifyPaneAtCapacity(windowName);
2270
+ if (!verify.atCapacity) {
2271
+ process.stderr.write(
2272
+ `[capacity-monitor] verifyPaneAtCapacity rejected kill for ${agentId} in ${windowName} (reason: ${verify.reason}). Skipping.
2273
+ `
2274
+ );
2275
+ void recordSessionKill({
2276
+ sessionName: windowName,
2277
+ agentId,
2278
+ reason: "capacity_false_positive_blocked"
2279
+ });
2280
+ continue;
2281
+ }
2282
+ process.stderr.write(
2283
+ `[capacity-monitor] Detected ${agentId} at capacity in session ${windowName} (confirmed). Auto-relaunching.
2284
+ `
2285
+ );
2286
+ try {
2287
+ transport.kill(windowName);
2288
+ void recordSessionKill({
2289
+ sessionName: windowName,
2290
+ agentId,
2291
+ reason: "capacity"
2292
+ });
2293
+ const client = getClient();
2294
+ const openTasks = await client.execute({
2295
+ sql: `SELECT id, title, priority, task_file, status
2296
+ FROM tasks
2297
+ WHERE assigned_to = ? AND status IN ('open', 'in_progress')
2298
+ ORDER BY
2299
+ CASE priority WHEN 'p0' THEN 0 WHEN 'p1' THEN 1 WHEN 'p2' THEN 2 ELSE 3 END,
2300
+ created_at ASC
2301
+ LIMIT 10`,
2302
+ args: [agentId]
2303
+ });
2304
+ if (openTasks.rows.length === 0) {
2305
+ process.stderr.write(
2306
+ `[capacity-monitor] ${agentId} has no open tasks \u2014 skipping relaunch.
2307
+ `
2308
+ );
2309
+ continue;
2310
+ }
2311
+ const { created } = await createOrRefreshResumeTask(
2312
+ agentId,
2313
+ projectDir,
2314
+ openTasks.rows
2315
+ );
2316
+ if (created) {
2317
+ await writeNotification({
2318
+ agentId: "system",
2319
+ agentRole: "daemon",
2320
+ event: "capacity_relaunch",
2321
+ project: projectDir.split("/").pop() ?? "unknown",
2322
+ summary: `${agentId} hit context capacity. Auto-relaunched with ${openTasks.rows.length} open task(s).`
2323
+ });
2324
+ }
2325
+ _lastRelaunch.set(agentId, Date.now());
2326
+ if (created) relaunched.push(agentId);
2327
+ } catch (err) {
2328
+ process.stderr.write(
2329
+ `[capacity-monitor] Failed to relaunch ${agentId}: ${err instanceof Error ? err.message : String(err)}
2330
+ `
2331
+ );
2332
+ }
2333
+ }
2334
+ return relaunched;
2335
+ }
2336
+ var CAPACITY_PATTERNS, CONTENT_LINE_PREFIX, CONTENT_LINE_MARKERS, SOURCE_CODE_MARKERS, RELAUNCH_COOLDOWN_MS, _lastRelaunch, RESUME_TITLE_PREFIX, RESUME_TITLE_LIKE_PATTERN, RESUME_ACTIVE_STATUSES, CONFIRMATION_WINDOW_MS, _pendingCapacityKill, CC_CONTEXT_BAR_RE, CTX_FLOOR_PERCENT;
2337
+ var init_capacity_monitor = __esm({
2338
+ "src/lib/capacity-monitor.ts"() {
2339
+ "use strict";
2340
+ init_session_registry();
2341
+ init_transport();
2342
+ init_notifications();
2343
+ init_database();
2344
+ init_session_kill_telemetry();
2345
+ init_tmux_routing();
2346
+ CAPACITY_PATTERNS = [
2347
+ /conversation is too long/i,
2348
+ /maximum context length/i,
2349
+ /context window.*(?:limit|exceed|full)/i,
2350
+ /reached.*(?:token|context).*limit/i
2351
+ ];
2352
+ CONTENT_LINE_PREFIX = /^[\s>#\-*[]/;
2353
+ CONTENT_LINE_MARKERS = [
2354
+ "RESUME:",
2355
+ "intercom",
2356
+ "capacity-monitor",
2357
+ "CAPACITY_PATTERNS",
2358
+ "isAtCapacity",
2359
+ "CONTENT_LINE_MARKERS",
2360
+ "pollCapacityDead",
2361
+ "confirmCapacityKill",
2362
+ "session_kills",
2363
+ "capacity-monitor.test"
2364
+ ];
2365
+ SOURCE_CODE_MARKERS = [
2366
+ /["'`/].*(?:maximum context length|conversation is too long)/i,
2367
+ /(?:maximum context length|conversation is too long).*["'`/]/i
2368
+ ];
2369
+ RELAUNCH_COOLDOWN_MS = 5 * 60 * 1e3;
2370
+ _lastRelaunch = /* @__PURE__ */ new Map();
2371
+ RESUME_TITLE_PREFIX = "RESUME:";
2372
+ RESUME_TITLE_LIKE_PATTERN = `${RESUME_TITLE_PREFIX} % hit context capacity%`;
2373
+ RESUME_ACTIVE_STATUSES = ["open", "in_progress"];
2374
+ CONFIRMATION_WINDOW_MS = 3 * 60 * 1e3;
2375
+ _pendingCapacityKill = /* @__PURE__ */ new Map();
2376
+ CC_CONTEXT_BAR_RE = /([\u2588\u2591\u2592\u2593]{10})\s+(\d+)%/;
2377
+ CTX_FLOOR_PERCENT = 50;
2102
2378
  }
2103
2379
  });
2104
2380
 
2105
2381
  // src/lib/tmux-routing.ts
2106
- import { execFileSync as execFileSync2, execSync as execSync5 } from "child_process";
2107
- import { readFileSync as readFileSync9, writeFileSync as writeFileSync4, mkdirSync as mkdirSync5, existsSync as existsSync11, appendFileSync } from "fs";
2108
- import path11 from "path";
2382
+ var tmux_routing_exports = {};
2383
+ __export(tmux_routing_exports, {
2384
+ acquireSpawnLock: () => acquireSpawnLock,
2385
+ employeeSessionName: () => employeeSessionName,
2386
+ ensureEmployee: () => ensureEmployee,
2387
+ extractRootExe: () => extractRootExe,
2388
+ findFreeInstance: () => findFreeInstance,
2389
+ getDispatchedBy: () => getDispatchedBy,
2390
+ getMySession: () => getMySession,
2391
+ getParentExe: () => getParentExe,
2392
+ getSessionState: () => getSessionState,
2393
+ isEmployeeAlive: () => isEmployeeAlive,
2394
+ isExeSession: () => isExeSession,
2395
+ isSessionBusy: () => isSessionBusy,
2396
+ notifyParentExe: () => notifyParentExe,
2397
+ parseParentExe: () => parseParentExe,
2398
+ registerParentExe: () => registerParentExe,
2399
+ releaseSpawnLock: () => releaseSpawnLock,
2400
+ resolveExeSession: () => resolveExeSession,
2401
+ sendIntercom: () => sendIntercom,
2402
+ spawnEmployee: () => spawnEmployee,
2403
+ verifyPaneAtCapacity: () => verifyPaneAtCapacity
2404
+ });
2405
+ import { execFileSync as execFileSync2, execSync as execSync4 } from "child_process";
2406
+ import { readFileSync as readFileSync8, writeFileSync as writeFileSync4, mkdirSync as mkdirSync5, existsSync as existsSync10, appendFileSync } from "fs";
2407
+ import path10 from "path";
2109
2408
  import os6 from "os";
2110
2409
  import { fileURLToPath } from "url";
2111
2410
  import { unlinkSync as unlinkSync2 } from "fs";
2112
2411
  function spawnLockPath(sessionName) {
2113
- return path11.join(SPAWN_LOCK_DIR, `${sessionName}.lock`);
2412
+ return path10.join(SPAWN_LOCK_DIR, `${sessionName}.lock`);
2114
2413
  }
2115
2414
  function isProcessAlive(pid) {
2116
2415
  try {
@@ -2121,13 +2420,13 @@ function isProcessAlive(pid) {
2121
2420
  }
2122
2421
  }
2123
2422
  function acquireSpawnLock(sessionName) {
2124
- if (!existsSync11(SPAWN_LOCK_DIR)) {
2423
+ if (!existsSync10(SPAWN_LOCK_DIR)) {
2125
2424
  mkdirSync5(SPAWN_LOCK_DIR, { recursive: true });
2126
2425
  }
2127
2426
  const lockFile = spawnLockPath(sessionName);
2128
- if (existsSync11(lockFile)) {
2427
+ if (existsSync10(lockFile)) {
2129
2428
  try {
2130
- const lock = JSON.parse(readFileSync9(lockFile, "utf8"));
2429
+ const lock = JSON.parse(readFileSync8(lockFile, "utf8"));
2131
2430
  const age = Date.now() - lock.timestamp;
2132
2431
  if (isProcessAlive(lock.pid) && age < 6e4) {
2133
2432
  return false;
@@ -2147,13 +2446,13 @@ function releaseSpawnLock(sessionName) {
2147
2446
  function resolveBehaviorsExporterScript() {
2148
2447
  try {
2149
2448
  const thisFile = fileURLToPath(import.meta.url);
2150
- const scriptPath = path11.join(
2151
- path11.dirname(thisFile),
2449
+ const scriptPath = path10.join(
2450
+ path10.dirname(thisFile),
2152
2451
  "..",
2153
2452
  "bin",
2154
2453
  "exe-export-behaviors.js"
2155
2454
  );
2156
- return existsSync11(scriptPath) ? scriptPath : null;
2455
+ return existsSync10(scriptPath) ? scriptPath : null;
2157
2456
  } catch {
2158
2457
  return null;
2159
2458
  }
@@ -2180,21 +2479,70 @@ function getMySession() {
2180
2479
  return getTransport().getMySession();
2181
2480
  }
2182
2481
  function employeeSessionName(employee, exeSession, instance) {
2183
- const suffix = instance != null && instance > 0 ? String(instance) : "";
2184
- return `${employee}${suffix}-${exeSession}`;
2185
- }
2186
- function extractRootExe(name) {
2482
+ if (!/^exe\d+$/.test(exeSession)) {
2483
+ const root = extractRootExe(exeSession);
2484
+ if (root) {
2485
+ process.stderr.write(
2486
+ `[tmux-routing] WARN: exeSession="${exeSession}" is not a root exe session, using "${root}" instead
2487
+ `
2488
+ );
2489
+ exeSession = root;
2490
+ } else {
2491
+ throw new Error(
2492
+ `Invalid exeSession "${exeSession}" \u2014 must be a root exe session (e.g., "exe1"), not an agent session`
2493
+ );
2494
+ }
2495
+ }
2496
+ const suffix = instance != null && instance > 0 ? String(instance) : "";
2497
+ const name = `${employee}${suffix}-${exeSession}`;
2498
+ if (!VALID_SESSION_NAME.test(name)) {
2499
+ throw new Error(
2500
+ `Invalid session name "${name}" \u2014 must match {agent}-exe{N} or {agent}{instance}-exe{N}`
2501
+ );
2502
+ }
2503
+ return name;
2504
+ }
2505
+ function parseParentExe(sessionName, agentId) {
2506
+ const escaped = agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2507
+ const regex = new RegExp(`^${escaped}\\d*-(.+)$`);
2508
+ const match = sessionName.match(regex);
2509
+ return match?.[1] ?? null;
2510
+ }
2511
+ function extractRootExe(name) {
2187
2512
  const match = name.match(/(exe\d+)$/);
2188
2513
  return match?.[1] ?? null;
2189
2514
  }
2515
+ function registerParentExe(sessionKey, parentExe, dispatchedBy) {
2516
+ if (!existsSync10(SESSION_CACHE)) {
2517
+ mkdirSync5(SESSION_CACHE, { recursive: true });
2518
+ }
2519
+ const rootExe = extractRootExe(parentExe) ?? parentExe;
2520
+ const filePath = path10.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`);
2521
+ writeFileSync4(filePath, JSON.stringify({
2522
+ parentExe: rootExe,
2523
+ dispatchedBy: dispatchedBy || rootExe,
2524
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString()
2525
+ }));
2526
+ }
2190
2527
  function getParentExe(sessionKey) {
2191
2528
  try {
2192
- const data = JSON.parse(readFileSync9(path11.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
2529
+ const data = JSON.parse(readFileSync8(path10.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
2193
2530
  return data.parentExe || null;
2194
2531
  } catch {
2195
2532
  return null;
2196
2533
  }
2197
2534
  }
2535
+ function getDispatchedBy(sessionKey) {
2536
+ try {
2537
+ const data = JSON.parse(readFileSync8(
2538
+ path10.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`),
2539
+ "utf8"
2540
+ ));
2541
+ return data.dispatchedBy ?? data.parentExe ?? null;
2542
+ } catch {
2543
+ return null;
2544
+ }
2545
+ }
2198
2546
  function resolveExeSession() {
2199
2547
  const mySession = getMySession();
2200
2548
  if (!mySession) return null;
@@ -2220,17 +2568,43 @@ function findFreeInstance(employeeName, exeSession, maxInstances = 10, isAlive =
2220
2568
  }
2221
2569
  return null;
2222
2570
  }
2571
+ async function verifyPaneAtCapacity(sessionName) {
2572
+ const transport = getTransport();
2573
+ if (!transport.isAlive(sessionName)) {
2574
+ return { atCapacity: false, reason: `session ${sessionName} is not alive` };
2575
+ }
2576
+ let pane;
2577
+ try {
2578
+ pane = transport.capturePane(sessionName, VERIFY_PANE_LINES);
2579
+ } catch (err) {
2580
+ return {
2581
+ atCapacity: false,
2582
+ reason: `capture-pane failed: ${err instanceof Error ? err.message : String(err)}`
2583
+ };
2584
+ }
2585
+ const { isAtCapacity: isAtCapacity2 } = await Promise.resolve().then(() => (init_capacity_monitor(), capacity_monitor_exports));
2586
+ if (!isAtCapacity2(pane)) {
2587
+ return {
2588
+ atCapacity: false,
2589
+ reason: `last ${VERIFY_PANE_LINES} lines show normal work, no capacity banner`
2590
+ };
2591
+ }
2592
+ return {
2593
+ atCapacity: true,
2594
+ reason: "capacity banner matched in recent pane output"
2595
+ };
2596
+ }
2223
2597
  function readDebounceState() {
2224
2598
  try {
2225
- if (!existsSync11(DEBOUNCE_FILE)) return {};
2226
- return JSON.parse(readFileSync9(DEBOUNCE_FILE, "utf8"));
2599
+ if (!existsSync10(DEBOUNCE_FILE)) return {};
2600
+ return JSON.parse(readFileSync8(DEBOUNCE_FILE, "utf8"));
2227
2601
  } catch {
2228
2602
  return {};
2229
2603
  }
2230
2604
  }
2231
2605
  function writeDebounceState(state) {
2232
2606
  try {
2233
- if (!existsSync11(SESSION_CACHE)) mkdirSync5(SESSION_CACHE, { recursive: true });
2607
+ if (!existsSync10(SESSION_CACHE)) mkdirSync5(SESSION_CACHE, { recursive: true });
2234
2608
  writeFileSync4(DEBOUNCE_FILE, JSON.stringify(state));
2235
2609
  } catch {
2236
2610
  }
@@ -2276,6 +2650,10 @@ function getSessionState(sessionName) {
2276
2650
  return "offline";
2277
2651
  }
2278
2652
  }
2653
+ function isSessionBusy(sessionName) {
2654
+ const state = getSessionState(sessionName);
2655
+ return state === "thinking" || state === "tool";
2656
+ }
2279
2657
  function isExeSession(sessionName) {
2280
2658
  return /^exe\d*$/.test(sessionName);
2281
2659
  }
@@ -2321,6 +2699,28 @@ function sendIntercom(targetSession) {
2321
2699
  return "failed";
2322
2700
  }
2323
2701
  }
2702
+ function notifyParentExe(sessionKey) {
2703
+ const target = getDispatchedBy(sessionKey);
2704
+ if (!target) {
2705
+ process.stderr.write(`[intercom] notifyParentExe: no dispatcher found for key ${sessionKey}
2706
+ `);
2707
+ return false;
2708
+ }
2709
+ process.stderr.write(`[intercom] notifyParentExe \u2192 ${target}
2710
+ `);
2711
+ const result = sendIntercom(target);
2712
+ if (result === "failed") {
2713
+ const rootExe = resolveExeSession();
2714
+ if (rootExe && rootExe !== target) {
2715
+ process.stderr.write(`[intercom] notifyParentExe: dispatcher ${target} dead, falling back to root exe ${rootExe}
2716
+ `);
2717
+ const fallback = sendIntercom(rootExe);
2718
+ return fallback !== "failed";
2719
+ }
2720
+ return false;
2721
+ }
2722
+ return true;
2723
+ }
2324
2724
  function ensureEmployee(employeeName, exeSession, projectDir, opts) {
2325
2725
  if (employeeName === "exe") {
2326
2726
  return { status: "failed", sessionName: "", error: "exe is the COO, not a dispatchable employee" };
@@ -2340,6 +2740,22 @@ function ensureEmployee(employeeName, exeSession, projectDir, opts) {
2340
2740
  error: `Error: pass employee name ('${bare}'), not session name ('${employeeName}')`
2341
2741
  };
2342
2742
  }
2743
+ if (!/^exe\d+$/.test(exeSession)) {
2744
+ const root = extractRootExe(exeSession);
2745
+ if (root) {
2746
+ process.stderr.write(
2747
+ `[ensureEmployee] WARN: caller passed exeSession="${exeSession}" (not a root exe). Auto-correcting to "${root}".
2748
+ `
2749
+ );
2750
+ exeSession = root;
2751
+ } else {
2752
+ return {
2753
+ status: "failed",
2754
+ sessionName: "",
2755
+ error: `Invalid exeSession "${exeSession}" \u2014 must be a root exe session (e.g., "exe1")`
2756
+ };
2757
+ }
2758
+ }
2343
2759
  let effectiveInstance = opts?.instance;
2344
2760
  if (effectiveInstance === void 0 && opts?.autoInstance) {
2345
2761
  const free = findFreeInstance(
@@ -2378,26 +2794,26 @@ function spawnEmployee(employeeName, exeSession, projectDir, opts) {
2378
2794
  const transport = getTransport();
2379
2795
  const sessionName = employeeSessionName(employeeName, exeSession, opts?.instance);
2380
2796
  const instanceLabel = opts?.instance != null && opts.instance > 0 ? `${employeeName}${opts.instance}` : employeeName;
2381
- const logDir = path11.join(os6.homedir(), ".exe-os", "session-logs");
2382
- const logFile = path11.join(logDir, `${instanceLabel}-${Date.now()}.log`);
2383
- if (!existsSync11(logDir)) {
2797
+ const logDir = path10.join(os6.homedir(), ".exe-os", "session-logs");
2798
+ const logFile = path10.join(logDir, `${instanceLabel}-${Date.now()}.log`);
2799
+ if (!existsSync10(logDir)) {
2384
2800
  mkdirSync5(logDir, { recursive: true });
2385
2801
  }
2386
2802
  transport.kill(sessionName);
2387
2803
  let cleanupSuffix = "";
2388
2804
  try {
2389
2805
  const thisFile = fileURLToPath(import.meta.url);
2390
- const cleanupScript = path11.join(path11.dirname(thisFile), "..", "bin", "exe-session-cleanup.js");
2391
- if (existsSync11(cleanupScript)) {
2806
+ const cleanupScript = path10.join(path10.dirname(thisFile), "..", "bin", "exe-session-cleanup.js");
2807
+ if (existsSync10(cleanupScript)) {
2392
2808
  cleanupSuffix = `; ${process.execPath} "${cleanupScript}" "${employeeName}" "${exeSession}"`;
2393
2809
  }
2394
2810
  } catch {
2395
2811
  }
2396
2812
  try {
2397
- const claudeJsonPath = path11.join(os6.homedir(), ".claude.json");
2813
+ const claudeJsonPath = path10.join(os6.homedir(), ".claude.json");
2398
2814
  let claudeJson = {};
2399
2815
  try {
2400
- claudeJson = JSON.parse(readFileSync9(claudeJsonPath, "utf8"));
2816
+ claudeJson = JSON.parse(readFileSync8(claudeJsonPath, "utf8"));
2401
2817
  } catch {
2402
2818
  }
2403
2819
  if (!claudeJson.projects) claudeJson.projects = {};
@@ -2409,13 +2825,13 @@ function spawnEmployee(employeeName, exeSession, projectDir, opts) {
2409
2825
  } catch {
2410
2826
  }
2411
2827
  try {
2412
- const settingsDir = path11.join(os6.homedir(), ".claude", "projects");
2828
+ const settingsDir = path10.join(os6.homedir(), ".claude", "projects");
2413
2829
  const normalizedKey = (opts?.cwd ?? projectDir).replace(/\//g, "-").replace(/^-/, "");
2414
- const projSettingsDir = path11.join(settingsDir, normalizedKey);
2415
- const settingsPath = path11.join(projSettingsDir, "settings.json");
2830
+ const projSettingsDir = path10.join(settingsDir, normalizedKey);
2831
+ const settingsPath = path10.join(projSettingsDir, "settings.json");
2416
2832
  let settings = {};
2417
2833
  try {
2418
- settings = JSON.parse(readFileSync9(settingsPath, "utf8"));
2834
+ settings = JSON.parse(readFileSync8(settingsPath, "utf8"));
2419
2835
  } catch {
2420
2836
  }
2421
2837
  const perms = settings.permissions ?? {};
@@ -2456,7 +2872,7 @@ function spawnEmployee(employeeName, exeSession, projectDir, opts) {
2456
2872
  let behaviorsFlag = "";
2457
2873
  let legacyFallbackWarned = false;
2458
2874
  if (!useExeAgent && !useBinSymlink) {
2459
- const identityPath = path11.join(
2875
+ const identityPath = path10.join(
2460
2876
  os6.homedir(),
2461
2877
  ".exe-os",
2462
2878
  "identity",
@@ -2466,13 +2882,13 @@ function spawnEmployee(employeeName, exeSession, projectDir, opts) {
2466
2882
  const hasAgentFlag = claudeSupportsAgentFlag();
2467
2883
  if (hasAgentFlag) {
2468
2884
  identityFlag = ` --agent ${employeeName}`;
2469
- } else if (existsSync11(identityPath)) {
2885
+ } else if (existsSync10(identityPath)) {
2470
2886
  identityFlag = ` --append-system-prompt-file ${identityPath}`;
2471
2887
  legacyFallbackWarned = true;
2472
2888
  }
2473
2889
  const behaviorsFile = exportBehaviorsSync(
2474
2890
  employeeName,
2475
- path11.basename(spawnCwd),
2891
+ path10.basename(spawnCwd),
2476
2892
  sessionName
2477
2893
  );
2478
2894
  if (behaviorsFile) {
@@ -2487,9 +2903,9 @@ function spawnEmployee(employeeName, exeSession, projectDir, opts) {
2487
2903
  }
2488
2904
  let sessionContextFlag = "";
2489
2905
  try {
2490
- const ctxDir = path11.join(os6.homedir(), ".exe-os", "session-cache");
2906
+ const ctxDir = path10.join(os6.homedir(), ".exe-os", "session-cache");
2491
2907
  mkdirSync5(ctxDir, { recursive: true });
2492
- const ctxFile = path11.join(ctxDir, `session-context-${sessionName}.md`);
2908
+ const ctxFile = path10.join(ctxDir, `session-context-${sessionName}.md`);
2493
2909
  const ctxContent = [
2494
2910
  `## Session Context`,
2495
2911
  `You are running in tmux session: ${sessionName}.`,
@@ -2509,109 +2925,686 @@ function spawnEmployee(employeeName, exeSession, projectDir, opts) {
2509
2925
  envPrefix = `${envPrefix} ${cfg.apiKeyEnv}=${keyVal}`;
2510
2926
  }
2511
2927
  }
2512
- }
2513
- let spawnCommand;
2514
- if (useExeAgent) {
2515
- spawnCommand = `${envPrefix} exe-agent --employee ${employeeName} --model ${opts.model} --provider ${opts.provider}${cleanupSuffix}`;
2516
- } else if (useBinSymlink) {
2517
- const binName = `${employeeName}-${ccProvider}`;
2928
+ }
2929
+ let spawnCommand;
2930
+ if (useExeAgent) {
2931
+ spawnCommand = `${envPrefix} exe-agent --employee ${employeeName} --model ${opts.model} --provider ${opts.provider}${cleanupSuffix}`;
2932
+ } else if (useBinSymlink) {
2933
+ const binName = `${employeeName}-${ccProvider}`;
2934
+ process.stderr.write(
2935
+ `[tmux-routing] provider cascade: ${ccProvider} \u2192 spawning ${binName}
2936
+ `
2937
+ );
2938
+ spawnCommand = `${envPrefix} ${binName}${cleanupSuffix}`;
2939
+ } else {
2940
+ spawnCommand = `${envPrefix} claude --dangerously-skip-permissions${identityFlag}${behaviorsFlag}${sessionContextFlag}${cleanupSuffix}`;
2941
+ }
2942
+ const spawnResult = transport.spawn(sessionName, {
2943
+ cwd: spawnCwd,
2944
+ command: spawnCommand
2945
+ });
2946
+ if (spawnResult.error) {
2947
+ releaseSpawnLock(sessionName);
2948
+ return { sessionName, error: `tmux new-session failed: ${spawnResult.error}` };
2949
+ }
2950
+ transport.pipeLog(sessionName, logFile);
2951
+ try {
2952
+ const mySession = getMySession();
2953
+ const dispatchInfo = path10.join(SESSION_CACHE, `dispatch-info-${sessionName}.json`);
2954
+ writeFileSync4(dispatchInfo, JSON.stringify({
2955
+ dispatchedBy: mySession,
2956
+ rootExe: exeSession,
2957
+ provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
2958
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
2959
+ }));
2960
+ } catch {
2961
+ }
2962
+ let booted = false;
2963
+ for (let i = 0; i < 30; i++) {
2964
+ try {
2965
+ execSync4("sleep 0.5");
2966
+ } catch {
2967
+ }
2968
+ try {
2969
+ const pane = transport.capturePane(sessionName);
2970
+ if (useExeAgent) {
2971
+ if (pane.includes("[exe-agent]") || pane.includes("online")) {
2972
+ booted = true;
2973
+ break;
2974
+ }
2975
+ } else {
2976
+ if (pane.includes("Claude Code") || pane.includes("\u276F")) {
2977
+ booted = true;
2978
+ break;
2979
+ }
2980
+ }
2981
+ } catch {
2982
+ }
2983
+ }
2984
+ if (!booted) {
2985
+ releaseSpawnLock(sessionName);
2986
+ return { sessionName, error: `${useExeAgent ? "exe-agent" : "claude"} did not boot within 15s` };
2987
+ }
2988
+ if (!useExeAgent) {
2989
+ try {
2990
+ transport.sendKeys(sessionName, `/exe-call ${employeeName}`);
2991
+ } catch {
2992
+ }
2993
+ }
2994
+ registerSession({
2995
+ windowName: sessionName,
2996
+ agentId: employeeName,
2997
+ projectDir: spawnCwd,
2998
+ parentExe: exeSession,
2999
+ pid: 0,
3000
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString()
3001
+ });
3002
+ releaseSpawnLock(sessionName);
3003
+ return { sessionName };
3004
+ }
3005
+ var SPAWN_LOCK_DIR, SESSION_CACHE, BEHAVIORS_EXPORT_TIMEOUT_MS, VALID_SESSION_NAME, VERIFY_PANE_LINES, INTERCOM_DEBOUNCE_MS, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS, BUSY_PATTERN;
3006
+ var init_tmux_routing = __esm({
3007
+ "src/lib/tmux-routing.ts"() {
3008
+ "use strict";
3009
+ init_session_registry();
3010
+ init_session_key();
3011
+ init_transport();
3012
+ init_cc_agent_support();
3013
+ init_mcp_prefix();
3014
+ init_provider_table();
3015
+ init_intercom_queue();
3016
+ init_plan_limits();
3017
+ SPAWN_LOCK_DIR = path10.join(os6.homedir(), ".exe-os", "spawn-locks");
3018
+ SESSION_CACHE = path10.join(os6.homedir(), ".exe-os", "session-cache");
3019
+ BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
3020
+ VALID_SESSION_NAME = /^[a-z]+-exe\d+$|^[a-z]+\d+-exe\d+$/;
3021
+ VERIFY_PANE_LINES = 200;
3022
+ INTERCOM_DEBOUNCE_MS = 3e4;
3023
+ INTERCOM_LOG2 = path10.join(os6.homedir(), ".exe-os", "intercom.log");
3024
+ DEBOUNCE_FILE = path10.join(SESSION_CACHE, "intercom-debounce.json");
3025
+ DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
3026
+ BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
3027
+ }
3028
+ });
3029
+
3030
+ // src/lib/tasks-crud.ts
3031
+ import crypto4 from "crypto";
3032
+ import path11 from "path";
3033
+ import { execSync as execSync5 } from "child_process";
3034
+ import { mkdir as mkdir4, writeFile as writeFile4, appendFile } from "fs/promises";
3035
+ import { existsSync as existsSync11, readFileSync as readFileSync9 } from "fs";
3036
+ async function writeCheckpoint(input) {
3037
+ const client = getClient();
3038
+ const row = await resolveTask(client, input.taskId);
3039
+ const taskId = String(row.id);
3040
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3041
+ const blockedByIds = [];
3042
+ if (row.blocked_by) {
3043
+ blockedByIds.push(String(row.blocked_by));
3044
+ }
3045
+ const checkpoint = {
3046
+ step: input.step,
3047
+ context_summary: input.contextSummary,
3048
+ files_touched: input.filesTouched ?? [],
3049
+ blocked_by_ids: blockedByIds,
3050
+ last_checkpoint_at: now
3051
+ };
3052
+ const result = await client.execute({
3053
+ sql: `UPDATE tasks SET checkpoint = ?, checkpoint_count = checkpoint_count + 1, updated_at = ? WHERE id = ?`,
3054
+ args: [JSON.stringify(checkpoint), now, taskId]
3055
+ });
3056
+ if (result.rowsAffected === 0) {
3057
+ throw new Error(`Checkpoint write failed: task ${taskId} not found`);
3058
+ }
3059
+ const countResult = await client.execute({
3060
+ sql: "SELECT checkpoint_count FROM tasks WHERE id = ?",
3061
+ args: [taskId]
3062
+ });
3063
+ const checkpointCount = Number(countResult.rows[0]?.checkpoint_count ?? 1);
3064
+ return { checkpointCount };
3065
+ }
3066
+ function extractParentFromContext(contextBody) {
3067
+ if (!contextBody) return null;
3068
+ const match = contextBody.match(
3069
+ /Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
3070
+ );
3071
+ return match ? match[1].toLowerCase() : null;
3072
+ }
3073
+ function slugify(title) {
3074
+ return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
3075
+ }
3076
+ async function resolveTask(client, identifier) {
3077
+ let result = await client.execute({
3078
+ sql: "SELECT * FROM tasks WHERE id = ?",
3079
+ args: [identifier]
3080
+ });
3081
+ if (result.rows.length === 1) return result.rows[0];
3082
+ result = await client.execute({
3083
+ sql: "SELECT * FROM tasks WHERE task_file LIKE ?",
3084
+ args: [`%${identifier}%`]
3085
+ });
3086
+ if (result.rows.length === 1) return result.rows[0];
3087
+ if (result.rows.length > 1) {
3088
+ const exact = result.rows.filter(
3089
+ (r) => String(r.task_file).endsWith(`/${identifier}.md`)
3090
+ );
3091
+ if (exact.length === 1) return exact[0];
3092
+ const candidates = exact.length > 1 ? exact : result.rows;
3093
+ const active = candidates.filter(
3094
+ (r) => !["done", "cancelled"].includes(String(r.status))
3095
+ );
3096
+ if (active.length === 1) return active[0];
3097
+ const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
3098
+ throw new Error(
3099
+ `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
3100
+ );
3101
+ }
3102
+ result = await client.execute({
3103
+ sql: "SELECT * FROM tasks WHERE title LIKE ?",
3104
+ args: [`%${identifier}%`]
3105
+ });
3106
+ if (result.rows.length === 1) return result.rows[0];
3107
+ if (result.rows.length > 1) {
3108
+ const active = result.rows.filter(
3109
+ (r) => !["done", "cancelled"].includes(String(r.status))
3110
+ );
3111
+ if (active.length === 1) return active[0];
3112
+ const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
3113
+ throw new Error(
3114
+ `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
3115
+ );
3116
+ }
3117
+ throw new Error(`Task not found: ${identifier}`);
3118
+ }
3119
+ async function createTaskCore(input) {
3120
+ const client = getClient();
3121
+ const id = crypto4.randomUUID();
3122
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3123
+ const slug = slugify(input.title);
3124
+ const taskFile = input.taskFile ?? `exe/${input.assignedTo}/${slug}.md`;
3125
+ let blockedById = null;
3126
+ const initialStatus = input.blockedBy ? "blocked" : "open";
3127
+ if (input.blockedBy) {
3128
+ const blocker = await resolveTask(client, input.blockedBy);
3129
+ blockedById = String(blocker.id);
3130
+ }
3131
+ let parentTaskId = null;
3132
+ let parentRef = input.parentTaskId;
3133
+ if (!parentRef) {
3134
+ const extracted = extractParentFromContext(input.context);
3135
+ if (extracted) {
3136
+ parentRef = extracted;
3137
+ process.stderr.write(
3138
+ "[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
3139
+ );
3140
+ }
3141
+ }
3142
+ if (parentRef) {
3143
+ try {
3144
+ const parent = await resolveTask(client, parentRef);
3145
+ parentTaskId = String(parent.id);
3146
+ } catch (err) {
3147
+ if (!input.parentTaskId) {
3148
+ throw new Error(
3149
+ `create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
3150
+ );
3151
+ }
3152
+ throw err;
3153
+ }
3154
+ }
3155
+ let warning;
3156
+ const dupCheck = await client.execute({
3157
+ sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
3158
+ args: [input.title, input.assignedTo]
3159
+ });
3160
+ if (dupCheck.rows.length > 0) {
3161
+ warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
3162
+ }
3163
+ if (input.baseDir) {
3164
+ try {
3165
+ await mkdir4(path11.join(input.baseDir, "exe", "output"), { recursive: true });
3166
+ await mkdir4(path11.join(input.baseDir, "exe", "research"), { recursive: true });
3167
+ await ensureArchitectureDoc(input.baseDir, input.projectName);
3168
+ await ensureGitignoreExe(input.baseDir);
3169
+ } catch {
3170
+ }
3171
+ }
3172
+ const complexity = input.complexity ?? "standard";
3173
+ let sessionScope = null;
3174
+ try {
3175
+ const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
3176
+ sessionScope = resolveExeSession2();
3177
+ } catch {
3178
+ }
3179
+ await client.execute({
3180
+ sql: `INSERT INTO tasks (id, title, assigned_to, assigned_by, project_name, priority, status, task_file, blocked_by, parent_task_id, reviewer, context, complexity, budget_tokens, budget_fallback_model, tokens_used, tokens_warned_at, session_scope, created_at, updated_at)
3181
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
3182
+ args: [
3183
+ id,
3184
+ input.title,
3185
+ input.assignedTo,
3186
+ input.assignedBy,
3187
+ input.projectName,
3188
+ input.priority,
3189
+ initialStatus,
3190
+ taskFile,
3191
+ blockedById,
3192
+ parentTaskId,
3193
+ input.reviewer ?? null,
3194
+ input.context,
3195
+ complexity,
3196
+ input.budgetTokens ?? null,
3197
+ input.budgetFallbackModel ?? null,
3198
+ 0,
3199
+ null,
3200
+ sessionScope,
3201
+ now,
3202
+ now
3203
+ ]
3204
+ });
3205
+ return {
3206
+ id,
3207
+ title: input.title,
3208
+ assignedTo: input.assignedTo,
3209
+ assignedBy: input.assignedBy,
3210
+ projectName: input.projectName,
3211
+ priority: input.priority,
3212
+ status: initialStatus,
3213
+ taskFile,
3214
+ createdAt: now,
3215
+ updatedAt: now,
3216
+ warning,
3217
+ budgetTokens: input.budgetTokens ?? null,
3218
+ budgetFallbackModel: input.budgetFallbackModel ?? null,
3219
+ tokensUsed: 0,
3220
+ tokensWarnedAt: null
3221
+ };
3222
+ }
3223
+ async function listTasks(input) {
3224
+ const client = getClient();
3225
+ const conditions = [];
3226
+ const args = [];
3227
+ if (input.assignedTo) {
3228
+ conditions.push("assigned_to = ?");
3229
+ args.push(input.assignedTo);
3230
+ }
3231
+ if (input.status) {
3232
+ conditions.push("status = ?");
3233
+ args.push(input.status);
3234
+ } else {
3235
+ conditions.push("status IN ('open', 'in_progress', 'blocked')");
3236
+ }
3237
+ if (input.projectName) {
3238
+ conditions.push("project_name = ?");
3239
+ args.push(input.projectName);
3240
+ }
3241
+ if (input.priority) {
3242
+ conditions.push("priority = ?");
3243
+ args.push(input.priority);
3244
+ }
3245
+ try {
3246
+ const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
3247
+ const session = resolveExeSession2();
3248
+ if (session) {
3249
+ conditions.push("(session_scope IS NULL OR session_scope = ?)");
3250
+ args.push(session);
3251
+ }
3252
+ } catch {
3253
+ }
3254
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
3255
+ const result = await client.execute({
3256
+ sql: `SELECT * FROM tasks ${where} ORDER BY CASE status WHEN 'blocked' THEN 0 WHEN 'in_progress' THEN 1 WHEN 'open' THEN 2 ELSE 3 END, priority ASC, created_at DESC LIMIT 1000`,
3257
+ args
3258
+ });
3259
+ return result.rows.map((r) => ({
3260
+ id: String(r.id),
3261
+ title: String(r.title),
3262
+ assignedTo: String(r.assigned_to),
3263
+ assignedBy: String(r.assigned_by),
3264
+ projectName: String(r.project_name),
3265
+ priority: String(r.priority),
3266
+ status: String(r.status),
3267
+ taskFile: String(r.task_file),
3268
+ createdAt: String(r.created_at),
3269
+ updatedAt: String(r.updated_at),
3270
+ checkpointCount: Number(r.checkpoint_count ?? 0),
3271
+ budgetTokens: r.budget_tokens !== null ? Number(r.budget_tokens) : null,
3272
+ budgetFallbackModel: r.budget_fallback_model !== null ? String(r.budget_fallback_model) : null,
3273
+ tokensUsed: Number(r.tokens_used ?? 0),
3274
+ tokensWarnedAt: r.tokens_warned_at !== null ? Number(r.tokens_warned_at) : null
3275
+ }));
3276
+ }
3277
+ function checkStaleCompletion(taskContext, taskCreatedAt) {
3278
+ if (!taskContext) return null;
3279
+ if (!DELEGATION_KEYWORDS.test(taskContext)) return null;
3280
+ try {
3281
+ const since = new Date(taskCreatedAt).toISOString();
3282
+ const branch = execSync5(
3283
+ "git rev-parse --abbrev-ref HEAD 2>/dev/null",
3284
+ { encoding: "utf8", timeout: 3e3 }
3285
+ ).trim();
3286
+ const branchArg = branch && branch !== "HEAD" ? branch : "";
3287
+ const commitCount = execSync5(
3288
+ `git log --oneline --since="${since}" ${branchArg} 2>/dev/null | wc -l`,
3289
+ { encoding: "utf8", timeout: 5e3 }
3290
+ ).trim();
3291
+ const count = parseInt(commitCount, 10);
3292
+ if (count === 0) {
3293
+ return "WARNING: task closed with no new commits since creation. Verify work was actually produced.";
3294
+ }
3295
+ return null;
3296
+ } catch {
3297
+ return null;
3298
+ }
3299
+ }
3300
+ async function updateTaskStatus(input) {
3301
+ const client = getClient();
3302
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3303
+ const row = await resolveTask(client, input.taskId);
3304
+ const taskId = String(row.id);
3305
+ const taskFile = String(row.task_file);
3306
+ if (input.status === "done" && String(row.assigned_by) === "system" && taskFile.includes("review-")) {
3307
+ process.stderr.write(
3308
+ `[updateTask] Review task "${String(row.title)}" being marked done (assigned to ${String(row.assigned_to)})
3309
+ `
3310
+ );
3311
+ }
3312
+ if (input.status === "done") {
3313
+ const existingRow = await client.execute({
3314
+ sql: "SELECT context, created_at FROM tasks WHERE id = ?",
3315
+ args: [taskId]
3316
+ });
3317
+ if (existingRow.rows.length > 0) {
3318
+ const ctx = existingRow.rows[0];
3319
+ const warning = checkStaleCompletion(ctx.context, ctx.created_at);
3320
+ if (warning) {
3321
+ input.result = input.result ? `\u26A0\uFE0F ${warning}
3322
+
3323
+ ${input.result}` : `\u26A0\uFE0F ${warning}`;
3324
+ process.stderr.write(`[tasks] ${warning} (task: ${taskId})
3325
+ `);
3326
+ }
3327
+ }
3328
+ }
3329
+ if (input.status === "in_progress") {
3330
+ const tmuxSession = process.env.TMUX_PANE ?? process.env.MY_TMUX_SESSION ?? "unknown";
3331
+ const claim = await client.execute({
3332
+ sql: `UPDATE tasks
3333
+ SET status = 'in_progress', assigned_tmux = ?, updated_at = ?
3334
+ WHERE id = ? AND status = 'open'`,
3335
+ args: [tmuxSession, now, taskId]
3336
+ });
3337
+ if (claim.rowsAffected === 0) {
3338
+ const current = await client.execute({
3339
+ sql: "SELECT status, assigned_tmux FROM tasks WHERE id = ?",
3340
+ args: [taskId]
3341
+ });
3342
+ const cur = current.rows[0];
3343
+ const status = cur?.status ?? "unknown";
3344
+ const claimedBy = cur?.assigned_tmux ? ` (claimed by ${cur.assigned_tmux})` : "";
3345
+ throw new Error(`${TASK_ALREADY_CLAIMED_PREFIX}: task ${taskId} is ${status}${claimedBy}`);
3346
+ }
3347
+ try {
3348
+ await writeCheckpoint({
3349
+ taskId,
3350
+ step: "claimed",
3351
+ contextSummary: `Task claimed by session. Transitioning open \u2192 in_progress.`
3352
+ });
3353
+ } catch {
3354
+ }
3355
+ return { row, taskFile, now, taskId };
3356
+ }
3357
+ if (input.result) {
3358
+ await client.execute({
3359
+ sql: "UPDATE tasks SET status = ?, result = ?, updated_at = ? WHERE id = ?",
3360
+ args: [input.status, input.result, now, taskId]
3361
+ });
3362
+ } else {
3363
+ await client.execute({
3364
+ sql: "UPDATE tasks SET status = ?, updated_at = ? WHERE id = ?",
3365
+ args: [input.status, now, taskId]
3366
+ });
3367
+ }
3368
+ try {
3369
+ await writeCheckpoint({
3370
+ taskId,
3371
+ step: `status_transition:${input.status}`,
3372
+ contextSummary: input.result ? `Transitioned to ${input.status}. Result: ${input.result.slice(0, 500)}` : `Transitioned to ${input.status}.`
3373
+ });
3374
+ } catch {
3375
+ }
3376
+ return { row, taskFile, now, taskId };
3377
+ }
3378
+ async function deleteTaskCore(taskId, _baseDir) {
3379
+ const client = getClient();
3380
+ const row = await resolveTask(client, taskId);
3381
+ const id = String(row.id);
3382
+ const taskFile = String(row.task_file);
3383
+ const assignedTo = String(row.assigned_to);
3384
+ const assignedBy = String(row.assigned_by);
3385
+ await client.execute({ sql: "DELETE FROM tasks WHERE id = ?", args: [id] });
3386
+ const taskSlug = taskFile.split("/").pop()?.replace(".md", "") ?? "";
3387
+ return { taskFile, assignedTo, assignedBy, taskSlug };
3388
+ }
3389
+ async function ensureArchitectureDoc(baseDir, projectName) {
3390
+ const archPath = path11.join(baseDir, "exe", "ARCHITECTURE.md");
3391
+ try {
3392
+ if (existsSync11(archPath)) return;
3393
+ const template = [
3394
+ `# ${projectName} \u2014 System Architecture`,
3395
+ "",
3396
+ "> Employees: read this before every task. Update it when you change system structure.",
3397
+ `> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
3398
+ "",
3399
+ "## Overview",
3400
+ "",
3401
+ "<!-- Describe what this system does, its main components, and how they connect. -->",
3402
+ "",
3403
+ "## Key Components",
3404
+ "",
3405
+ "<!-- List the major modules, services, or subsystems. -->",
3406
+ "",
3407
+ "## Data Flow",
3408
+ "",
3409
+ "<!-- How does data move through the system? What writes where? -->",
3410
+ "",
3411
+ "## Invariants",
3412
+ "",
3413
+ "<!-- Rules that must never be violated. What breaks if these are wrong? -->",
3414
+ "",
3415
+ "## Dependencies",
3416
+ "",
3417
+ "<!-- What depends on what? If I change X, what else is affected? -->",
3418
+ ""
3419
+ ].join("\n");
3420
+ await writeFile4(archPath, template, "utf-8");
3421
+ } catch {
3422
+ }
3423
+ }
3424
+ async function ensureGitignoreExe(baseDir) {
3425
+ const gitignorePath = path11.join(baseDir, ".gitignore");
3426
+ try {
3427
+ if (existsSync11(gitignorePath)) {
3428
+ const content = readFileSync9(gitignorePath, "utf-8");
3429
+ if (/^\/?exe\/?$/m.test(content)) return;
3430
+ await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
3431
+ } else {
3432
+ await writeFile4(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
3433
+ }
3434
+ } catch {
3435
+ }
3436
+ }
3437
+ var DELEGATION_KEYWORDS, TASK_ALREADY_CLAIMED_PREFIX;
3438
+ var init_tasks_crud = __esm({
3439
+ "src/lib/tasks-crud.ts"() {
3440
+ "use strict";
3441
+ init_database();
3442
+ DELEGATION_KEYWORDS = /parallel|delegate|wave|tom\d*-exe/i;
3443
+ TASK_ALREADY_CLAIMED_PREFIX = "TASK_ALREADY_CLAIMED";
3444
+ }
3445
+ });
3446
+
3447
+ // src/lib/tasks-review.ts
3448
+ import path12 from "path";
3449
+ import { existsSync as existsSync12, readdirSync as readdirSync3, unlinkSync as unlinkSync3 } from "fs";
3450
+ async function countPendingReviews() {
3451
+ const client = getClient();
3452
+ const result = await client.execute({
3453
+ sql: "SELECT COUNT(*) as cnt FROM tasks WHERE status = 'needs_review'",
3454
+ args: []
3455
+ });
3456
+ return Number(result.rows[0]?.cnt) || 0;
3457
+ }
3458
+ async function countNewPendingReviewsSince(sinceIso) {
3459
+ const client = getClient();
3460
+ const result = await client.execute({
3461
+ sql: `SELECT COUNT(*) as cnt FROM tasks
3462
+ WHERE status = 'needs_review' AND updated_at > ?`,
3463
+ args: [sinceIso]
3464
+ });
3465
+ return Number(result.rows[0]?.cnt) || 0;
3466
+ }
3467
+ async function listPendingReviews(limit) {
3468
+ const client = getClient();
3469
+ const result = await client.execute({
3470
+ sql: `SELECT title, assigned_to, project_name FROM tasks
3471
+ WHERE status = 'needs_review'
3472
+ ORDER BY priority ASC, created_at DESC LIMIT ?`,
3473
+ args: [limit]
3474
+ });
3475
+ return result.rows;
3476
+ }
3477
+ async function cleanupOrphanedReviews() {
3478
+ const client = getClient();
3479
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3480
+ const r1 = await client.execute({
3481
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
3482
+ WHERE status = 'needs_review'
3483
+ AND assigned_by = 'system'
3484
+ AND title LIKE 'Review:%'
3485
+ AND parent_task_id IN (SELECT id FROM tasks WHERE status IN ('done', 'cancelled'))`,
3486
+ args: [now]
3487
+ });
3488
+ const staleThreshold = new Date(Date.now() - 60 * 60 * 1e3).toISOString();
3489
+ const r2 = await client.execute({
3490
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
3491
+ WHERE status = 'needs_review'
3492
+ AND result IS NOT NULL
3493
+ AND updated_at < ?`,
3494
+ args: [now, staleThreshold]
3495
+ });
3496
+ const total = r1.rowsAffected + r2.rowsAffected;
3497
+ if (total > 0) {
3498
+ process.stderr.write(
3499
+ `[cleanup] Closed ${total} orphaned review(s): ${r1.rowsAffected} cascade + ${r2.rowsAffected} stale
3500
+ `
3501
+ );
3502
+ }
3503
+ return total;
3504
+ }
3505
+ function getReviewChecklist(role, agent, taskSlug) {
3506
+ const roleLower = role.toLowerCase();
3507
+ if (roleLower.includes("engineer") || roleLower === "principal engineer") {
3508
+ return {
3509
+ lens: "Code Quality (Engineer)",
3510
+ checklist: [
3511
+ "1. Do all tests pass? Any new tests needed?",
3512
+ "2. Is the code clean \u2014 no dead code, no TODOs left?",
3513
+ "3. Does it follow existing patterns and conventions in the codebase?",
3514
+ "4. Any regressions in the test suite?"
3515
+ ]
3516
+ };
3517
+ }
3518
+ if (roleLower === "cto" || roleLower.includes("architect")) {
3519
+ return {
3520
+ lens: "Architecture (CTO)",
3521
+ checklist: [
3522
+ "1. Does this fit the existing architecture? Consistent with ARCHITECTURE.md?",
3523
+ "2. Is it backward compatible? Any breaking changes?",
3524
+ "3. Does it introduce technical debt? Is that debt justified?",
3525
+ "4. Security implications? Any new attack surface?",
3526
+ "5. Does it scale? Performance considerations?",
3527
+ "6. Coordination: does this affect other employees' work or other projects?"
3528
+ ]
3529
+ };
3530
+ }
3531
+ if (roleLower === "coo" || roleLower.includes("operations")) {
3532
+ return {
3533
+ lens: "Strategic (COO)",
3534
+ checklist: [
3535
+ "1. Does this serve the project mission?",
3536
+ "2. Is this the right work at the right time?",
3537
+ "3. Does the architectural assessment make sense for the business?",
3538
+ "4. Any cross-project implications?"
3539
+ ]
3540
+ };
3541
+ }
3542
+ return {
3543
+ lens: "General",
3544
+ checklist: [
3545
+ "1. Read the original task's acceptance criteria",
3546
+ `2. Check git log for related commits: \`git log --oneline --author-date-order -10\``,
3547
+ "3. Verify code changes match requirements",
3548
+ "4. Check if tests were added/updated",
3549
+ `5. Look for output files in exe/output/${agent}-${taskSlug}*`
3550
+ ]
3551
+ };
3552
+ }
3553
+ async function cleanupReviewFile(row, taskFile, _baseDir) {
3554
+ if (String(row.assigned_by) !== "system" || !taskFile.includes("review-")) return;
3555
+ try {
3556
+ const client = getClient();
3557
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3558
+ const parentId = row.parent_task_id ? String(row.parent_task_id) : null;
3559
+ if (parentId) {
3560
+ const result = await client.execute({
3561
+ sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ? AND status = 'needs_review'",
3562
+ args: [now, parentId]
3563
+ });
3564
+ if (result.rowsAffected > 0) {
3565
+ process.stderr.write(
3566
+ `[review-cleanup] Cascaded original task to done via parent_task_id: ${parentId}
3567
+ `
3568
+ );
3569
+ }
3570
+ } else {
3571
+ const fileName = taskFile.split("/").pop() ?? "";
3572
+ const reviewPrefix = fileName.replace(".md", "");
3573
+ const parts = reviewPrefix.split("-");
3574
+ if (parts.length >= 3 && parts[0] === "review") {
3575
+ const agent = parts[1];
3576
+ const slug = parts.slice(2).join("-");
3577
+ const originalTaskFile = `exe/${agent}/${slug}.md`;
3578
+ const result = await client.execute({
3579
+ sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE task_file = ? AND status = 'needs_review'",
3580
+ args: [now, originalTaskFile]
3581
+ });
3582
+ if (result.rowsAffected > 0) {
3583
+ process.stderr.write(
3584
+ `[review-cleanup] Cascaded original task to done (legacy path): ${originalTaskFile}
3585
+ `
3586
+ );
3587
+ }
3588
+ }
3589
+ }
3590
+ } catch (err) {
2518
3591
  process.stderr.write(
2519
- `[tmux-routing] provider cascade: ${ccProvider} \u2192 spawning ${binName}
3592
+ `[review-cleanup] Failed to cascade original task: ${err instanceof Error ? err.message : String(err)}
2520
3593
  `
2521
3594
  );
2522
- spawnCommand = `${envPrefix} ${binName}${cleanupSuffix}`;
2523
- } else {
2524
- spawnCommand = `${envPrefix} claude --dangerously-skip-permissions${identityFlag}${behaviorsFlag}${sessionContextFlag}${cleanupSuffix}`;
2525
- }
2526
- const spawnResult = transport.spawn(sessionName, {
2527
- cwd: spawnCwd,
2528
- command: spawnCommand
2529
- });
2530
- if (spawnResult.error) {
2531
- releaseSpawnLock(sessionName);
2532
- return { sessionName, error: `tmux new-session failed: ${spawnResult.error}` };
2533
3595
  }
2534
- transport.pipeLog(sessionName, logFile);
2535
3596
  try {
2536
- const mySession = getMySession();
2537
- const dispatchInfo = path11.join(SESSION_CACHE, `dispatch-info-${sessionName}.json`);
2538
- writeFileSync4(dispatchInfo, JSON.stringify({
2539
- dispatchedBy: mySession,
2540
- rootExe: exeSession,
2541
- provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
2542
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
2543
- }));
2544
- } catch {
2545
- }
2546
- let booted = false;
2547
- for (let i = 0; i < 30; i++) {
2548
- try {
2549
- execSync5("sleep 0.5");
2550
- } catch {
2551
- }
2552
- try {
2553
- const pane = transport.capturePane(sessionName);
2554
- if (useExeAgent) {
2555
- if (pane.includes("[exe-agent]") || pane.includes("online")) {
2556
- booted = true;
2557
- break;
2558
- }
2559
- } else {
2560
- if (pane.includes("Claude Code") || pane.includes("\u276F")) {
2561
- booted = true;
2562
- break;
3597
+ const cacheDir = path12.join(EXE_AI_DIR, "session-cache");
3598
+ if (existsSync12(cacheDir)) {
3599
+ for (const f of readdirSync3(cacheDir)) {
3600
+ if (f.startsWith("review-notified-")) {
3601
+ unlinkSync3(path12.join(cacheDir, f));
2563
3602
  }
2564
3603
  }
2565
- } catch {
2566
- }
2567
- }
2568
- if (!booted) {
2569
- releaseSpawnLock(sessionName);
2570
- return { sessionName, error: `${useExeAgent ? "exe-agent" : "claude"} did not boot within 15s` };
2571
- }
2572
- if (!useExeAgent) {
2573
- try {
2574
- transport.sendKeys(sessionName, `/exe-call ${employeeName}`);
2575
- } catch {
2576
3604
  }
3605
+ } catch {
2577
3606
  }
2578
- registerSession({
2579
- windowName: sessionName,
2580
- agentId: employeeName,
2581
- projectDir: spawnCwd,
2582
- parentExe: exeSession,
2583
- pid: 0,
2584
- registeredAt: (/* @__PURE__ */ new Date()).toISOString()
2585
- });
2586
- releaseSpawnLock(sessionName);
2587
- return { sessionName };
2588
3607
  }
2589
- var SPAWN_LOCK_DIR, SESSION_CACHE, BEHAVIORS_EXPORT_TIMEOUT_MS, INTERCOM_DEBOUNCE_MS, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS, BUSY_PATTERN;
2590
- var init_tmux_routing = __esm({
2591
- "src/lib/tmux-routing.ts"() {
2592
- "use strict";
2593
- init_session_registry();
2594
- init_session_key();
2595
- init_transport();
2596
- init_cc_agent_support();
2597
- init_mcp_prefix();
2598
- init_provider_table();
2599
- init_intercom_queue();
2600
- init_plan_limits();
2601
- SPAWN_LOCK_DIR = path11.join(os6.homedir(), ".exe-os", "spawn-locks");
2602
- SESSION_CACHE = path11.join(os6.homedir(), ".exe-os", "session-cache");
2603
- BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
2604
- INTERCOM_DEBOUNCE_MS = 3e4;
2605
- INTERCOM_LOG2 = path11.join(os6.homedir(), ".exe-os", "intercom.log");
2606
- DEBOUNCE_FILE = path11.join(SESSION_CACHE, "intercom-debounce.json");
2607
- DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
2608
- BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
2609
- }
2610
- });
2611
-
2612
- // src/lib/tasks-review.ts
2613
- import path12 from "path";
2614
- import { existsSync as existsSync12, readdirSync as readdirSync3, unlinkSync as unlinkSync3 } from "fs";
2615
3608
  var init_tasks_review = __esm({
2616
3609
  "src/lib/tasks-review.ts"() {
2617
3610
  "use strict";
@@ -2622,12 +3615,83 @@ var init_tasks_review = __esm({
2622
3615
  init_tasks_crud();
2623
3616
  init_tmux_routing();
2624
3617
  init_session_key();
3618
+ init_state_bus();
2625
3619
  }
2626
3620
  });
2627
3621
 
2628
3622
  // src/lib/tasks-chain.ts
2629
3623
  import path13 from "path";
2630
3624
  import { readFile as readFile4, writeFile as writeFile5 } from "fs/promises";
3625
+ async function cascadeUnblock(taskId, baseDir, now) {
3626
+ const client = getClient();
3627
+ const unblocked = await client.execute({
3628
+ sql: `UPDATE tasks SET status = 'open', blocked_by = NULL, updated_at = ?
3629
+ WHERE blocked_by = ? AND status = 'blocked'`,
3630
+ args: [now, taskId]
3631
+ });
3632
+ if (baseDir && unblocked.rowsAffected > 0) {
3633
+ const unblockedRows = await client.execute({
3634
+ sql: `SELECT task_file FROM tasks WHERE blocked_by IS NULL AND updated_at = ?`,
3635
+ args: [now]
3636
+ });
3637
+ for (const ur of unblockedRows.rows) {
3638
+ try {
3639
+ const ubFile = path13.join(baseDir, String(ur.task_file));
3640
+ let ubContent = await readFile4(ubFile, "utf-8");
3641
+ ubContent = ubContent.replace(/\*\*Status:\*\* blocked/, "**Status:** open");
3642
+ ubContent = ubContent.replace(/\n\*\*Blocked by:\*\*.*\n/, "\n");
3643
+ await writeFile5(ubFile, ubContent, "utf-8");
3644
+ } catch {
3645
+ }
3646
+ }
3647
+ }
3648
+ }
3649
+ async function findNextTask(assignedTo) {
3650
+ const client = getClient();
3651
+ const nextResult = await client.execute({
3652
+ sql: `SELECT title, task_file, priority FROM tasks
3653
+ WHERE assigned_to = ? AND status = 'open'
3654
+ ORDER BY priority ASC, created_at ASC
3655
+ LIMIT 1`,
3656
+ args: [assignedTo]
3657
+ });
3658
+ if (nextResult.rows.length === 1) {
3659
+ const nr = nextResult.rows[0];
3660
+ return {
3661
+ title: String(nr.title),
3662
+ priority: String(nr.priority),
3663
+ taskFile: String(nr.task_file)
3664
+ };
3665
+ }
3666
+ return void 0;
3667
+ }
3668
+ async function checkSubtaskCompletion(parentTaskId, projectName) {
3669
+ const client = getClient();
3670
+ const remaining = await client.execute({
3671
+ sql: `SELECT COUNT(*) as cnt FROM tasks
3672
+ WHERE parent_task_id = ? AND status NOT IN ('done', 'cancelled')`,
3673
+ args: [parentTaskId]
3674
+ });
3675
+ const cnt = Number(remaining.rows[0]?.cnt ?? 1);
3676
+ if (cnt === 0) {
3677
+ const parentRow = await client.execute({
3678
+ sql: `SELECT assigned_to, title, task_file, project_name FROM tasks WHERE id = ?`,
3679
+ args: [parentTaskId]
3680
+ });
3681
+ if (parentRow.rows.length === 1) {
3682
+ const pr = parentRow.rows[0];
3683
+ const parentProject = pr.project_name == null ? projectName : String(pr.project_name);
3684
+ await writeNotification({
3685
+ agentId: String(pr.assigned_to),
3686
+ agentRole: "system",
3687
+ event: "subtasks_complete",
3688
+ project: parentProject,
3689
+ summary: `All subtasks complete for "${String(pr.title)}" \u2014 ready for rollup review`,
3690
+ taskFile: String(pr.task_file)
3691
+ });
3692
+ }
3693
+ }
3694
+ }
2631
3695
  var init_tasks_chain = __esm({
2632
3696
  "src/lib/tasks-chain.ts"() {
2633
3697
  "use strict";
@@ -2716,13 +3780,12 @@ function assertSessionScope(actionType, targetProject) {
2716
3780
  };
2717
3781
  }
2718
3782
  process.stderr.write(
2719
- `[session-scope] Cross-project ${actionType}: session project="${currentProject}" \u2260 target project="${targetProject}"
3783
+ `[session-scope] BLOCKED cross-project ${actionType}: session project="${currentProject}" \u2260 target project="${targetProject}"
2720
3784
  `
2721
3785
  );
2722
3786
  return {
2723
- allowed: true,
2724
- // v1: warn-only, don't block
2725
- reason: "cross_session_granted",
3787
+ allowed: false,
3788
+ reason: "cross_session_denied",
2726
3789
  currentProject,
2727
3790
  targetProject,
2728
3791
  targetSession: findSessionForProject(targetProject)?.windowName
@@ -2748,8 +3811,9 @@ async function dispatchTaskToEmployee(input) {
2748
3811
  try {
2749
3812
  const { assertSessionScope: assertSessionScope2 } = (init_session_scope(), __toCommonJS(session_scope_exports));
2750
3813
  const check = assertSessionScope2("dispatch_task", input.projectName);
2751
- if (check.reason === "cross_session_granted") {
3814
+ if (check.reason === "cross_session_denied") {
2752
3815
  crossProject = true;
3816
+ return { dispatched: "skipped", crossProject: true };
2753
3817
  }
2754
3818
  } catch {
2755
3819
  }
@@ -2781,6 +3845,19 @@ async function dispatchTaskToEmployee(input) {
2781
3845
  return { dispatched: "session_missing" };
2782
3846
  }
2783
3847
  }
3848
+ function notifyTaskDone() {
3849
+ try {
3850
+ const key = getSessionKey();
3851
+ if (key && !process.env.VITEST) notifyParentExe(key);
3852
+ } catch {
3853
+ }
3854
+ }
3855
+ async function markTaskNotificationsRead(taskFile) {
3856
+ try {
3857
+ await markAsReadByTaskFile(taskFile);
3858
+ } catch {
3859
+ }
3860
+ }
2784
3861
  var init_tasks_notify = __esm({
2785
3862
  "src/lib/tasks-notify.ts"() {
2786
3863
  "use strict";
@@ -2792,7 +3869,337 @@ var init_tasks_notify = __esm({
2792
3869
  }
2793
3870
  });
2794
3871
 
3872
+ // src/lib/behaviors.ts
3873
+ import crypto5 from "crypto";
3874
+ async function storeBehavior(opts) {
3875
+ const client = getClient();
3876
+ const id = crypto5.randomUUID();
3877
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3878
+ await client.execute({
3879
+ sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, priority, content, active, created_at, updated_at)
3880
+ VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)`,
3881
+ args: [id, opts.agentId, opts.projectName ?? null, opts.domain ?? null, opts.priority ?? "p1", opts.content, now, now]
3882
+ });
3883
+ return id;
3884
+ }
3885
+ var init_behaviors = __esm({
3886
+ "src/lib/behaviors.ts"() {
3887
+ "use strict";
3888
+ init_database();
3889
+ }
3890
+ });
3891
+
3892
+ // src/lib/skill-learning.ts
3893
+ var skill_learning_exports = {};
3894
+ __export(skill_learning_exports, {
3895
+ captureAndLearn: () => captureAndLearn,
3896
+ captureTrajectory: () => captureTrajectory,
3897
+ editDistance: () => editDistance,
3898
+ extractSkill: () => extractSkill,
3899
+ extractTrajectory: () => extractTrajectory,
3900
+ findSimilarTrajectories: () => findSimilarTrajectories,
3901
+ hashSignature: () => hashSignature,
3902
+ storeTrajectory: () => storeTrajectory,
3903
+ sweepTrajectories: () => sweepTrajectories
3904
+ });
3905
+ import crypto6 from "crypto";
3906
+ async function extractTrajectory(taskId, agentId) {
3907
+ const client = getClient();
3908
+ const result = await client.execute({
3909
+ sql: `SELECT tool_name, raw_text
3910
+ FROM memories
3911
+ WHERE task_id = ? AND agent_id = ?
3912
+ ORDER BY timestamp ASC`,
3913
+ args: [taskId, agentId]
3914
+ });
3915
+ if (result.rows.length === 0) return [];
3916
+ const rawTools = result.rows.map((r) => {
3917
+ const toolName = String(r.tool_name);
3918
+ if (toolName === "Bash") {
3919
+ const text = String(r.raw_text);
3920
+ const cmdMatch = text.match(/(?:command|Command).*?[:\s]+"?(\w+)/);
3921
+ return cmdMatch ? `Bash:${cmdMatch[1]}` : "Bash";
3922
+ }
3923
+ return toolName;
3924
+ });
3925
+ const signature = [];
3926
+ for (const tool of rawTools) {
3927
+ if (signature.length === 0 || signature[signature.length - 1] !== tool) {
3928
+ signature.push(tool);
3929
+ }
3930
+ }
3931
+ return signature;
3932
+ }
3933
+ function hashSignature(signature) {
3934
+ return crypto6.createHash("sha256").update(signature.join("|")).digest("hex").slice(0, 16);
3935
+ }
3936
+ async function storeTrajectory(opts) {
3937
+ const client = getClient();
3938
+ const id = crypto6.randomUUID();
3939
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3940
+ const signatureHash = hashSignature(opts.signature);
3941
+ await client.execute({
3942
+ sql: `INSERT INTO trajectories (id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at)
3943
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
3944
+ args: [
3945
+ id,
3946
+ opts.taskId,
3947
+ opts.agentId,
3948
+ opts.projectName,
3949
+ opts.taskTitle,
3950
+ JSON.stringify(opts.signature),
3951
+ signatureHash,
3952
+ opts.signature.length,
3953
+ now
3954
+ ]
3955
+ });
3956
+ return id;
3957
+ }
3958
+ async function findSimilarTrajectories(signature, threshold = DEFAULT_SKILL_THRESHOLD) {
3959
+ const client = getClient();
3960
+ const hash = hashSignature(signature);
3961
+ const result = await client.execute({
3962
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
3963
+ FROM trajectories
3964
+ WHERE signature_hash = ?
3965
+ ORDER BY created_at DESC
3966
+ LIMIT 20`,
3967
+ args: [hash]
3968
+ });
3969
+ const mapRow = (r) => ({
3970
+ id: String(r.id),
3971
+ taskId: String(r.task_id),
3972
+ agentId: String(r.agent_id),
3973
+ projectName: String(r.project_name),
3974
+ taskTitle: String(r.task_title),
3975
+ signature: JSON.parse(String(r.signature)),
3976
+ signatureHash: String(r.signature_hash),
3977
+ toolCount: Number(r.tool_count),
3978
+ skillId: r.skill_id ? String(r.skill_id) : null,
3979
+ createdAt: String(r.created_at)
3980
+ });
3981
+ const matches = result.rows.map(mapRow);
3982
+ if (matches.length >= threshold) return matches;
3983
+ const nearResult = await client.execute({
3984
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
3985
+ FROM trajectories
3986
+ WHERE tool_count BETWEEN ? AND ?
3987
+ AND signature_hash != ?
3988
+ ORDER BY created_at DESC
3989
+ LIMIT 50`,
3990
+ args: [
3991
+ Math.max(1, signature.length - 3),
3992
+ signature.length + 3,
3993
+ hash
3994
+ ]
3995
+ });
3996
+ for (const r of nearResult.rows) {
3997
+ const candidateSig = JSON.parse(String(r.signature));
3998
+ if (editDistance(signature, candidateSig) <= 2) {
3999
+ matches.push(mapRow(r));
4000
+ }
4001
+ }
4002
+ return matches;
4003
+ }
4004
+ async function captureTrajectory(opts) {
4005
+ const signature = await extractTrajectory(opts.taskId, opts.agentId);
4006
+ if (signature.length < 3) {
4007
+ return { trajectoryId: "", similarCount: 0, similar: [] };
4008
+ }
4009
+ const trajectoryId = await storeTrajectory({
4010
+ taskId: opts.taskId,
4011
+ agentId: opts.agentId,
4012
+ projectName: opts.projectName,
4013
+ taskTitle: opts.taskTitle,
4014
+ signature
4015
+ });
4016
+ const similar = await findSimilarTrajectories(
4017
+ signature,
4018
+ opts.skillThreshold ?? DEFAULT_SKILL_THRESHOLD
4019
+ );
4020
+ return { trajectoryId, similarCount: similar.length, similar };
4021
+ }
4022
+ function buildExtractionPrompt(trajectories) {
4023
+ const items = trajectories.map((t, i) => {
4024
+ const sig = t.signature.join(" \u2192 ");
4025
+ return `Task ${i + 1}: "${t.taskTitle}" (${t.agentId}, ${t.projectName}) \u2014 ${t.toolCount} tool calls
4026
+ Signature: ${sig}`;
4027
+ }).join("\n\n");
4028
+ return `You are analyzing ${trajectories.length} completed tasks that followed similar procedures:
4029
+
4030
+ ${items}
4031
+
4032
+ Extract the reusable procedure. Format your response EXACTLY like this:
4033
+
4034
+ SKILL: {name \u2014 short, descriptive}
4035
+ TRIGGER: {when to use this \u2014 one sentence}
4036
+ STEPS:
4037
+ 1. ...
4038
+ 2. ...
4039
+ PITFALLS: {common mistakes to avoid}
4040
+
4041
+ Be specific and actionable. Include tool names, file patterns, and concrete commands where applicable.`;
4042
+ }
4043
+ async function extractSkill(trajectories, model) {
4044
+ if (trajectories.length === 0) return null;
4045
+ const config = await loadConfig();
4046
+ const skillModel = model ?? config.skillModel;
4047
+ const Anthropic = (await import("@anthropic-ai/sdk")).default;
4048
+ const client = new Anthropic();
4049
+ const prompt = buildExtractionPrompt(trajectories);
4050
+ const response = await client.messages.create({
4051
+ model: skillModel,
4052
+ max_tokens: 500,
4053
+ messages: [{ role: "user", content: prompt }]
4054
+ });
4055
+ const textBlock = response.content.find((b) => b.type === "text");
4056
+ const skillText = textBlock?.text;
4057
+ if (!skillText) return null;
4058
+ const agentId = trajectories[0].agentId;
4059
+ const projectName = trajectories[0].projectName;
4060
+ const skillId = await storeBehavior({
4061
+ agentId,
4062
+ content: skillText,
4063
+ domain: "skill",
4064
+ projectName
4065
+ });
4066
+ const dbClient = getClient();
4067
+ for (const t of trajectories) {
4068
+ await dbClient.execute({
4069
+ sql: "UPDATE trajectories SET skill_id = ? WHERE id = ?",
4070
+ args: [skillId, t.id]
4071
+ });
4072
+ }
4073
+ process.stderr.write(
4074
+ `[skill-learning] Skill extracted from ${trajectories.length} trajectories \u2192 behavior ${skillId}
4075
+ `
4076
+ );
4077
+ return skillId;
4078
+ }
4079
+ async function captureAndLearn(opts) {
4080
+ try {
4081
+ const config = await loadConfig();
4082
+ if (!config.skillLearning) return;
4083
+ const { trajectoryId, similarCount, similar } = await captureTrajectory({
4084
+ ...opts,
4085
+ skillThreshold: config.skillThreshold
4086
+ });
4087
+ if (!trajectoryId) return;
4088
+ if (similarCount >= config.skillThreshold) {
4089
+ const unprocessed = similar.filter((t) => !t.skillId);
4090
+ if (unprocessed.length >= config.skillThreshold) {
4091
+ extractSkill(unprocessed, config.skillModel).catch((err) => {
4092
+ process.stderr.write(
4093
+ `[skill-learning] Extraction failed: ${err instanceof Error ? err.message : String(err)}
4094
+ `
4095
+ );
4096
+ });
4097
+ }
4098
+ }
4099
+ } catch (err) {
4100
+ process.stderr.write(
4101
+ `[skill-learning] captureAndLearn failed: ${err instanceof Error ? err.message : String(err)}
4102
+ `
4103
+ );
4104
+ }
4105
+ }
4106
+ async function sweepTrajectories(threshold, model) {
4107
+ const config = await loadConfig();
4108
+ if (!config.skillLearning) return { clustersProcessed: 0, skillsExtracted: 0 };
4109
+ const t = threshold ?? config.skillThreshold;
4110
+ const client = getClient();
4111
+ const result = await client.execute({
4112
+ sql: `SELECT signature_hash, COUNT(*) as cnt
4113
+ FROM trajectories
4114
+ WHERE skill_id IS NULL
4115
+ GROUP BY signature_hash
4116
+ HAVING cnt >= ?
4117
+ ORDER BY cnt DESC
4118
+ LIMIT 10`,
4119
+ args: [t]
4120
+ });
4121
+ let clustersProcessed = 0;
4122
+ let skillsExtracted = 0;
4123
+ for (const row of result.rows) {
4124
+ const hash = String(row.signature_hash);
4125
+ const trajResult = await client.execute({
4126
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at
4127
+ FROM trajectories
4128
+ WHERE signature_hash = ? AND skill_id IS NULL
4129
+ ORDER BY created_at DESC
4130
+ LIMIT 10`,
4131
+ args: [hash]
4132
+ });
4133
+ const trajectories = trajResult.rows.map((r) => ({
4134
+ id: String(r.id),
4135
+ taskId: String(r.task_id),
4136
+ agentId: String(r.agent_id),
4137
+ projectName: String(r.project_name),
4138
+ taskTitle: String(r.task_title),
4139
+ signature: JSON.parse(String(r.signature)),
4140
+ signatureHash: String(r.signature_hash),
4141
+ toolCount: Number(r.tool_count),
4142
+ skillId: null,
4143
+ createdAt: String(r.created_at)
4144
+ }));
4145
+ if (trajectories.length >= t) {
4146
+ clustersProcessed++;
4147
+ const skillId = await extractSkill(trajectories, model ?? config.skillModel);
4148
+ if (skillId) skillsExtracted++;
4149
+ }
4150
+ }
4151
+ return { clustersProcessed, skillsExtracted };
4152
+ }
4153
+ function editDistance(a, b) {
4154
+ const m = a.length;
4155
+ const n = b.length;
4156
+ const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
4157
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
4158
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
4159
+ for (let i = 1; i <= m; i++) {
4160
+ for (let j = 1; j <= n; j++) {
4161
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
4162
+ dp[i][j] = Math.min(
4163
+ dp[i - 1][j] + 1,
4164
+ dp[i][j - 1] + 1,
4165
+ dp[i - 1][j - 1] + cost
4166
+ );
4167
+ }
4168
+ }
4169
+ return dp[m][n];
4170
+ }
4171
+ var DEFAULT_SKILL_THRESHOLD;
4172
+ var init_skill_learning = __esm({
4173
+ "src/lib/skill-learning.ts"() {
4174
+ "use strict";
4175
+ init_database();
4176
+ init_behaviors();
4177
+ init_config();
4178
+ DEFAULT_SKILL_THRESHOLD = 3;
4179
+ }
4180
+ });
4181
+
2795
4182
  // src/lib/tasks.ts
4183
+ var tasks_exports = {};
4184
+ __export(tasks_exports, {
4185
+ cleanupOrphanedReviews: () => cleanupOrphanedReviews,
4186
+ countNewPendingReviewsSince: () => countNewPendingReviewsSince,
4187
+ countPendingReviews: () => countPendingReviews,
4188
+ createTask: () => createTask,
4189
+ createTaskCore: () => createTaskCore,
4190
+ deleteTask: () => deleteTask,
4191
+ deleteTaskCore: () => deleteTaskCore,
4192
+ ensureArchitectureDoc: () => ensureArchitectureDoc,
4193
+ ensureGitignoreExe: () => ensureGitignoreExe,
4194
+ getReviewChecklist: () => getReviewChecklist,
4195
+ listPendingReviews: () => listPendingReviews,
4196
+ listTasks: () => listTasks,
4197
+ resolveTask: () => resolveTask,
4198
+ slugify: () => slugify,
4199
+ updateTask: () => updateTask,
4200
+ updateTaskStatus: () => updateTaskStatus,
4201
+ writeCheckpoint: () => writeCheckpoint
4202
+ });
2796
4203
  import path15 from "path";
2797
4204
  import { writeFileSync as writeFileSync5, mkdirSync as mkdirSync6, unlinkSync as unlinkSync4 } from "fs";
2798
4205
  async function createTask(input) {
@@ -2809,12 +4216,141 @@ async function createTask(input) {
2809
4216
  }
2810
4217
  return result;
2811
4218
  }
4219
+ async function updateTask(input) {
4220
+ const { row, taskFile, now, taskId } = await updateTaskStatus(input);
4221
+ try {
4222
+ const agent = String(row.assigned_to);
4223
+ const cacheDir = path15.join(EXE_AI_DIR, "session-cache");
4224
+ const cachePath = path15.join(cacheDir, `current-task-${agent}.json`);
4225
+ if (input.status === "in_progress") {
4226
+ mkdirSync6(cacheDir, { recursive: true });
4227
+ writeFileSync5(cachePath, JSON.stringify({ taskId, title: String(row.title) }));
4228
+ } else if (input.status === "done" || input.status === "blocked" || input.status === "cancelled") {
4229
+ try {
4230
+ unlinkSync4(cachePath);
4231
+ } catch {
4232
+ }
4233
+ }
4234
+ } catch {
4235
+ }
4236
+ if (input.status === "done") {
4237
+ await cleanupReviewFile(row, taskFile, input.baseDir);
4238
+ }
4239
+ if (input.status === "done" || input.status === "cancelled") {
4240
+ try {
4241
+ const client = getClient();
4242
+ const taskTitle = String(row.title);
4243
+ const escaped = taskTitle.replace(/%/g, "\\%").replace(/_/g, "\\_");
4244
+ await client.execute({
4245
+ sql: `UPDATE tasks SET status = 'cancelled', updated_at = ?
4246
+ WHERE title LIKE ? ESCAPE '\\' AND status IN ('open', 'in_progress')`,
4247
+ args: [now, `%left '${escaped}' as in\\_progress%`]
4248
+ });
4249
+ } catch {
4250
+ }
4251
+ try {
4252
+ const client = getClient();
4253
+ const cascaded = await client.execute({
4254
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
4255
+ WHERE parent_task_id = ? AND status = 'needs_review'`,
4256
+ args: [now, taskId]
4257
+ });
4258
+ if (cascaded.rowsAffected > 0) {
4259
+ process.stderr.write(
4260
+ `[cascade] Closed ${cascaded.rowsAffected} orphaned review task(s) for parent ${taskId}
4261
+ `
4262
+ );
4263
+ }
4264
+ } catch {
4265
+ }
4266
+ }
4267
+ const isTerminal = input.status === "done" || input.status === "needs_review";
4268
+ if (isTerminal) {
4269
+ const isExe = String(row.assigned_to) === "exe";
4270
+ if (!isExe) {
4271
+ notifyTaskDone();
4272
+ }
4273
+ await markTaskNotificationsRead(taskFile);
4274
+ if (input.status === "done") {
4275
+ try {
4276
+ await cascadeUnblock(taskId, input.baseDir, now);
4277
+ } catch {
4278
+ }
4279
+ orgBus.emit({
4280
+ type: "task_completed",
4281
+ taskId,
4282
+ employee: String(row.assigned_to),
4283
+ result: input.result ?? "",
4284
+ timestamp: now
4285
+ });
4286
+ if (row.parent_task_id) {
4287
+ try {
4288
+ await checkSubtaskCompletion(String(row.parent_task_id), String(row.project_name));
4289
+ } catch {
4290
+ }
4291
+ }
4292
+ }
4293
+ }
4294
+ if (input.status === "done" && String(row.assigned_to) !== "exe" && !process.env.VITEST) {
4295
+ Promise.resolve().then(() => (init_skill_learning(), skill_learning_exports)).then(
4296
+ ({ captureAndLearn: captureAndLearn2 }) => captureAndLearn2({
4297
+ taskId,
4298
+ agentId: String(row.assigned_to),
4299
+ projectName: String(row.project_name),
4300
+ taskTitle: String(row.title)
4301
+ })
4302
+ ).catch((err) => {
4303
+ process.stderr.write(
4304
+ `[updateTask] skill learning failed: ${err instanceof Error ? err.message : String(err)}
4305
+ `
4306
+ );
4307
+ });
4308
+ }
4309
+ let nextTask;
4310
+ if (isTerminal && String(row.assigned_to) !== "exe") {
4311
+ try {
4312
+ nextTask = await findNextTask(String(row.assigned_to));
4313
+ } catch {
4314
+ }
4315
+ }
4316
+ return {
4317
+ id: String(row.id),
4318
+ title: String(row.title),
4319
+ assignedTo: String(row.assigned_to),
4320
+ assignedBy: String(row.assigned_by),
4321
+ projectName: String(row.project_name),
4322
+ priority: String(row.priority),
4323
+ status: input.status,
4324
+ taskFile,
4325
+ createdAt: String(row.created_at),
4326
+ updatedAt: now,
4327
+ budgetTokens: row.budget_tokens !== void 0 && row.budget_tokens !== null ? Number(row.budget_tokens) : null,
4328
+ budgetFallbackModel: row.budget_fallback_model !== void 0 && row.budget_fallback_model !== null ? String(row.budget_fallback_model) : null,
4329
+ tokensUsed: Number(row.tokens_used ?? 0),
4330
+ tokensWarnedAt: row.tokens_warned_at !== void 0 && row.tokens_warned_at !== null ? Number(row.tokens_warned_at) : null,
4331
+ nextTask
4332
+ };
4333
+ }
4334
+ async function deleteTask(taskId, baseDir) {
4335
+ const client = getClient();
4336
+ const { taskFile, assignedTo, assignedBy, taskSlug } = await deleteTaskCore(taskId, baseDir);
4337
+ const reviewer = assignedBy || "exe";
4338
+ const reviewSlug = `review-${assignedTo}-${taskSlug}`;
4339
+ const reviewFile = `exe/${reviewer}/${reviewSlug}.md`;
4340
+ await client.execute({
4341
+ sql: "DELETE FROM tasks WHERE task_file = ? OR task_file = ?",
4342
+ args: [reviewFile, `exe/exe/${reviewSlug}.md`]
4343
+ });
4344
+ await markAsReadByTaskFile(taskFile);
4345
+ await markAsReadByTaskFile(reviewFile);
4346
+ }
2812
4347
  var init_tasks = __esm({
2813
4348
  "src/lib/tasks.ts"() {
2814
4349
  "use strict";
2815
4350
  init_database();
2816
4351
  init_config();
2817
4352
  init_notifications();
4353
+ init_state_bus();
2818
4354
  init_tasks_crud();
2819
4355
  init_tasks_review();
2820
4356
  init_tasks_crud();
@@ -2873,6 +4409,7 @@ async function getMasterKey() {
2873
4409
 
2874
4410
  // src/lib/store.ts
2875
4411
  init_config();
4412
+ init_state_bus();
2876
4413
  var INIT_MAX_RETRIES = 3;
2877
4414
  var INIT_RETRY_DELAY_MS = 1e3;
2878
4415
  function isBusyError2(err) {
@@ -2943,6 +4480,11 @@ async function initStore(options) {
2943
4480
  "version-query"
2944
4481
  );
2945
4482
  _nextVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
4483
+ try {
4484
+ const { loadGlobalProcedures: loadGlobalProcedures2 } = await Promise.resolve().then(() => (init_global_procedures(), global_procedures_exports));
4485
+ await loadGlobalProcedures2();
4486
+ } catch {
4487
+ }
2946
4488
  }
2947
4489
 
2948
4490
  // src/adapters/claude/hooks/bug-report-worker.ts