@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
@@ -575,6 +575,13 @@ async function ensureSchema() {
575
575
  });
576
576
  } catch {
577
577
  }
578
+ try {
579
+ await client.execute({
580
+ sql: `ALTER TABLE tasks ADD COLUMN session_scope TEXT`,
581
+ args: []
582
+ });
583
+ } catch {
584
+ }
578
585
  try {
579
586
  await client.execute({
580
587
  sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
@@ -1021,6 +1028,18 @@ async function ensureSchema() {
1021
1028
  CREATE INDEX IF NOT EXISTS idx_session_kills_agent
1022
1029
  ON session_kills(agent_id);
1023
1030
  `);
1031
+ await client.execute(`
1032
+ CREATE TABLE IF NOT EXISTS global_procedures (
1033
+ id TEXT PRIMARY KEY,
1034
+ title TEXT NOT NULL,
1035
+ content TEXT NOT NULL,
1036
+ priority TEXT NOT NULL DEFAULT 'p0',
1037
+ domain TEXT,
1038
+ active INTEGER NOT NULL DEFAULT 1,
1039
+ created_at TEXT NOT NULL,
1040
+ updated_at TEXT NOT NULL
1041
+ )
1042
+ `);
1024
1043
  await client.executeMultiple(`
1025
1044
  CREATE TABLE IF NOT EXISTS conversations (
1026
1045
  id TEXT PRIMARY KEY,
@@ -1228,6 +1247,61 @@ var init_keychain = __esm({
1228
1247
  }
1229
1248
  });
1230
1249
 
1250
+ // src/lib/state-bus.ts
1251
+ var StateBus, orgBus;
1252
+ var init_state_bus = __esm({
1253
+ "src/lib/state-bus.ts"() {
1254
+ "use strict";
1255
+ StateBus = class {
1256
+ handlers = /* @__PURE__ */ new Map();
1257
+ globalHandlers = /* @__PURE__ */ new Set();
1258
+ /** Emit an event to all subscribers */
1259
+ emit(event) {
1260
+ const typeHandlers = this.handlers.get(event.type);
1261
+ if (typeHandlers) {
1262
+ for (const handler of typeHandlers) {
1263
+ try {
1264
+ handler(event);
1265
+ } catch {
1266
+ }
1267
+ }
1268
+ }
1269
+ for (const handler of this.globalHandlers) {
1270
+ try {
1271
+ handler(event);
1272
+ } catch {
1273
+ }
1274
+ }
1275
+ }
1276
+ /** Subscribe to a specific event type */
1277
+ on(type, handler) {
1278
+ if (!this.handlers.has(type)) {
1279
+ this.handlers.set(type, /* @__PURE__ */ new Set());
1280
+ }
1281
+ this.handlers.get(type).add(handler);
1282
+ }
1283
+ /** Subscribe to ALL events */
1284
+ onAny(handler) {
1285
+ this.globalHandlers.add(handler);
1286
+ }
1287
+ /** Unsubscribe from a specific event type */
1288
+ off(type, handler) {
1289
+ this.handlers.get(type)?.delete(handler);
1290
+ }
1291
+ /** Unsubscribe from ALL events */
1292
+ offAny(handler) {
1293
+ this.globalHandlers.delete(handler);
1294
+ }
1295
+ /** Remove all listeners */
1296
+ clear() {
1297
+ this.handlers.clear();
1298
+ this.globalHandlers.clear();
1299
+ }
1300
+ };
1301
+ orgBus = new StateBus();
1302
+ }
1303
+ });
1304
+
1231
1305
  // src/lib/shard-manager.ts
1232
1306
  var shard_manager_exports = {};
1233
1307
  __export(shard_manager_exports, {
@@ -1469,6 +1543,71 @@ var init_shard_manager = __esm({
1469
1543
  }
1470
1544
  });
1471
1545
 
1546
+ // src/lib/global-procedures.ts
1547
+ var global_procedures_exports = {};
1548
+ __export(global_procedures_exports, {
1549
+ deactivateGlobalProcedure: () => deactivateGlobalProcedure,
1550
+ getGlobalProceduresBlock: () => getGlobalProceduresBlock,
1551
+ loadGlobalProcedures: () => loadGlobalProcedures,
1552
+ storeGlobalProcedure: () => storeGlobalProcedure
1553
+ });
1554
+ import { randomUUID } from "crypto";
1555
+ async function loadGlobalProcedures() {
1556
+ const client = getClient();
1557
+ const result = await client.execute({
1558
+ sql: "SELECT * FROM global_procedures WHERE active = 1 ORDER BY priority ASC, created_at ASC",
1559
+ args: []
1560
+ });
1561
+ const procedures = result.rows;
1562
+ if (procedures.length > 0) {
1563
+ _cache = procedures.map((p) => `### ${p.title}
1564
+ ${p.content}`).join("\n\n");
1565
+ } else {
1566
+ _cache = "";
1567
+ }
1568
+ _cacheLoaded = true;
1569
+ return procedures;
1570
+ }
1571
+ function getGlobalProceduresBlock() {
1572
+ if (!_cacheLoaded) return "";
1573
+ if (!_cache) return "";
1574
+ return `## Organization-Wide Procedures (MANDATORY \u2014 supersedes all other rules)
1575
+
1576
+ ${_cache}
1577
+ `;
1578
+ }
1579
+ async function storeGlobalProcedure(input2) {
1580
+ const id = randomUUID();
1581
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1582
+ const client = getClient();
1583
+ await client.execute({
1584
+ sql: `INSERT INTO global_procedures (id, title, content, priority, domain, active, created_at, updated_at)
1585
+ VALUES (?, ?, ?, ?, ?, 1, ?, ?)`,
1586
+ args: [id, input2.title, input2.content, input2.priority ?? "p0", input2.domain ?? null, now, now]
1587
+ });
1588
+ await loadGlobalProcedures();
1589
+ return id;
1590
+ }
1591
+ async function deactivateGlobalProcedure(id) {
1592
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1593
+ const client = getClient();
1594
+ const result = await client.execute({
1595
+ sql: "UPDATE global_procedures SET active = 0, updated_at = ? WHERE id = ?",
1596
+ args: [now, id]
1597
+ });
1598
+ await loadGlobalProcedures();
1599
+ return result.rowsAffected > 0;
1600
+ }
1601
+ var _cache, _cacheLoaded;
1602
+ var init_global_procedures = __esm({
1603
+ "src/lib/global-procedures.ts"() {
1604
+ "use strict";
1605
+ init_database();
1606
+ _cache = "";
1607
+ _cacheLoaded = false;
1608
+ }
1609
+ });
1610
+
1472
1611
  // src/lib/store.ts
1473
1612
  var store_exports = {};
1474
1613
  __export(store_exports, {
@@ -1548,6 +1687,11 @@ async function initStore(options) {
1548
1687
  "version-query"
1549
1688
  );
1550
1689
  _nextVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
1690
+ try {
1691
+ const { loadGlobalProcedures: loadGlobalProcedures2 } = await Promise.resolve().then(() => (init_global_procedures(), global_procedures_exports));
1692
+ await loadGlobalProcedures2();
1693
+ } catch {
1694
+ }
1551
1695
  }
1552
1696
  function classifyTier(record) {
1553
1697
  if (record.tool_name === "commit_to_long_term_memory" && (record.importance ?? 0) >= 8) return 1;
@@ -1589,6 +1733,12 @@ async function writeMemory(record) {
1589
1733
  supersedes_id: record.supersedes_id ?? null
1590
1734
  };
1591
1735
  _pendingRecords.push(dbRow);
1736
+ orgBus.emit({
1737
+ type: "memory_stored",
1738
+ agentId: record.agent_id,
1739
+ project: record.project_name,
1740
+ timestamp: record.timestamp
1741
+ });
1592
1742
  const MAX_PENDING = 1e3;
1593
1743
  if (_pendingRecords.length > MAX_PENDING) {
1594
1744
  const dropped = _pendingRecords.length - MAX_PENDING;
@@ -1934,6 +2084,7 @@ var init_store = __esm({
1934
2084
  init_database();
1935
2085
  init_keychain();
1936
2086
  init_config();
2087
+ init_state_bus();
1937
2088
  INIT_MAX_RETRIES = 3;
1938
2089
  INIT_RETRY_DELAY_MS = 1e3;
1939
2090
  _pendingRecords = [];
@@ -2037,7 +2188,7 @@ var init_self_query_router = __esm({
2037
2188
  // src/lib/exe-daemon-client.ts
2038
2189
  import net from "net";
2039
2190
  import { spawn } from "child_process";
2040
- import { randomUUID } from "crypto";
2191
+ import { randomUUID as randomUUID2 } from "crypto";
2041
2192
  import { existsSync as existsSync4, unlinkSync, readFileSync as readFileSync2, openSync, closeSync, statSync } from "fs";
2042
2193
  import path4 from "path";
2043
2194
  import { fileURLToPath } from "url";
@@ -2229,7 +2380,7 @@ function sendRequest(texts, priority) {
2229
2380
  resolve({ error: "Not connected" });
2230
2381
  return;
2231
2382
  }
2232
- const id = randomUUID();
2383
+ const id = randomUUID2();
2233
2384
  const timer = setTimeout(() => {
2234
2385
  _pending.delete(id);
2235
2386
  resolve({ error: "Request timeout" });
@@ -2247,7 +2398,7 @@ function sendRequest(texts, priority) {
2247
2398
  async function pingDaemon() {
2248
2399
  if (!_socket || !_connected) return null;
2249
2400
  return new Promise((resolve) => {
2250
- const id = randomUUID();
2401
+ const id = randomUUID2();
2251
2402
  const timer = setTimeout(() => {
2252
2403
  _pending.delete(id);
2253
2404
  resolve(null);
@@ -2413,8 +2564,8 @@ async function embedDirect(text) {
2413
2564
  const llamaCpp = await import("node-llama-cpp");
2414
2565
  const { MODELS_DIR: MODELS_DIR2 } = await Promise.resolve().then(() => (init_config(), config_exports));
2415
2566
  const { existsSync: existsSync17 } = await import("fs");
2416
- const path19 = await import("path");
2417
- const modelPath = path19.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
2567
+ const path21 = await import("path");
2568
+ const modelPath = path21.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
2418
2569
  if (!existsSync17(modelPath)) {
2419
2570
  throw new Error(`Embedding model not found at ${modelPath}. Run '/exe-setup' to download it.`);
2420
2571
  }
@@ -3128,7 +3279,7 @@ function queueIntercom(targetSession, reason) {
3128
3279
  }
3129
3280
  writeQueue(queue);
3130
3281
  }
3131
- function drainQueue(isSessionBusy, sendKeys) {
3282
+ function drainQueue(isSessionBusy2, sendKeys) {
3132
3283
  const queue = readQueue();
3133
3284
  if (queue.length === 0) return { drained: 0, failed: 0 };
3134
3285
  const remaining = [];
@@ -3142,7 +3293,7 @@ function drainQueue(isSessionBusy, sendKeys) {
3142
3293
  continue;
3143
3294
  }
3144
3295
  try {
3145
- if (!isSessionBusy(item.targetSession)) {
3296
+ if (!isSessionBusy2(item.targetSession)) {
3146
3297
  const success = sendKeys(item.targetSession);
3147
3298
  if (success) {
3148
3299
  logQueue(`DRAINED \u2192 ${item.targetSession} (after ${item.attempts} retries)`);
@@ -3214,21 +3365,36 @@ async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
3214
3365
  return [];
3215
3366
  }
3216
3367
  }
3368
+ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
3369
+ if (!existsSync9(employeesPath)) return [];
3370
+ try {
3371
+ return JSON.parse(readFileSync7(employeesPath, "utf-8"));
3372
+ } catch {
3373
+ return [];
3374
+ }
3375
+ }
3217
3376
  function getEmployee(employees, name) {
3218
3377
  return employees.find((e) => e.name.toLowerCase() === name.toLowerCase());
3219
3378
  }
3220
- var EMPLOYEES_PATH;
3379
+ function isMultiInstance(agentName, employees) {
3380
+ const roster = employees ?? loadEmployeesSync();
3381
+ const emp = getEmployee(roster, agentName);
3382
+ if (!emp) return false;
3383
+ return MULTI_INSTANCE_ROLES.has(emp.role.toLowerCase());
3384
+ }
3385
+ var EMPLOYEES_PATH, MULTI_INSTANCE_ROLES;
3221
3386
  var init_employees = __esm({
3222
3387
  "src/lib/employees.ts"() {
3223
3388
  "use strict";
3224
3389
  init_config();
3225
3390
  EMPLOYEES_PATH = path11.join(EXE_AI_DIR, "exe-employees.json");
3391
+ MULTI_INSTANCE_ROLES = /* @__PURE__ */ new Set(["principal engineer", "content production specialist", "staff code reviewer"]);
3226
3392
  }
3227
3393
  });
3228
3394
 
3229
3395
  // src/lib/license.ts
3230
3396
  import { readFileSync as readFileSync8, writeFileSync as writeFileSync4, existsSync as existsSync10, mkdirSync as mkdirSync5 } from "fs";
3231
- import { randomUUID as randomUUID2 } from "crypto";
3397
+ import { randomUUID as randomUUID3 } from "crypto";
3232
3398
  import path12 from "path";
3233
3399
  import { jwtVerify, importSPKI } from "jose";
3234
3400
  var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH, PLAN_LIMITS;
@@ -3327,1287 +3493,2666 @@ var init_plan_limits = __esm({
3327
3493
  }
3328
3494
  });
3329
3495
 
3330
- // src/lib/tmux-routing.ts
3331
- import { execFileSync as execFileSync2, execSync as execSync7 } from "child_process";
3332
- import { readFileSync as readFileSync10, writeFileSync as writeFileSync5, mkdirSync as mkdirSync6, existsSync as existsSync12, appendFileSync } from "fs";
3496
+ // src/lib/notifications.ts
3497
+ import crypto3 from "crypto";
3333
3498
  import path14 from "path";
3334
3499
  import os5 from "os";
3335
- import { fileURLToPath as fileURLToPath2 } from "url";
3336
- import { unlinkSync as unlinkSync3 } from "fs";
3337
- function spawnLockPath(sessionName) {
3338
- return path14.join(SPAWN_LOCK_DIR, `${sessionName}.lock`);
3339
- }
3340
- function isProcessAlive(pid) {
3500
+ import {
3501
+ readFileSync as readFileSync10,
3502
+ readdirSync as readdirSync4,
3503
+ unlinkSync as unlinkSync3,
3504
+ existsSync as existsSync12,
3505
+ rmdirSync
3506
+ } from "fs";
3507
+ async function writeNotification(notification) {
3341
3508
  try {
3342
- process.kill(pid, 0);
3343
- return true;
3344
- } catch {
3345
- return false;
3346
- }
3347
- }
3348
- function acquireSpawnLock2(sessionName) {
3349
- if (!existsSync12(SPAWN_LOCK_DIR)) {
3350
- mkdirSync6(SPAWN_LOCK_DIR, { recursive: true });
3351
- }
3352
- const lockFile = spawnLockPath(sessionName);
3353
- if (existsSync12(lockFile)) {
3354
- try {
3355
- const lock = JSON.parse(readFileSync10(lockFile, "utf8"));
3356
- const age = Date.now() - lock.timestamp;
3357
- if (isProcessAlive(lock.pid) && age < 6e4) {
3358
- return false;
3359
- }
3360
- } catch {
3361
- }
3509
+ const client = getClient();
3510
+ const id = crypto3.randomUUID();
3511
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3512
+ await client.execute({
3513
+ sql: `INSERT INTO notifications (id, agent_id, agent_role, event, project, summary, task_file, read, created_at)
3514
+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)`,
3515
+ args: [
3516
+ id,
3517
+ notification.agentId,
3518
+ notification.agentRole,
3519
+ notification.event,
3520
+ notification.project,
3521
+ notification.summary,
3522
+ notification.taskFile ?? null,
3523
+ now
3524
+ ]
3525
+ });
3526
+ } catch (err) {
3527
+ process.stderr.write(`[notifications] WRITE FAILED: ${err instanceof Error ? err.message : String(err)}
3528
+ `);
3362
3529
  }
3363
- writeFileSync5(lockFile, JSON.stringify({ pid: process.pid, timestamp: Date.now() }));
3364
- return true;
3365
3530
  }
3366
- function releaseSpawnLock2(sessionName) {
3531
+ async function markAsReadByTaskFile(taskFile) {
3367
3532
  try {
3368
- unlinkSync3(spawnLockPath(sessionName));
3533
+ const client = getClient();
3534
+ await client.execute({
3535
+ sql: "UPDATE notifications SET read = 1 WHERE task_file = ? AND read = 0",
3536
+ args: [taskFile]
3537
+ });
3369
3538
  } catch {
3370
3539
  }
3371
3540
  }
3372
- function resolveBehaviorsExporterScript() {
3373
- try {
3374
- const thisFile = fileURLToPath2(import.meta.url);
3375
- const scriptPath = path14.join(
3376
- path14.dirname(thisFile),
3377
- "..",
3378
- "bin",
3379
- "exe-export-behaviors.js"
3380
- );
3381
- return existsSync12(scriptPath) ? scriptPath : null;
3382
- } catch {
3383
- return null;
3541
+ var init_notifications = __esm({
3542
+ "src/lib/notifications.ts"() {
3543
+ "use strict";
3544
+ init_database();
3384
3545
  }
3385
- }
3386
- function exportBehaviorsSync(agentId, projectName, sessionKey) {
3387
- const script = resolveBehaviorsExporterScript();
3388
- if (!script) return null;
3546
+ });
3547
+
3548
+ // src/lib/session-kill-telemetry.ts
3549
+ import crypto4 from "crypto";
3550
+ async function recordSessionKill(input2) {
3389
3551
  try {
3390
- const output = execFileSync2(
3391
- process.execPath,
3392
- [script, agentId, projectName, sessionKey],
3393
- { encoding: "utf-8", timeout: BEHAVIORS_EXPORT_TIMEOUT_MS }
3394
- ).trim();
3395
- return output.length > 0 ? output : null;
3552
+ const client = getClient();
3553
+ await client.execute({
3554
+ sql: `INSERT INTO session_kills
3555
+ (id, session_name, agent_id, killed_at, reason,
3556
+ ticks_idle, estimated_tokens_saved)
3557
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
3558
+ args: [
3559
+ crypto4.randomUUID(),
3560
+ input2.sessionName,
3561
+ input2.agentId,
3562
+ (/* @__PURE__ */ new Date()).toISOString(),
3563
+ input2.reason,
3564
+ input2.ticksIdle ?? null,
3565
+ input2.estimatedTokensSaved ?? null
3566
+ ]
3567
+ });
3396
3568
  } catch (err) {
3397
3569
  process.stderr.write(
3398
- `[tmux-routing] behaviors export failed for ${agentId}: ${err instanceof Error ? err.message : String(err)}
3570
+ `[session-kill-telemetry] write failed: ${err instanceof Error ? err.message : String(err)}
3399
3571
  `
3400
3572
  );
3401
- return null;
3402
3573
  }
3403
3574
  }
3404
- function getMySession() {
3405
- return getTransport().getMySession();
3406
- }
3407
- function employeeSessionName(employee, exeSession, instance) {
3408
- const suffix = instance != null && instance > 0 ? String(instance) : "";
3409
- return `${employee}${suffix}-${exeSession}`;
3410
- }
3411
- function extractRootExe(name) {
3412
- const match = name.match(/(exe\d+)$/);
3413
- return match?.[1] ?? null;
3414
- }
3415
- function getParentExe(sessionKey) {
3416
- try {
3417
- const data = JSON.parse(readFileSync10(path14.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
3418
- return data.parentExe || null;
3419
- } catch {
3420
- return null;
3575
+ var init_session_kill_telemetry = __esm({
3576
+ "src/lib/session-kill-telemetry.ts"() {
3577
+ "use strict";
3578
+ init_database();
3421
3579
  }
3422
- }
3423
- function resolveExeSession() {
3424
- const mySession = getMySession();
3425
- if (!mySession) return null;
3426
- try {
3427
- const key = getSessionKey();
3428
- const parentExe = getParentExe(key);
3429
- if (parentExe) {
3430
- return extractRootExe(parentExe) ?? parentExe;
3431
- }
3432
- } catch {
3580
+ });
3581
+
3582
+ // src/lib/tasks-crud.ts
3583
+ import crypto5 from "crypto";
3584
+ import path15 from "path";
3585
+ import { execSync as execSync7 } from "child_process";
3586
+ import { mkdir as mkdir4, writeFile as writeFile4, appendFile } from "fs/promises";
3587
+ import { existsSync as existsSync13, readFileSync as readFileSync11 } from "fs";
3588
+ async function writeCheckpoint(input2) {
3589
+ const client = getClient();
3590
+ const row = await resolveTask(client, input2.taskId);
3591
+ const taskId = String(row.id);
3592
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3593
+ const blockedByIds = [];
3594
+ if (row.blocked_by) {
3595
+ blockedByIds.push(String(row.blocked_by));
3596
+ }
3597
+ const checkpoint = {
3598
+ step: input2.step,
3599
+ context_summary: input2.contextSummary,
3600
+ files_touched: input2.filesTouched ?? [],
3601
+ blocked_by_ids: blockedByIds,
3602
+ last_checkpoint_at: now
3603
+ };
3604
+ const result = await client.execute({
3605
+ sql: `UPDATE tasks SET checkpoint = ?, checkpoint_count = checkpoint_count + 1, updated_at = ? WHERE id = ?`,
3606
+ args: [JSON.stringify(checkpoint), now, taskId]
3607
+ });
3608
+ if (result.rowsAffected === 0) {
3609
+ throw new Error(`Checkpoint write failed: task ${taskId} not found`);
3433
3610
  }
3434
- return extractRootExe(mySession) ?? mySession;
3435
- }
3436
- function isEmployeeAlive(sessionName) {
3437
- return getTransport().isAlive(sessionName);
3611
+ const countResult = await client.execute({
3612
+ sql: "SELECT checkpoint_count FROM tasks WHERE id = ?",
3613
+ args: [taskId]
3614
+ });
3615
+ const checkpointCount = Number(countResult.rows[0]?.checkpoint_count ?? 1);
3616
+ return { checkpointCount };
3438
3617
  }
3439
- function findFreeInstance(employeeName, exeSession, maxInstances = 10, isAlive = isEmployeeAlive) {
3440
- const base = employeeSessionName(employeeName, exeSession);
3441
- if (!isAlive(base) && acquireSpawnLock2(base)) return 0;
3442
- for (let i = 2; i <= maxInstances; i++) {
3443
- const candidate = employeeSessionName(employeeName, exeSession, i);
3444
- if (!isAlive(candidate) && acquireSpawnLock2(candidate)) return i;
3445
- }
3446
- return null;
3618
+ function extractParentFromContext(contextBody) {
3619
+ if (!contextBody) return null;
3620
+ const match = contextBody.match(
3621
+ /Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
3622
+ );
3623
+ return match ? match[1].toLowerCase() : null;
3447
3624
  }
3448
- function readDebounceState() {
3449
- try {
3450
- if (!existsSync12(DEBOUNCE_FILE)) return {};
3451
- return JSON.parse(readFileSync10(DEBOUNCE_FILE, "utf8"));
3452
- } catch {
3453
- return {};
3454
- }
3625
+ function slugify(title) {
3626
+ return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
3455
3627
  }
3456
- function writeDebounceState(state) {
3457
- try {
3458
- if (!existsSync12(SESSION_CACHE)) mkdirSync6(SESSION_CACHE, { recursive: true });
3459
- writeFileSync5(DEBOUNCE_FILE, JSON.stringify(state));
3460
- } catch {
3628
+ async function resolveTask(client, identifier) {
3629
+ let result = await client.execute({
3630
+ sql: "SELECT * FROM tasks WHERE id = ?",
3631
+ args: [identifier]
3632
+ });
3633
+ if (result.rows.length === 1) return result.rows[0];
3634
+ result = await client.execute({
3635
+ sql: "SELECT * FROM tasks WHERE task_file LIKE ?",
3636
+ args: [`%${identifier}%`]
3637
+ });
3638
+ if (result.rows.length === 1) return result.rows[0];
3639
+ if (result.rows.length > 1) {
3640
+ const exact = result.rows.filter(
3641
+ (r) => String(r.task_file).endsWith(`/${identifier}.md`)
3642
+ );
3643
+ if (exact.length === 1) return exact[0];
3644
+ const candidates = exact.length > 1 ? exact : result.rows;
3645
+ const active = candidates.filter(
3646
+ (r) => !["done", "cancelled"].includes(String(r.status))
3647
+ );
3648
+ if (active.length === 1) return active[0];
3649
+ const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
3650
+ throw new Error(
3651
+ `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
3652
+ );
3461
3653
  }
3462
- }
3463
- function isDebounced(targetSession) {
3464
- const state = readDebounceState();
3465
- const lastSent = state[targetSession] ?? 0;
3466
- return Date.now() - lastSent < INTERCOM_DEBOUNCE_MS;
3467
- }
3468
- function recordDebounce(targetSession) {
3469
- const state = readDebounceState();
3470
- state[targetSession] = Date.now();
3471
- const cutoff = Date.now() - DEBOUNCE_CLEANUP_AGE_MS;
3472
- for (const key of Object.keys(state)) {
3473
- if ((state[key] ?? 0) < cutoff) delete state[key];
3654
+ result = await client.execute({
3655
+ sql: "SELECT * FROM tasks WHERE title LIKE ?",
3656
+ args: [`%${identifier}%`]
3657
+ });
3658
+ if (result.rows.length === 1) return result.rows[0];
3659
+ if (result.rows.length > 1) {
3660
+ const active = result.rows.filter(
3661
+ (r) => !["done", "cancelled"].includes(String(r.status))
3662
+ );
3663
+ if (active.length === 1) return active[0];
3664
+ const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
3665
+ throw new Error(
3666
+ `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
3667
+ );
3474
3668
  }
3475
- writeDebounceState(state);
3669
+ throw new Error(`Task not found: ${identifier}`);
3476
3670
  }
3477
- function logIntercom(msg) {
3478
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${msg}
3479
- `;
3480
- process.stderr.write(`[intercom] ${msg}
3481
- `);
3482
- try {
3483
- appendFileSync(INTERCOM_LOG2, line);
3484
- } catch {
3671
+ async function createTaskCore(input2) {
3672
+ const client = getClient();
3673
+ const id = crypto5.randomUUID();
3674
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3675
+ const slug = slugify(input2.title);
3676
+ const taskFile = input2.taskFile ?? `exe/${input2.assignedTo}/${slug}.md`;
3677
+ let blockedById = null;
3678
+ const initialStatus = input2.blockedBy ? "blocked" : "open";
3679
+ if (input2.blockedBy) {
3680
+ const blocker = await resolveTask(client, input2.blockedBy);
3681
+ blockedById = String(blocker.id);
3485
3682
  }
3486
- }
3487
- function getSessionState(sessionName) {
3488
- const transport = getTransport();
3489
- if (!transport.isAlive(sessionName)) return "offline";
3490
- try {
3491
- const pane = transport.capturePane(sessionName, 5);
3492
- if (!pane.includes("\u276F") && !pane.includes("Claude Code") && !BUSY_PATTERN.test(pane) && !/Running…/.test(pane)) {
3493
- if (/\$\s*$/.test(pane) || /% $/.test(pane.trimEnd())) {
3494
- return "no_claude";
3683
+ let parentTaskId = null;
3684
+ let parentRef = input2.parentTaskId;
3685
+ if (!parentRef) {
3686
+ const extracted = extractParentFromContext(input2.context);
3687
+ if (extracted) {
3688
+ parentRef = extracted;
3689
+ process.stderr.write(
3690
+ "[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
3691
+ );
3692
+ }
3693
+ }
3694
+ if (parentRef) {
3695
+ try {
3696
+ const parent = await resolveTask(client, parentRef);
3697
+ parentTaskId = String(parent.id);
3698
+ } catch (err) {
3699
+ if (!input2.parentTaskId) {
3700
+ throw new Error(
3701
+ `create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
3702
+ );
3495
3703
  }
3704
+ throw err;
3496
3705
  }
3497
- if (/Running…/.test(pane)) return "tool";
3498
- if (BUSY_PATTERN.test(pane)) return "thinking";
3499
- return "idle";
3706
+ }
3707
+ let warning;
3708
+ const dupCheck = await client.execute({
3709
+ sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
3710
+ args: [input2.title, input2.assignedTo]
3711
+ });
3712
+ if (dupCheck.rows.length > 0) {
3713
+ warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
3714
+ }
3715
+ if (input2.baseDir) {
3716
+ try {
3717
+ await mkdir4(path15.join(input2.baseDir, "exe", "output"), { recursive: true });
3718
+ await mkdir4(path15.join(input2.baseDir, "exe", "research"), { recursive: true });
3719
+ await ensureArchitectureDoc(input2.baseDir, input2.projectName);
3720
+ await ensureGitignoreExe(input2.baseDir);
3721
+ } catch {
3722
+ }
3723
+ }
3724
+ const complexity = input2.complexity ?? "standard";
3725
+ let sessionScope = null;
3726
+ try {
3727
+ const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
3728
+ sessionScope = resolveExeSession2();
3500
3729
  } catch {
3501
- return "offline";
3502
3730
  }
3731
+ await client.execute({
3732
+ 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)
3733
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
3734
+ args: [
3735
+ id,
3736
+ input2.title,
3737
+ input2.assignedTo,
3738
+ input2.assignedBy,
3739
+ input2.projectName,
3740
+ input2.priority,
3741
+ initialStatus,
3742
+ taskFile,
3743
+ blockedById,
3744
+ parentTaskId,
3745
+ input2.reviewer ?? null,
3746
+ input2.context,
3747
+ complexity,
3748
+ input2.budgetTokens ?? null,
3749
+ input2.budgetFallbackModel ?? null,
3750
+ 0,
3751
+ null,
3752
+ sessionScope,
3753
+ now,
3754
+ now
3755
+ ]
3756
+ });
3757
+ return {
3758
+ id,
3759
+ title: input2.title,
3760
+ assignedTo: input2.assignedTo,
3761
+ assignedBy: input2.assignedBy,
3762
+ projectName: input2.projectName,
3763
+ priority: input2.priority,
3764
+ status: initialStatus,
3765
+ taskFile,
3766
+ createdAt: now,
3767
+ updatedAt: now,
3768
+ warning,
3769
+ budgetTokens: input2.budgetTokens ?? null,
3770
+ budgetFallbackModel: input2.budgetFallbackModel ?? null,
3771
+ tokensUsed: 0,
3772
+ tokensWarnedAt: null
3773
+ };
3503
3774
  }
3504
- function isExeSession(sessionName) {
3505
- return /^exe\d*$/.test(sessionName);
3506
- }
3507
- function sendIntercom(targetSession) {
3508
- const transport = getTransport();
3509
- if (isExeSession(targetSession)) {
3510
- logIntercom(`SKIP_EXE \u2192 ${targetSession} (exe sessions use prompt-submit hook)`);
3511
- return "skipped_exe";
3775
+ async function listTasks(input2) {
3776
+ const client = getClient();
3777
+ const conditions = [];
3778
+ const args = [];
3779
+ if (input2.assignedTo) {
3780
+ conditions.push("assigned_to = ?");
3781
+ args.push(input2.assignedTo);
3512
3782
  }
3513
- if (isDebounced(targetSession)) {
3514
- logIntercom(`DEBOUNCE \u2192 ${targetSession} (cross-process file debounce)`);
3515
- return "debounced";
3783
+ if (input2.status) {
3784
+ conditions.push("status = ?");
3785
+ args.push(input2.status);
3786
+ } else {
3787
+ conditions.push("status IN ('open', 'in_progress', 'blocked')");
3788
+ }
3789
+ if (input2.projectName) {
3790
+ conditions.push("project_name = ?");
3791
+ args.push(input2.projectName);
3792
+ }
3793
+ if (input2.priority) {
3794
+ conditions.push("priority = ?");
3795
+ args.push(input2.priority);
3516
3796
  }
3517
3797
  try {
3518
- const sessions = transport.listSessions();
3519
- if (!sessions.includes(targetSession)) {
3520
- logIntercom(`SKIP \u2192 ${targetSession} (session not found)`);
3521
- return "failed";
3522
- }
3523
- const sessionState = getSessionState(targetSession);
3524
- if (sessionState === "no_claude") {
3525
- queueIntercom(targetSession, "claude not running in session");
3526
- recordDebounce(targetSession);
3527
- logIntercom(`QUEUED \u2192 ${targetSession} (no claude process \u2014 raw shell detected)`);
3528
- return "queued";
3529
- }
3530
- if (sessionState === "thinking" || sessionState === "tool") {
3531
- queueIntercom(targetSession, "session busy at send time");
3532
- recordDebounce(targetSession);
3533
- logIntercom(`QUEUED \u2192 ${targetSession} (session busy, will retry from queue)`);
3534
- return "queued";
3535
- }
3536
- if (transport.isPaneInCopyMode(targetSession)) {
3537
- logIntercom(`COPY_MODE \u2192 ${targetSession} (exiting copy mode first)`);
3538
- transport.sendKeys(targetSession, "q");
3798
+ const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
3799
+ const session = resolveExeSession2();
3800
+ if (session) {
3801
+ conditions.push("(session_scope IS NULL OR session_scope = ?)");
3802
+ args.push(session);
3539
3803
  }
3540
- transport.sendKeys(targetSession, "/exe-intercom");
3541
- recordDebounce(targetSession);
3542
- logIntercom(`DELIVERED \u2192 ${targetSession} (fire-and-forget)`);
3543
- return "delivered";
3544
3804
  } catch {
3545
- logIntercom(`FAIL \u2192 ${targetSession}`);
3546
- return "failed";
3547
3805
  }
3806
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
3807
+ const result = await client.execute({
3808
+ 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`,
3809
+ args
3810
+ });
3811
+ return result.rows.map((r) => ({
3812
+ id: String(r.id),
3813
+ title: String(r.title),
3814
+ assignedTo: String(r.assigned_to),
3815
+ assignedBy: String(r.assigned_by),
3816
+ projectName: String(r.project_name),
3817
+ priority: String(r.priority),
3818
+ status: String(r.status),
3819
+ taskFile: String(r.task_file),
3820
+ createdAt: String(r.created_at),
3821
+ updatedAt: String(r.updated_at),
3822
+ checkpointCount: Number(r.checkpoint_count ?? 0),
3823
+ budgetTokens: r.budget_tokens !== null ? Number(r.budget_tokens) : null,
3824
+ budgetFallbackModel: r.budget_fallback_model !== null ? String(r.budget_fallback_model) : null,
3825
+ tokensUsed: Number(r.tokens_used ?? 0),
3826
+ tokensWarnedAt: r.tokens_warned_at !== null ? Number(r.tokens_warned_at) : null
3827
+ }));
3548
3828
  }
3549
- function ensureEmployee(employeeName, exeSession, projectDir, opts) {
3550
- if (employeeName === "exe") {
3551
- return { status: "failed", sessionName: "", error: "exe is the COO, not a dispatchable employee" };
3552
- }
3829
+ function checkStaleCompletion(taskContext, taskCreatedAt) {
3830
+ if (!taskContext) return null;
3831
+ if (!DELEGATION_KEYWORDS.test(taskContext)) return null;
3553
3832
  try {
3554
- assertEmployeeLimitSync();
3555
- } catch (err) {
3556
- if (err instanceof PlanLimitError) {
3557
- return { status: "failed", sessionName: "", error: err.message };
3833
+ const since = new Date(taskCreatedAt).toISOString();
3834
+ const branch = execSync7(
3835
+ "git rev-parse --abbrev-ref HEAD 2>/dev/null",
3836
+ { encoding: "utf8", timeout: 3e3 }
3837
+ ).trim();
3838
+ const branchArg = branch && branch !== "HEAD" ? branch : "";
3839
+ const commitCount = execSync7(
3840
+ `git log --oneline --since="${since}" ${branchArg} 2>/dev/null | wc -l`,
3841
+ { encoding: "utf8", timeout: 5e3 }
3842
+ ).trim();
3843
+ const count = parseInt(commitCount, 10);
3844
+ if (count === 0) {
3845
+ return "WARNING: task closed with no new commits since creation. Verify work was actually produced.";
3558
3846
  }
3847
+ return null;
3848
+ } catch {
3849
+ return null;
3559
3850
  }
3560
- if (/-exe\d*$/.test(employeeName)) {
3561
- const bare = employeeName.replace(/-exe\d*$/, "").replace(/\d+$/, "");
3562
- return {
3563
- status: "failed",
3564
- sessionName: "",
3565
- error: `Error: pass employee name ('${bare}'), not session name ('${employeeName}')`
3566
- };
3567
- }
3568
- let effectiveInstance = opts?.instance;
3569
- if (effectiveInstance === void 0 && opts?.autoInstance) {
3570
- const free = findFreeInstance(
3571
- employeeName,
3572
- exeSession,
3573
- opts.maxAutoInstances ?? 10
3851
+ }
3852
+ async function updateTaskStatus(input2) {
3853
+ const client = getClient();
3854
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3855
+ const row = await resolveTask(client, input2.taskId);
3856
+ const taskId = String(row.id);
3857
+ const taskFile = String(row.task_file);
3858
+ if (input2.status === "done" && String(row.assigned_by) === "system" && taskFile.includes("review-")) {
3859
+ process.stderr.write(
3860
+ `[updateTask] Review task "${String(row.title)}" being marked done (assigned to ${String(row.assigned_to)})
3861
+ `
3574
3862
  );
3575
- if (free === null) {
3576
- return {
3577
- status: "failed",
3578
- sessionName: employeeSessionName(employeeName, exeSession),
3579
- error: `All ${opts.maxAutoInstances ?? 10} instances of ${employeeName} are alive \u2014 cap reached`
3580
- };
3863
+ }
3864
+ if (input2.status === "done") {
3865
+ const existingRow = await client.execute({
3866
+ sql: "SELECT context, created_at FROM tasks WHERE id = ?",
3867
+ args: [taskId]
3868
+ });
3869
+ if (existingRow.rows.length > 0) {
3870
+ const ctx = existingRow.rows[0];
3871
+ const warning = checkStaleCompletion(ctx.context, ctx.created_at);
3872
+ if (warning) {
3873
+ input2.result = input2.result ? `\u26A0\uFE0F ${warning}
3874
+
3875
+ ${input2.result}` : `\u26A0\uFE0F ${warning}`;
3876
+ process.stderr.write(`[tasks] ${warning} (task: ${taskId})
3877
+ `);
3878
+ }
3581
3879
  }
3582
- effectiveInstance = free === 0 ? void 0 : free;
3583
3880
  }
3584
- const sessionName = employeeSessionName(employeeName, exeSession, effectiveInstance);
3585
- if (isEmployeeAlive(sessionName)) {
3586
- const result2 = sendIntercom(sessionName);
3587
- if (result2 === "acknowledged" || result2 === "skipped_exe" || result2 === "debounced" || result2 === "queued") {
3588
- return { status: "intercom_sent", sessionName };
3881
+ if (input2.status === "in_progress") {
3882
+ const tmuxSession = process.env.TMUX_PANE ?? process.env.MY_TMUX_SESSION ?? "unknown";
3883
+ const claim = await client.execute({
3884
+ sql: `UPDATE tasks
3885
+ SET status = 'in_progress', assigned_tmux = ?, updated_at = ?
3886
+ WHERE id = ? AND status = 'open'`,
3887
+ args: [tmuxSession, now, taskId]
3888
+ });
3889
+ if (claim.rowsAffected === 0) {
3890
+ const current = await client.execute({
3891
+ sql: "SELECT status, assigned_tmux FROM tasks WHERE id = ?",
3892
+ args: [taskId]
3893
+ });
3894
+ const cur = current.rows[0];
3895
+ const status = cur?.status ?? "unknown";
3896
+ const claimedBy = cur?.assigned_tmux ? ` (claimed by ${cur.assigned_tmux})` : "";
3897
+ throw new Error(`${TASK_ALREADY_CLAIMED_PREFIX}: task ${taskId} is ${status}${claimedBy}`);
3589
3898
  }
3590
- if (result2 === "delivered") {
3591
- return { status: "intercom_unprocessed", sessionName };
3899
+ try {
3900
+ await writeCheckpoint({
3901
+ taskId,
3902
+ step: "claimed",
3903
+ contextSummary: `Task claimed by session. Transitioning open \u2192 in_progress.`
3904
+ });
3905
+ } catch {
3592
3906
  }
3593
- return { status: "failed", sessionName, error: "intercom delivery failed" };
3594
- }
3595
- const spawnOpts = { ...opts, instance: effectiveInstance };
3596
- const result = spawnEmployee(employeeName, exeSession, projectDir, spawnOpts);
3597
- if (result.error) {
3598
- return { status: "failed", sessionName, error: result.error };
3907
+ return { row, taskFile, now, taskId };
3599
3908
  }
3600
- return { status: "spawned", sessionName };
3601
- }
3602
- function spawnEmployee(employeeName, exeSession, projectDir, opts) {
3603
- const transport = getTransport();
3604
- const sessionName = employeeSessionName(employeeName, exeSession, opts?.instance);
3605
- const instanceLabel = opts?.instance != null && opts.instance > 0 ? `${employeeName}${opts.instance}` : employeeName;
3606
- const logDir = path14.join(os5.homedir(), ".exe-os", "session-logs");
3607
- const logFile = path14.join(logDir, `${instanceLabel}-${Date.now()}.log`);
3608
- if (!existsSync12(logDir)) {
3609
- mkdirSync6(logDir, { recursive: true });
3909
+ if (input2.result) {
3910
+ await client.execute({
3911
+ sql: "UPDATE tasks SET status = ?, result = ?, updated_at = ? WHERE id = ?",
3912
+ args: [input2.status, input2.result, now, taskId]
3913
+ });
3914
+ } else {
3915
+ await client.execute({
3916
+ sql: "UPDATE tasks SET status = ?, updated_at = ? WHERE id = ?",
3917
+ args: [input2.status, now, taskId]
3918
+ });
3610
3919
  }
3611
- transport.kill(sessionName);
3612
- let cleanupSuffix = "";
3613
3920
  try {
3614
- const thisFile = fileURLToPath2(import.meta.url);
3615
- const cleanupScript = path14.join(path14.dirname(thisFile), "..", "bin", "exe-session-cleanup.js");
3616
- if (existsSync12(cleanupScript)) {
3617
- cleanupSuffix = `; ${process.execPath} "${cleanupScript}" "${employeeName}" "${exeSession}"`;
3618
- }
3921
+ await writeCheckpoint({
3922
+ taskId,
3923
+ step: `status_transition:${input2.status}`,
3924
+ contextSummary: input2.result ? `Transitioned to ${input2.status}. Result: ${input2.result.slice(0, 500)}` : `Transitioned to ${input2.status}.`
3925
+ });
3619
3926
  } catch {
3620
3927
  }
3621
- try {
3622
- const claudeJsonPath = path14.join(os5.homedir(), ".claude.json");
3623
- let claudeJson = {};
3624
- try {
3625
- claudeJson = JSON.parse(readFileSync10(claudeJsonPath, "utf8"));
3626
- } catch {
3627
- }
3628
- if (!claudeJson.projects) claudeJson.projects = {};
3629
- const projects = claudeJson.projects;
3630
- const trustDir = opts?.cwd ?? projectDir;
3631
- if (!projects[trustDir]) projects[trustDir] = {};
3632
- projects[trustDir].hasTrustDialogAccepted = true;
3633
- writeFileSync5(claudeJsonPath, JSON.stringify(claudeJson, null, 2) + "\n");
3928
+ return { row, taskFile, now, taskId };
3929
+ }
3930
+ async function deleteTaskCore(taskId, _baseDir) {
3931
+ const client = getClient();
3932
+ const row = await resolveTask(client, taskId);
3933
+ const id = String(row.id);
3934
+ const taskFile = String(row.task_file);
3935
+ const assignedTo = String(row.assigned_to);
3936
+ const assignedBy = String(row.assigned_by);
3937
+ await client.execute({ sql: "DELETE FROM tasks WHERE id = ?", args: [id] });
3938
+ const taskSlug = taskFile.split("/").pop()?.replace(".md", "") ?? "";
3939
+ return { taskFile, assignedTo, assignedBy, taskSlug };
3940
+ }
3941
+ async function ensureArchitectureDoc(baseDir, projectName) {
3942
+ const archPath = path15.join(baseDir, "exe", "ARCHITECTURE.md");
3943
+ try {
3944
+ if (existsSync13(archPath)) return;
3945
+ const template = [
3946
+ `# ${projectName} \u2014 System Architecture`,
3947
+ "",
3948
+ "> Employees: read this before every task. Update it when you change system structure.",
3949
+ `> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
3950
+ "",
3951
+ "## Overview",
3952
+ "",
3953
+ "<!-- Describe what this system does, its main components, and how they connect. -->",
3954
+ "",
3955
+ "## Key Components",
3956
+ "",
3957
+ "<!-- List the major modules, services, or subsystems. -->",
3958
+ "",
3959
+ "## Data Flow",
3960
+ "",
3961
+ "<!-- How does data move through the system? What writes where? -->",
3962
+ "",
3963
+ "## Invariants",
3964
+ "",
3965
+ "<!-- Rules that must never be violated. What breaks if these are wrong? -->",
3966
+ "",
3967
+ "## Dependencies",
3968
+ "",
3969
+ "<!-- What depends on what? If I change X, what else is affected? -->",
3970
+ ""
3971
+ ].join("\n");
3972
+ await writeFile4(archPath, template, "utf-8");
3634
3973
  } catch {
3635
3974
  }
3975
+ }
3976
+ async function ensureGitignoreExe(baseDir) {
3977
+ const gitignorePath = path15.join(baseDir, ".gitignore");
3636
3978
  try {
3637
- const settingsDir = path14.join(os5.homedir(), ".claude", "projects");
3638
- const normalizedKey = (opts?.cwd ?? projectDir).replace(/\//g, "-").replace(/^-/, "");
3639
- const projSettingsDir = path14.join(settingsDir, normalizedKey);
3640
- const settingsPath = path14.join(projSettingsDir, "settings.json");
3641
- let settings = {};
3642
- try {
3643
- settings = JSON.parse(readFileSync10(settingsPath, "utf8"));
3644
- } catch {
3645
- }
3646
- const perms = settings.permissions ?? {};
3647
- const allow = perms.allow ?? [];
3648
- const toolNames = [
3649
- "recall_my_memory",
3650
- "store_memory",
3651
- "create_task",
3652
- "update_task",
3653
- "list_tasks",
3654
- "get_task",
3655
- "ask_team_memory",
3656
- "store_behavior",
3657
- "get_identity",
3658
- "send_message"
3659
- ];
3660
- const requiredTools = expandDualPrefixTools(toolNames);
3661
- let changed = false;
3662
- for (const tool of requiredTools) {
3663
- if (!allow.includes(tool)) {
3664
- allow.push(tool);
3665
- changed = true;
3666
- }
3667
- }
3668
- if (changed) {
3669
- perms.allow = allow;
3670
- settings.permissions = perms;
3671
- mkdirSync6(projSettingsDir, { recursive: true });
3672
- writeFileSync5(settingsPath, JSON.stringify(settings, null, 2) + "\n");
3979
+ if (existsSync13(gitignorePath)) {
3980
+ const content = readFileSync11(gitignorePath, "utf-8");
3981
+ if (/^\/?exe\/?$/m.test(content)) return;
3982
+ await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
3983
+ } else {
3984
+ await writeFile4(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
3673
3985
  }
3674
3986
  } catch {
3675
3987
  }
3676
- const spawnCwd = opts?.cwd ?? projectDir;
3677
- const useExeAgent = !!(opts?.model && opts?.provider);
3678
- const ccProvider = useExeAgent ? DEFAULT_PROVIDER : detectActiveProvider();
3679
- const useBinSymlink = ccProvider !== DEFAULT_PROVIDER;
3680
- let identityFlag = "";
3681
- let behaviorsFlag = "";
3682
- let legacyFallbackWarned = false;
3683
- if (!useExeAgent && !useBinSymlink) {
3684
- const identityPath = path14.join(
3685
- os5.homedir(),
3686
- ".exe-os",
3687
- "identity",
3688
- `${employeeName}.md`
3689
- );
3690
- _resetCcAgentSupportCache();
3691
- const hasAgentFlag = claudeSupportsAgentFlag();
3692
- if (hasAgentFlag) {
3693
- identityFlag = ` --agent ${employeeName}`;
3694
- } else if (existsSync12(identityPath)) {
3695
- identityFlag = ` --append-system-prompt-file ${identityPath}`;
3696
- legacyFallbackWarned = true;
3697
- }
3698
- const behaviorsFile = exportBehaviorsSync(
3699
- employeeName,
3700
- path14.basename(spawnCwd),
3701
- sessionName
3702
- );
3703
- if (behaviorsFile) {
3704
- behaviorsFlag = ` --append-system-prompt-file ${behaviorsFile}`;
3705
- }
3988
+ }
3989
+ var DELEGATION_KEYWORDS, TASK_ALREADY_CLAIMED_PREFIX;
3990
+ var init_tasks_crud = __esm({
3991
+ "src/lib/tasks-crud.ts"() {
3992
+ "use strict";
3993
+ init_database();
3994
+ DELEGATION_KEYWORDS = /parallel|delegate|wave|tom\d*-exe/i;
3995
+ TASK_ALREADY_CLAIMED_PREFIX = "TASK_ALREADY_CLAIMED";
3706
3996
  }
3707
- if (legacyFallbackWarned) {
3997
+ });
3998
+
3999
+ // src/lib/tasks-review.ts
4000
+ var tasks_review_exports = {};
4001
+ __export(tasks_review_exports, {
4002
+ cleanupOrphanedReviews: () => cleanupOrphanedReviews,
4003
+ cleanupReviewFile: () => cleanupReviewFile,
4004
+ countNewPendingReviewsSince: () => countNewPendingReviewsSince,
4005
+ countPendingReviews: () => countPendingReviews,
4006
+ createReviewForCompletedTask: () => createReviewForCompletedTask,
4007
+ getReviewChecklist: () => getReviewChecklist,
4008
+ listPendingReviews: () => listPendingReviews
4009
+ });
4010
+ import path16 from "path";
4011
+ import { existsSync as existsSync14, readdirSync as readdirSync5, unlinkSync as unlinkSync4 } from "fs";
4012
+ async function countPendingReviews() {
4013
+ const client = getClient();
4014
+ const result = await client.execute({
4015
+ sql: "SELECT COUNT(*) as cnt FROM tasks WHERE status = 'needs_review'",
4016
+ args: []
4017
+ });
4018
+ return Number(result.rows[0]?.cnt) || 0;
4019
+ }
4020
+ async function countNewPendingReviewsSince(sinceIso) {
4021
+ const client = getClient();
4022
+ const result = await client.execute({
4023
+ sql: `SELECT COUNT(*) as cnt FROM tasks
4024
+ WHERE status = 'needs_review' AND updated_at > ?`,
4025
+ args: [sinceIso]
4026
+ });
4027
+ return Number(result.rows[0]?.cnt) || 0;
4028
+ }
4029
+ async function listPendingReviews(limit) {
4030
+ const client = getClient();
4031
+ const result = await client.execute({
4032
+ sql: `SELECT title, assigned_to, project_name FROM tasks
4033
+ WHERE status = 'needs_review'
4034
+ ORDER BY priority ASC, created_at DESC LIMIT ?`,
4035
+ args: [limit]
4036
+ });
4037
+ return result.rows;
4038
+ }
4039
+ async function cleanupOrphanedReviews() {
4040
+ const client = getClient();
4041
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4042
+ const r1 = await client.execute({
4043
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
4044
+ WHERE status = 'needs_review'
4045
+ AND assigned_by = 'system'
4046
+ AND title LIKE 'Review:%'
4047
+ AND parent_task_id IN (SELECT id FROM tasks WHERE status IN ('done', 'cancelled'))`,
4048
+ args: [now]
4049
+ });
4050
+ const staleThreshold = new Date(Date.now() - 60 * 60 * 1e3).toISOString();
4051
+ const r2 = await client.execute({
4052
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
4053
+ WHERE status = 'needs_review'
4054
+ AND result IS NOT NULL
4055
+ AND updated_at < ?`,
4056
+ args: [now, staleThreshold]
4057
+ });
4058
+ const total = r1.rowsAffected + r2.rowsAffected;
4059
+ if (total > 0) {
3708
4060
  process.stderr.write(
3709
- `[tmux-routing] claude --agent not supported by installed CC. Falling back to --append-system-prompt-file for ${employeeName}. Upgrade Claude Code to enable native --agent launch.
4061
+ `[cleanup] Closed ${total} orphaned review(s): ${r1.rowsAffected} cascade + ${r2.rowsAffected} stale
3710
4062
  `
3711
4063
  );
3712
4064
  }
3713
- let sessionContextFlag = "";
3714
- try {
3715
- const ctxDir = path14.join(os5.homedir(), ".exe-os", "session-cache");
3716
- mkdirSync6(ctxDir, { recursive: true });
3717
- const ctxFile = path14.join(ctxDir, `session-context-${sessionName}.md`);
3718
- const ctxContent = [
3719
- `## Session Context`,
3720
- `You are running in tmux session: ${sessionName}.`,
3721
- `Your parent exe session is ${exeSession}.`,
3722
- `Your employees (if any) use the -${exeSession} suffix (e.g., tom-${exeSession}).`
3723
- ].join("\n");
3724
- writeFileSync5(ctxFile, ctxContent);
3725
- sessionContextFlag = ` --append-system-prompt-file ${ctxFile}`;
3726
- } catch {
3727
- }
3728
- let envPrefix = `EXE_SESSION=${exeSession} EXE_SESSION_NAME=${sessionName}`;
3729
- if (ccProvider !== DEFAULT_PROVIDER) {
3730
- const cfg = PROVIDER_TABLE[ccProvider];
3731
- if (cfg?.apiKeyEnv) {
3732
- const keyVal = process.env[cfg.apiKeyEnv];
3733
- if (keyVal) {
3734
- envPrefix = `${envPrefix} ${cfg.apiKeyEnv}=${keyVal}`;
3735
- }
3736
- }
4065
+ return total;
4066
+ }
4067
+ function getReviewChecklist(role, agent, taskSlug) {
4068
+ const roleLower = role.toLowerCase();
4069
+ if (roleLower.includes("engineer") || roleLower === "principal engineer") {
4070
+ return {
4071
+ lens: "Code Quality (Engineer)",
4072
+ checklist: [
4073
+ "1. Do all tests pass? Any new tests needed?",
4074
+ "2. Is the code clean \u2014 no dead code, no TODOs left?",
4075
+ "3. Does it follow existing patterns and conventions in the codebase?",
4076
+ "4. Any regressions in the test suite?"
4077
+ ]
4078
+ };
3737
4079
  }
3738
- let spawnCommand;
3739
- if (useExeAgent) {
3740
- spawnCommand = `${envPrefix} exe-agent --employee ${employeeName} --model ${opts.model} --provider ${opts.provider}${cleanupSuffix}`;
3741
- } else if (useBinSymlink) {
3742
- const binName = `${employeeName}-${ccProvider}`;
3743
- process.stderr.write(
3744
- `[tmux-routing] provider cascade: ${ccProvider} \u2192 spawning ${binName}
3745
- `
3746
- );
3747
- spawnCommand = `${envPrefix} ${binName}${cleanupSuffix}`;
3748
- } else {
3749
- spawnCommand = `${envPrefix} claude --dangerously-skip-permissions${identityFlag}${behaviorsFlag}${sessionContextFlag}${cleanupSuffix}`;
4080
+ if (roleLower === "cto" || roleLower.includes("architect")) {
4081
+ return {
4082
+ lens: "Architecture (CTO)",
4083
+ checklist: [
4084
+ "1. Does this fit the existing architecture? Consistent with ARCHITECTURE.md?",
4085
+ "2. Is it backward compatible? Any breaking changes?",
4086
+ "3. Does it introduce technical debt? Is that debt justified?",
4087
+ "4. Security implications? Any new attack surface?",
4088
+ "5. Does it scale? Performance considerations?",
4089
+ "6. Coordination: does this affect other employees' work or other projects?"
4090
+ ]
4091
+ };
3750
4092
  }
3751
- const spawnResult = transport.spawn(sessionName, {
3752
- cwd: spawnCwd,
3753
- command: spawnCommand
3754
- });
3755
- if (spawnResult.error) {
3756
- releaseSpawnLock2(sessionName);
3757
- return { sessionName, error: `tmux new-session failed: ${spawnResult.error}` };
4093
+ if (roleLower === "coo" || roleLower.includes("operations")) {
4094
+ return {
4095
+ lens: "Strategic (COO)",
4096
+ checklist: [
4097
+ "1. Does this serve the project mission?",
4098
+ "2. Is this the right work at the right time?",
4099
+ "3. Does the architectural assessment make sense for the business?",
4100
+ "4. Any cross-project implications?"
4101
+ ]
4102
+ };
3758
4103
  }
3759
- transport.pipeLog(sessionName, logFile);
3760
- try {
3761
- const mySession = getMySession();
3762
- const dispatchInfo = path14.join(SESSION_CACHE, `dispatch-info-${sessionName}.json`);
3763
- writeFileSync5(dispatchInfo, JSON.stringify({
3764
- dispatchedBy: mySession,
3765
- rootExe: exeSession,
3766
- provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
3767
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
3768
- }));
4104
+ return {
4105
+ lens: "General",
4106
+ checklist: [
4107
+ "1. Read the original task's acceptance criteria",
4108
+ `2. Check git log for related commits: \`git log --oneline --author-date-order -10\``,
4109
+ "3. Verify code changes match requirements",
4110
+ "4. Check if tests were added/updated",
4111
+ `5. Look for output files in exe/output/${agent}-${taskSlug}*`
4112
+ ]
4113
+ };
4114
+ }
4115
+ async function createReviewForCompletedTask(row, result, _baseDir, now) {
4116
+ const taskFile = String(row.task_file);
4117
+ if (String(row.assigned_to) === "exe") return;
4118
+ if (String(row.title).startsWith("Review:")) return;
4119
+ const fileName = taskFile.split("/").pop() ?? "";
4120
+ if (fileName.startsWith("review-") && String(row.assigned_by) === "system") return;
4121
+ if (fileName.startsWith("review-") && String(row.assigned_to) === "system") return;
4122
+ const client = getClient();
4123
+ const agent = String(row.assigned_to);
4124
+ const reviewer = String(row.reviewer || row.assigned_by) || "exe";
4125
+ let reviewerRole = "unknown";
4126
+ try {
4127
+ const employees = await loadEmployees();
4128
+ const emp = getEmployee(employees, reviewer);
4129
+ if (emp) reviewerRole = emp.role;
3769
4130
  } catch {
3770
4131
  }
3771
- let booted = false;
3772
- for (let i = 0; i < 30; i++) {
4132
+ const taskTitle = String(row.title);
4133
+ const taskSlug = taskFile.split("/").pop()?.replace(".md", "") ?? "unknown";
4134
+ const { lens, checklist } = getReviewChecklist(reviewerRole, agent, taskSlug);
4135
+ const reviewSlug = `review-${agent}-${taskSlug}`;
4136
+ const reviewFile = `exe/${reviewer}/${reviewSlug}.md`;
4137
+ await client.execute({
4138
+ sql: "DELETE FROM tasks WHERE task_file = ?",
4139
+ args: [reviewFile]
4140
+ });
4141
+ process.stderr.write(
4142
+ `[review] Creating review for "${taskTitle}" \u2192 assigned to ${reviewer} (${reviewerRole})
4143
+ `
4144
+ );
4145
+ const reviewContext = [
4146
+ `${agent} marked this task as done:`,
4147
+ `- Original task: ${taskFile}`,
4148
+ `- Result: ${result ?? "No result summary provided"}`,
4149
+ "",
4150
+ `## Review lens: ${lens}`,
4151
+ `You are reviewing as **${reviewer}** (${reviewerRole}).`,
4152
+ "",
4153
+ "## Review checklist",
4154
+ ...checklist,
4155
+ "",
4156
+ "## Verdict",
4157
+ "After review, update this task:",
4158
+ "- **Approved:** mark this review task as done",
4159
+ "- **Needs work:** re-open the original task with notes, mark this review as done"
4160
+ ].join("\n");
4161
+ const originalTaskId = String(row.id);
4162
+ const reviewTask = await createTaskCore({
4163
+ title: `Review: ${agent} completed "${taskTitle}"`,
4164
+ assignedTo: reviewer,
4165
+ assignedBy: "system",
4166
+ projectName: String(row.project_name),
4167
+ priority: "p1",
4168
+ context: reviewContext,
4169
+ taskFile: reviewFile,
4170
+ parentTaskId: originalTaskId,
4171
+ skipDispatch: true
4172
+ });
4173
+ const reviewId = reviewTask.id;
4174
+ orgBus.emit({
4175
+ type: "review_created",
4176
+ reviewId,
4177
+ employee: agent,
4178
+ reviewer,
4179
+ timestamp: now
4180
+ });
4181
+ await writeNotification({
4182
+ agentId: agent,
4183
+ agentRole: String(row.assigned_to),
4184
+ event: "task_complete",
4185
+ project: String(row.project_name),
4186
+ summary: `completed "${taskTitle}" \u2014 review task created`,
4187
+ taskFile: reviewFile
4188
+ });
4189
+ const originalPriority = String(row.priority).toLowerCase();
4190
+ const autoApprove = originalPriority === "p2" && result?.toLowerCase().includes("tests pass");
4191
+ if (!autoApprove) {
3773
4192
  try {
3774
- execSync7("sleep 0.5");
4193
+ const key = getSessionKey();
4194
+ const exeSession = getParentExe(key);
4195
+ if (exeSession) {
4196
+ sendIntercom(exeSession);
4197
+ }
3775
4198
  } catch {
3776
4199
  }
3777
- try {
3778
- const pane = transport.capturePane(sessionName);
3779
- if (useExeAgent) {
3780
- if (pane.includes("[exe-agent]") || pane.includes("online")) {
3781
- booted = true;
3782
- break;
4200
+ }
4201
+ if (autoApprove) {
4202
+ process.stderr.write(
4203
+ `[review] Auto-approving review for "${taskTitle}" (P2 + tests pass)
4204
+ `
4205
+ );
4206
+ await client.execute({
4207
+ sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ?",
4208
+ args: [now, reviewId]
4209
+ });
4210
+ }
4211
+ }
4212
+ async function cleanupReviewFile(row, taskFile, _baseDir) {
4213
+ if (String(row.assigned_by) !== "system" || !taskFile.includes("review-")) return;
4214
+ try {
4215
+ const client = getClient();
4216
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4217
+ const parentId = row.parent_task_id ? String(row.parent_task_id) : null;
4218
+ if (parentId) {
4219
+ const result = await client.execute({
4220
+ sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ? AND status = 'needs_review'",
4221
+ args: [now, parentId]
4222
+ });
4223
+ if (result.rowsAffected > 0) {
4224
+ process.stderr.write(
4225
+ `[review-cleanup] Cascaded original task to done via parent_task_id: ${parentId}
4226
+ `
4227
+ );
4228
+ }
4229
+ } else {
4230
+ const fileName = taskFile.split("/").pop() ?? "";
4231
+ const reviewPrefix = fileName.replace(".md", "");
4232
+ const parts = reviewPrefix.split("-");
4233
+ if (parts.length >= 3 && parts[0] === "review") {
4234
+ const agent = parts[1];
4235
+ const slug = parts.slice(2).join("-");
4236
+ const originalTaskFile = `exe/${agent}/${slug}.md`;
4237
+ const result = await client.execute({
4238
+ sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE task_file = ? AND status = 'needs_review'",
4239
+ args: [now, originalTaskFile]
4240
+ });
4241
+ if (result.rowsAffected > 0) {
4242
+ process.stderr.write(
4243
+ `[review-cleanup] Cascaded original task to done (legacy path): ${originalTaskFile}
4244
+ `
4245
+ );
3783
4246
  }
3784
- } else {
3785
- if (pane.includes("Claude Code") || pane.includes("\u276F")) {
3786
- booted = true;
3787
- break;
4247
+ }
4248
+ }
4249
+ } catch (err) {
4250
+ process.stderr.write(
4251
+ `[review-cleanup] Failed to cascade original task: ${err instanceof Error ? err.message : String(err)}
4252
+ `
4253
+ );
4254
+ }
4255
+ try {
4256
+ const cacheDir = path16.join(EXE_AI_DIR, "session-cache");
4257
+ if (existsSync14(cacheDir)) {
4258
+ for (const f of readdirSync5(cacheDir)) {
4259
+ if (f.startsWith("review-notified-")) {
4260
+ unlinkSync4(path16.join(cacheDir, f));
3788
4261
  }
3789
4262
  }
3790
- } catch {
3791
4263
  }
4264
+ } catch {
3792
4265
  }
3793
- if (!booted) {
3794
- releaseSpawnLock2(sessionName);
3795
- return { sessionName, error: `${useExeAgent ? "exe-agent" : "claude"} did not boot within 15s` };
4266
+ }
4267
+ var init_tasks_review = __esm({
4268
+ "src/lib/tasks-review.ts"() {
4269
+ "use strict";
4270
+ init_database();
4271
+ init_config();
4272
+ init_employees();
4273
+ init_notifications();
4274
+ init_tasks_crud();
4275
+ init_tmux_routing();
4276
+ init_session_key();
4277
+ init_state_bus();
3796
4278
  }
3797
- if (!useExeAgent) {
3798
- try {
3799
- transport.sendKeys(sessionName, `/exe-call ${employeeName}`);
3800
- } catch {
4279
+ });
4280
+
4281
+ // src/lib/tasks-chain.ts
4282
+ import path17 from "path";
4283
+ import { readFile as readFile4, writeFile as writeFile5 } from "fs/promises";
4284
+ async function cascadeUnblock(taskId, baseDir, now) {
4285
+ const client = getClient();
4286
+ const unblocked = await client.execute({
4287
+ sql: `UPDATE tasks SET status = 'open', blocked_by = NULL, updated_at = ?
4288
+ WHERE blocked_by = ? AND status = 'blocked'`,
4289
+ args: [now, taskId]
4290
+ });
4291
+ if (baseDir && unblocked.rowsAffected > 0) {
4292
+ const unblockedRows = await client.execute({
4293
+ sql: `SELECT task_file FROM tasks WHERE blocked_by IS NULL AND updated_at = ?`,
4294
+ args: [now]
4295
+ });
4296
+ for (const ur of unblockedRows.rows) {
4297
+ try {
4298
+ const ubFile = path17.join(baseDir, String(ur.task_file));
4299
+ let ubContent = await readFile4(ubFile, "utf-8");
4300
+ ubContent = ubContent.replace(/\*\*Status:\*\* blocked/, "**Status:** open");
4301
+ ubContent = ubContent.replace(/\n\*\*Blocked by:\*\*.*\n/, "\n");
4302
+ await writeFile5(ubFile, ubContent, "utf-8");
4303
+ } catch {
4304
+ }
3801
4305
  }
3802
4306
  }
3803
- registerSession({
3804
- windowName: sessionName,
3805
- agentId: employeeName,
3806
- projectDir: spawnCwd,
3807
- parentExe: exeSession,
3808
- pid: 0,
3809
- registeredAt: (/* @__PURE__ */ new Date()).toISOString()
4307
+ }
4308
+ async function findNextTask(assignedTo) {
4309
+ const client = getClient();
4310
+ const nextResult = await client.execute({
4311
+ sql: `SELECT title, task_file, priority FROM tasks
4312
+ WHERE assigned_to = ? AND status = 'open'
4313
+ ORDER BY priority ASC, created_at ASC
4314
+ LIMIT 1`,
4315
+ args: [assignedTo]
3810
4316
  });
3811
- releaseSpawnLock2(sessionName);
3812
- return { sessionName };
4317
+ if (nextResult.rows.length === 1) {
4318
+ const nr = nextResult.rows[0];
4319
+ return {
4320
+ title: String(nr.title),
4321
+ priority: String(nr.priority),
4322
+ taskFile: String(nr.task_file)
4323
+ };
4324
+ }
4325
+ return void 0;
3813
4326
  }
3814
- var SPAWN_LOCK_DIR, SESSION_CACHE, BEHAVIORS_EXPORT_TIMEOUT_MS, INTERCOM_DEBOUNCE_MS, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS, BUSY_PATTERN;
3815
- var init_tmux_routing = __esm({
3816
- "src/lib/tmux-routing.ts"() {
4327
+ async function checkSubtaskCompletion(parentTaskId, projectName) {
4328
+ const client = getClient();
4329
+ const remaining = await client.execute({
4330
+ sql: `SELECT COUNT(*) as cnt FROM tasks
4331
+ WHERE parent_task_id = ? AND status NOT IN ('done', 'cancelled')`,
4332
+ args: [parentTaskId]
4333
+ });
4334
+ const cnt = Number(remaining.rows[0]?.cnt ?? 1);
4335
+ if (cnt === 0) {
4336
+ const parentRow = await client.execute({
4337
+ sql: `SELECT assigned_to, title, task_file, project_name FROM tasks WHERE id = ?`,
4338
+ args: [parentTaskId]
4339
+ });
4340
+ if (parentRow.rows.length === 1) {
4341
+ const pr = parentRow.rows[0];
4342
+ const parentProject = pr.project_name == null ? projectName : String(pr.project_name);
4343
+ await writeNotification({
4344
+ agentId: String(pr.assigned_to),
4345
+ agentRole: "system",
4346
+ event: "subtasks_complete",
4347
+ project: parentProject,
4348
+ summary: `All subtasks complete for "${String(pr.title)}" \u2014 ready for rollup review`,
4349
+ taskFile: String(pr.task_file)
4350
+ });
4351
+ }
4352
+ }
4353
+ }
4354
+ var init_tasks_chain = __esm({
4355
+ "src/lib/tasks-chain.ts"() {
3817
4356
  "use strict";
3818
- init_session_registry();
3819
- init_session_key();
3820
- init_transport();
3821
- init_cc_agent_support();
3822
- init_mcp_prefix();
3823
- init_provider_table();
3824
- init_intercom_queue();
3825
- init_plan_limits();
3826
- SPAWN_LOCK_DIR = path14.join(os5.homedir(), ".exe-os", "spawn-locks");
3827
- SESSION_CACHE = path14.join(os5.homedir(), ".exe-os", "session-cache");
3828
- BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
3829
- INTERCOM_DEBOUNCE_MS = 3e4;
3830
- INTERCOM_LOG2 = path14.join(os5.homedir(), ".exe-os", "intercom.log");
3831
- DEBOUNCE_FILE = path14.join(SESSION_CACHE, "intercom-debounce.json");
3832
- DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
3833
- BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
4357
+ init_database();
4358
+ init_notifications();
3834
4359
  }
3835
4360
  });
3836
4361
 
3837
- // src/lib/messaging.ts
3838
- var messaging_exports = {};
3839
- __export(messaging_exports, {
3840
- deliverLocalMessage: () => deliverLocalMessage,
3841
- getFailedMessages: () => getFailedMessages,
3842
- getMessageStatus: () => getMessageStatus,
3843
- getPendingMessages: () => getPendingMessages,
3844
- getReadMessages: () => getReadMessages,
3845
- getUnacknowledgedMessages: () => getUnacknowledgedMessages,
3846
- markAcknowledged: () => markAcknowledged,
3847
- markFailed: () => markFailed,
3848
- markProcessed: () => markProcessed,
3849
- markRead: () => markRead,
3850
- retryPendingMessages: () => retryPendingMessages,
3851
- sendMessage: () => sendMessage,
3852
- setWsClientSend: () => setWsClientSend
4362
+ // src/lib/session-scope.ts
4363
+ var session_scope_exports = {};
4364
+ __export(session_scope_exports, {
4365
+ assertSessionScope: () => assertSessionScope,
4366
+ findSessionForProject: () => findSessionForProject,
4367
+ getSessionProject: () => getSessionProject
3853
4368
  });
3854
- import crypto3 from "crypto";
3855
- function generateUlid() {
3856
- const timestamp = Date.now().toString(36).padStart(10, "0");
3857
- const random = crypto3.randomBytes(10).toString("hex").slice(0, 16);
3858
- return (timestamp + random).toUpperCase();
4369
+ function getSessionProject(sessionName) {
4370
+ const sessions = listSessions();
4371
+ const entry = sessions.find((s) => s.windowName === sessionName);
4372
+ if (!entry) return null;
4373
+ const parts = entry.projectDir.split("/").filter(Boolean);
4374
+ return parts[parts.length - 1] ?? null;
3859
4375
  }
3860
- function rowToMessage(row) {
3861
- return {
3862
- id: row.id,
3863
- fromAgent: row.from_agent,
3864
- fromDevice: row.from_device,
3865
- targetAgent: row.target_agent,
3866
- targetProject: row.target_project ?? null,
3867
- targetDevice: row.target_device,
3868
- content: row.content,
3869
- priority: row.priority ?? "normal",
3870
- status: row.status ?? "pending",
3871
- serverSeq: row.server_seq != null ? Number(row.server_seq) : null,
3872
- retryCount: Number(row.retry_count ?? 0),
3873
- createdAt: row.created_at,
3874
- deliveredAt: row.delivered_at ?? null,
3875
- processedAt: row.processed_at ?? null,
3876
- failedAt: row.failed_at ?? null,
3877
- failureReason: row.failure_reason ?? null
3878
- };
4376
+ function findSessionForProject(projectName) {
4377
+ const sessions = listSessions();
4378
+ for (const s of sessions) {
4379
+ const proj = s.projectDir.split("/").filter(Boolean).pop();
4380
+ if (proj === projectName && s.agentId === "exe") return s;
4381
+ }
4382
+ return null;
3879
4383
  }
3880
- async function sendMessage(input2) {
3881
- const client = getClient();
3882
- const id = generateUlid();
3883
- const now = (/* @__PURE__ */ new Date()).toISOString();
3884
- const targetDevice = input2.targetDevice ?? "local";
3885
- await client.execute({
3886
- sql: `INSERT INTO messages (id, from_agent, from_device, target_agent, target_project, target_device, content, priority, status, created_at)
3887
- VALUES (?, ?, 'local', ?, ?, ?, ?, ?, 'pending', ?)`,
3888
- args: [
3889
- id,
3890
- input2.fromAgent,
3891
- input2.targetAgent,
3892
- input2.targetProject ?? null,
3893
- targetDevice,
3894
- input2.content,
3895
- input2.priority ?? "normal",
3896
- now
3897
- ]
3898
- });
4384
+ function assertSessionScope(actionType, targetProject) {
3899
4385
  try {
3900
- if (targetDevice !== "local") {
3901
- await deliverCrossMachineMessage(id, targetDevice);
3902
- } else {
3903
- await deliverLocalMessage(id);
4386
+ const currentProject = getProjectName();
4387
+ const exeSession = resolveExeSession();
4388
+ if (!exeSession) {
4389
+ return { allowed: true, reason: "no_session" };
4390
+ }
4391
+ if (currentProject === targetProject) {
4392
+ return {
4393
+ allowed: true,
4394
+ reason: "same_session",
4395
+ currentProject,
4396
+ targetProject
4397
+ };
3904
4398
  }
4399
+ process.stderr.write(
4400
+ `[session-scope] BLOCKED cross-project ${actionType}: session project="${currentProject}" \u2260 target project="${targetProject}"
4401
+ `
4402
+ );
4403
+ return {
4404
+ allowed: false,
4405
+ reason: "cross_session_denied",
4406
+ currentProject,
4407
+ targetProject,
4408
+ targetSession: findSessionForProject(targetProject)?.windowName
4409
+ };
3905
4410
  } catch {
4411
+ return { allowed: true, reason: "no_session" };
3906
4412
  }
3907
- const result = await client.execute({
3908
- sql: "SELECT * FROM messages WHERE id = ?",
3909
- args: [id]
3910
- });
3911
- return rowToMessage(result.rows[0]);
3912
4413
  }
3913
- function setWsClientSend(fn) {
3914
- _wsClientSend = fn;
3915
- }
3916
- async function deliverCrossMachineMessage(messageId, targetDevice) {
3917
- const client = getClient();
3918
- const result = await client.execute({
3919
- sql: "SELECT * FROM messages WHERE id = ?",
3920
- args: [messageId]
3921
- });
3922
- if (result.rows.length === 0) return false;
3923
- const msg = rowToMessage(result.rows[0]);
3924
- if (msg.status !== "pending") return false;
3925
- if (!_wsClientSend) {
3926
- return false;
4414
+ var init_session_scope = __esm({
4415
+ "src/lib/session-scope.ts"() {
4416
+ "use strict";
4417
+ init_session_registry();
4418
+ init_project_name();
4419
+ init_tmux_routing();
3927
4420
  }
3928
- const payload = JSON.stringify({
3929
- id: msg.id,
3930
- fromAgent: msg.fromAgent,
3931
- targetAgent: msg.targetAgent,
3932
- targetProject: msg.targetProject,
3933
- content: msg.content,
3934
- priority: msg.priority,
3935
- createdAt: msg.createdAt
3936
- });
3937
- const sent = _wsClientSend(targetDevice, payload);
3938
- if (sent) {
3939
- await client.execute({
3940
- sql: "UPDATE messages SET status = 'synced' WHERE id = ?",
3941
- args: [messageId]
3942
- });
3943
- return true;
4421
+ });
4422
+
4423
+ // src/lib/tasks-notify.ts
4424
+ async function dispatchTaskToEmployee(input2) {
4425
+ if (input2.assignedTo === "exe") return { dispatched: "skipped" };
4426
+ let crossProject = false;
4427
+ if (input2.projectName) {
4428
+ try {
4429
+ const { assertSessionScope: assertSessionScope2 } = (init_session_scope(), __toCommonJS(session_scope_exports));
4430
+ const check = assertSessionScope2("dispatch_task", input2.projectName);
4431
+ if (check.reason === "cross_session_denied") {
4432
+ crossProject = true;
4433
+ return { dispatched: "skipped", crossProject: true };
4434
+ }
4435
+ } catch {
4436
+ }
3944
4437
  }
3945
- return false;
3946
- }
3947
- async function deliverLocalMessage(messageId) {
3948
- const client = getClient();
3949
- const result = await client.execute({
3950
- sql: "SELECT * FROM messages WHERE id = ?",
3951
- args: [messageId]
3952
- });
3953
- if (result.rows.length === 0) return false;
3954
- const msg = rowToMessage(result.rows[0]);
3955
- if (msg.status !== "pending") return false;
3956
- const targetAgent = msg.targetAgent;
3957
- const now = (/* @__PURE__ */ new Date()).toISOString();
3958
4438
  try {
4439
+ const transport = getTransport();
3959
4440
  const exeSession = resolveExeSession();
3960
- if (!exeSession) {
3961
- throw new Error("No exe session found");
3962
- }
3963
- const ensureResult = ensureEmployee(targetAgent, exeSession, process.cwd());
3964
- if (ensureResult.status === "failed") {
3965
- throw new Error(ensureResult.error ?? "ensureEmployee failed");
3966
- }
3967
- await client.execute({
3968
- sql: "UPDATE messages SET status = 'delivered', delivered_at = ? WHERE id = ?",
3969
- args: [now, messageId]
3970
- });
3971
- return true;
3972
- } catch {
3973
- const newRetryCount = msg.retryCount + 1;
3974
- if (newRetryCount >= MAX_RETRIES3) {
3975
- await markFailed(messageId, "session unavailable after 10 retries");
4441
+ if (!exeSession) return { dispatched: "session_missing" };
4442
+ const sessionName = employeeSessionName(input2.assignedTo, exeSession);
4443
+ if (transport.isAlive(sessionName)) {
4444
+ const result = sendIntercom(sessionName);
4445
+ const dispatched = result === "acknowledged" || result === "debounced" || result === "queued" ? "verified" : result === "delivered" ? "sent_unverified" : "session_dead";
4446
+ return { dispatched, session: sessionName, crossProject };
3976
4447
  } else {
3977
- await client.execute({
3978
- sql: "UPDATE messages SET retry_count = ? WHERE id = ?",
3979
- args: [newRetryCount, messageId]
4448
+ const projectDir = input2.projectDir ?? process.cwd();
4449
+ const result = ensureEmployee(input2.assignedTo, exeSession, projectDir, {
4450
+ autoInstance: isMultiInstance(input2.assignedTo)
3980
4451
  });
4452
+ if (result.status === "failed") {
4453
+ process.stderr.write(
4454
+ `[dispatch] Failed to spawn ${input2.assignedTo}: ${result.error}
4455
+ `
4456
+ );
4457
+ return { dispatched: "session_missing" };
4458
+ }
4459
+ return { dispatched: "spawned", session: result.sessionName, crossProject };
3981
4460
  }
3982
- return false;
4461
+ } catch {
4462
+ return { dispatched: "session_missing" };
3983
4463
  }
3984
4464
  }
3985
- async function getPendingMessages(targetAgent) {
3986
- const client = getClient();
3987
- const result = await client.execute({
3988
- sql: `SELECT * FROM messages
3989
- WHERE target_agent = ? AND status IN ('pending', 'delivered')
3990
- ORDER BY id`,
3991
- args: [targetAgent]
3992
- });
3993
- return result.rows.map((row) => rowToMessage(row));
4465
+ function notifyTaskDone() {
4466
+ try {
4467
+ const key = getSessionKey();
4468
+ if (key && !process.env.VITEST) notifyParentExe(key);
4469
+ } catch {
4470
+ }
3994
4471
  }
3995
- async function markRead(messageId) {
4472
+ async function markTaskNotificationsRead(taskFile) {
4473
+ try {
4474
+ await markAsReadByTaskFile(taskFile);
4475
+ } catch {
4476
+ }
4477
+ }
4478
+ var init_tasks_notify = __esm({
4479
+ "src/lib/tasks-notify.ts"() {
4480
+ "use strict";
4481
+ init_tmux_routing();
4482
+ init_session_key();
4483
+ init_notifications();
4484
+ init_transport();
4485
+ init_employees();
4486
+ }
4487
+ });
4488
+
4489
+ // src/lib/behaviors.ts
4490
+ import crypto6 from "crypto";
4491
+ async function storeBehavior(opts) {
3996
4492
  const client = getClient();
4493
+ const id = crypto6.randomUUID();
4494
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3997
4495
  await client.execute({
3998
- sql: "UPDATE messages SET status = 'read' WHERE id = ? AND status IN ('pending', 'delivered')",
3999
- args: [messageId]
4496
+ sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, priority, content, active, created_at, updated_at)
4497
+ VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)`,
4498
+ args: [id, opts.agentId, opts.projectName ?? null, opts.domain ?? null, opts.priority ?? "p1", opts.content, now, now]
4000
4499
  });
4500
+ return id;
4001
4501
  }
4002
- async function markAcknowledged(messageId) {
4502
+ var init_behaviors = __esm({
4503
+ "src/lib/behaviors.ts"() {
4504
+ "use strict";
4505
+ init_database();
4506
+ }
4507
+ });
4508
+
4509
+ // src/lib/skill-learning.ts
4510
+ var skill_learning_exports = {};
4511
+ __export(skill_learning_exports, {
4512
+ captureAndLearn: () => captureAndLearn,
4513
+ captureTrajectory: () => captureTrajectory,
4514
+ editDistance: () => editDistance,
4515
+ extractSkill: () => extractSkill,
4516
+ extractTrajectory: () => extractTrajectory,
4517
+ findSimilarTrajectories: () => findSimilarTrajectories,
4518
+ hashSignature: () => hashSignature,
4519
+ storeTrajectory: () => storeTrajectory,
4520
+ sweepTrajectories: () => sweepTrajectories
4521
+ });
4522
+ import crypto7 from "crypto";
4523
+ async function extractTrajectory(taskId, agentId) {
4003
4524
  const client = getClient();
4004
- await client.execute({
4005
- sql: "UPDATE messages SET status = 'acknowledged', processed_at = ? WHERE id = ? AND status = 'read'",
4006
- args: [(/* @__PURE__ */ new Date()).toISOString(), messageId]
4525
+ const result = await client.execute({
4526
+ sql: `SELECT tool_name, raw_text
4527
+ FROM memories
4528
+ WHERE task_id = ? AND agent_id = ?
4529
+ ORDER BY timestamp ASC`,
4530
+ args: [taskId, agentId]
4531
+ });
4532
+ if (result.rows.length === 0) return [];
4533
+ const rawTools = result.rows.map((r) => {
4534
+ const toolName = String(r.tool_name);
4535
+ if (toolName === "Bash") {
4536
+ const text = String(r.raw_text);
4537
+ const cmdMatch = text.match(/(?:command|Command).*?[:\s]+"?(\w+)/);
4538
+ return cmdMatch ? `Bash:${cmdMatch[1]}` : "Bash";
4539
+ }
4540
+ return toolName;
4007
4541
  });
4542
+ const signature = [];
4543
+ for (const tool of rawTools) {
4544
+ if (signature.length === 0 || signature[signature.length - 1] !== tool) {
4545
+ signature.push(tool);
4546
+ }
4547
+ }
4548
+ return signature;
4008
4549
  }
4009
- async function markProcessed(messageId) {
4550
+ function hashSignature(signature) {
4551
+ return crypto7.createHash("sha256").update(signature.join("|")).digest("hex").slice(0, 16);
4552
+ }
4553
+ async function storeTrajectory(opts) {
4010
4554
  const client = getClient();
4555
+ const id = crypto7.randomUUID();
4556
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4557
+ const signatureHash = hashSignature(opts.signature);
4011
4558
  await client.execute({
4012
- sql: "UPDATE messages SET status = 'processed', processed_at = ? WHERE id = ?",
4013
- args: [(/* @__PURE__ */ new Date()).toISOString(), messageId]
4559
+ sql: `INSERT INTO trajectories (id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at)
4560
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
4561
+ args: [
4562
+ id,
4563
+ opts.taskId,
4564
+ opts.agentId,
4565
+ opts.projectName,
4566
+ opts.taskTitle,
4567
+ JSON.stringify(opts.signature),
4568
+ signatureHash,
4569
+ opts.signature.length,
4570
+ now
4571
+ ]
4014
4572
  });
4573
+ return id;
4015
4574
  }
4016
- async function getMessageStatus(messageId) {
4575
+ async function findSimilarTrajectories(signature, threshold = DEFAULT_SKILL_THRESHOLD) {
4017
4576
  const client = getClient();
4577
+ const hash = hashSignature(signature);
4018
4578
  const result = await client.execute({
4019
- sql: "SELECT status FROM messages WHERE id = ?",
4020
- args: [messageId]
4579
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
4580
+ FROM trajectories
4581
+ WHERE signature_hash = ?
4582
+ ORDER BY created_at DESC
4583
+ LIMIT 20`,
4584
+ args: [hash]
4021
4585
  });
4022
- return result.rows[0]?.status ?? null;
4023
- }
4024
- async function getUnacknowledgedMessages(targetAgent) {
4025
- const client = getClient();
4026
- const result = await client.execute({
4027
- sql: `SELECT * FROM messages
4028
- WHERE target_agent = ? AND status IN ('pending', 'delivered', 'read')
4029
- ORDER BY id`,
4030
- args: [targetAgent]
4586
+ const mapRow = (r) => ({
4587
+ id: String(r.id),
4588
+ taskId: String(r.task_id),
4589
+ agentId: String(r.agent_id),
4590
+ projectName: String(r.project_name),
4591
+ taskTitle: String(r.task_title),
4592
+ signature: JSON.parse(String(r.signature)),
4593
+ signatureHash: String(r.signature_hash),
4594
+ toolCount: Number(r.tool_count),
4595
+ skillId: r.skill_id ? String(r.skill_id) : null,
4596
+ createdAt: String(r.created_at)
4031
4597
  });
4032
- return result.rows.map((row) => rowToMessage(row));
4033
- }
4034
- async function getReadMessages(targetAgent) {
4035
- const client = getClient();
4036
- const result = await client.execute({
4037
- sql: "SELECT * FROM messages WHERE target_agent = ? AND status = 'read' ORDER BY id",
4038
- args: [targetAgent]
4598
+ const matches = result.rows.map(mapRow);
4599
+ if (matches.length >= threshold) return matches;
4600
+ const nearResult = await client.execute({
4601
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
4602
+ FROM trajectories
4603
+ WHERE tool_count BETWEEN ? AND ?
4604
+ AND signature_hash != ?
4605
+ ORDER BY created_at DESC
4606
+ LIMIT 50`,
4607
+ args: [
4608
+ Math.max(1, signature.length - 3),
4609
+ signature.length + 3,
4610
+ hash
4611
+ ]
4039
4612
  });
4040
- return result.rows.map((row) => rowToMessage(row));
4613
+ for (const r of nearResult.rows) {
4614
+ const candidateSig = JSON.parse(String(r.signature));
4615
+ if (editDistance(signature, candidateSig) <= 2) {
4616
+ matches.push(mapRow(r));
4617
+ }
4618
+ }
4619
+ return matches;
4041
4620
  }
4042
- async function markFailed(messageId, reason) {
4043
- const client = getClient();
4044
- await client.execute({
4045
- sql: "UPDATE messages SET status = 'failed', failed_at = ?, failure_reason = ? WHERE id = ?",
4046
- args: [(/* @__PURE__ */ new Date()).toISOString(), reason, messageId]
4621
+ async function captureTrajectory(opts) {
4622
+ const signature = await extractTrajectory(opts.taskId, opts.agentId);
4623
+ if (signature.length < 3) {
4624
+ return { trajectoryId: "", similarCount: 0, similar: [] };
4625
+ }
4626
+ const trajectoryId = await storeTrajectory({
4627
+ taskId: opts.taskId,
4628
+ agentId: opts.agentId,
4629
+ projectName: opts.projectName,
4630
+ taskTitle: opts.taskTitle,
4631
+ signature
4047
4632
  });
4048
- }
4049
- async function getFailedMessages() {
4050
- const client = getClient();
4051
- const result = await client.execute({
4052
- sql: "SELECT * FROM messages WHERE status = 'failed' ORDER BY created_at DESC",
4053
- args: []
4633
+ const similar = await findSimilarTrajectories(
4634
+ signature,
4635
+ opts.skillThreshold ?? DEFAULT_SKILL_THRESHOLD
4636
+ );
4637
+ return { trajectoryId, similarCount: similar.length, similar };
4638
+ }
4639
+ function buildExtractionPrompt(trajectories) {
4640
+ const items = trajectories.map((t, i) => {
4641
+ const sig = t.signature.join(" \u2192 ");
4642
+ return `Task ${i + 1}: "${t.taskTitle}" (${t.agentId}, ${t.projectName}) \u2014 ${t.toolCount} tool calls
4643
+ Signature: ${sig}`;
4644
+ }).join("\n\n");
4645
+ return `You are analyzing ${trajectories.length} completed tasks that followed similar procedures:
4646
+
4647
+ ${items}
4648
+
4649
+ Extract the reusable procedure. Format your response EXACTLY like this:
4650
+
4651
+ SKILL: {name \u2014 short, descriptive}
4652
+ TRIGGER: {when to use this \u2014 one sentence}
4653
+ STEPS:
4654
+ 1. ...
4655
+ 2. ...
4656
+ PITFALLS: {common mistakes to avoid}
4657
+
4658
+ Be specific and actionable. Include tool names, file patterns, and concrete commands where applicable.`;
4659
+ }
4660
+ async function extractSkill(trajectories, model) {
4661
+ if (trajectories.length === 0) return null;
4662
+ const config = await loadConfig();
4663
+ const skillModel = model ?? config.skillModel;
4664
+ const Anthropic = (await import("@anthropic-ai/sdk")).default;
4665
+ const client = new Anthropic();
4666
+ const prompt = buildExtractionPrompt(trajectories);
4667
+ const response = await client.messages.create({
4668
+ model: skillModel,
4669
+ max_tokens: 500,
4670
+ messages: [{ role: "user", content: prompt }]
4054
4671
  });
4055
- return result.rows.map((row) => rowToMessage(row));
4672
+ const textBlock = response.content.find((b) => b.type === "text");
4673
+ const skillText = textBlock?.text;
4674
+ if (!skillText) return null;
4675
+ const agentId = trajectories[0].agentId;
4676
+ const projectName = trajectories[0].projectName;
4677
+ const skillId = await storeBehavior({
4678
+ agentId,
4679
+ content: skillText,
4680
+ domain: "skill",
4681
+ projectName
4682
+ });
4683
+ const dbClient = getClient();
4684
+ for (const t of trajectories) {
4685
+ await dbClient.execute({
4686
+ sql: "UPDATE trajectories SET skill_id = ? WHERE id = ?",
4687
+ args: [skillId, t.id]
4688
+ });
4689
+ }
4690
+ process.stderr.write(
4691
+ `[skill-learning] Skill extracted from ${trajectories.length} trajectories \u2192 behavior ${skillId}
4692
+ `
4693
+ );
4694
+ return skillId;
4056
4695
  }
4057
- async function retryPendingMessages() {
4696
+ async function captureAndLearn(opts) {
4697
+ try {
4698
+ const config = await loadConfig();
4699
+ if (!config.skillLearning) return;
4700
+ const { trajectoryId, similarCount, similar } = await captureTrajectory({
4701
+ ...opts,
4702
+ skillThreshold: config.skillThreshold
4703
+ });
4704
+ if (!trajectoryId) return;
4705
+ if (similarCount >= config.skillThreshold) {
4706
+ const unprocessed = similar.filter((t) => !t.skillId);
4707
+ if (unprocessed.length >= config.skillThreshold) {
4708
+ extractSkill(unprocessed, config.skillModel).catch((err) => {
4709
+ process.stderr.write(
4710
+ `[skill-learning] Extraction failed: ${err instanceof Error ? err.message : String(err)}
4711
+ `
4712
+ );
4713
+ });
4714
+ }
4715
+ }
4716
+ } catch (err) {
4717
+ process.stderr.write(
4718
+ `[skill-learning] captureAndLearn failed: ${err instanceof Error ? err.message : String(err)}
4719
+ `
4720
+ );
4721
+ }
4722
+ }
4723
+ async function sweepTrajectories(threshold, model) {
4724
+ const config = await loadConfig();
4725
+ if (!config.skillLearning) return { clustersProcessed: 0, skillsExtracted: 0 };
4726
+ const t = threshold ?? config.skillThreshold;
4058
4727
  const client = getClient();
4059
4728
  const result = await client.execute({
4060
- sql: `SELECT * FROM messages
4061
- WHERE status = 'pending' AND retry_count < ?
4062
- ORDER BY id`,
4063
- args: [MAX_RETRIES3]
4729
+ sql: `SELECT signature_hash, COUNT(*) as cnt
4730
+ FROM trajectories
4731
+ WHERE skill_id IS NULL
4732
+ GROUP BY signature_hash
4733
+ HAVING cnt >= ?
4734
+ ORDER BY cnt DESC
4735
+ LIMIT 10`,
4736
+ args: [t]
4064
4737
  });
4065
- let delivered = 0;
4738
+ let clustersProcessed = 0;
4739
+ let skillsExtracted = 0;
4066
4740
  for (const row of result.rows) {
4067
- const msg = rowToMessage(row);
4068
- try {
4069
- const success = await deliverLocalMessage(msg.id);
4070
- if (success) delivered++;
4071
- } catch {
4741
+ const hash = String(row.signature_hash);
4742
+ const trajResult = await client.execute({
4743
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at
4744
+ FROM trajectories
4745
+ WHERE signature_hash = ? AND skill_id IS NULL
4746
+ ORDER BY created_at DESC
4747
+ LIMIT 10`,
4748
+ args: [hash]
4749
+ });
4750
+ const trajectories = trajResult.rows.map((r) => ({
4751
+ id: String(r.id),
4752
+ taskId: String(r.task_id),
4753
+ agentId: String(r.agent_id),
4754
+ projectName: String(r.project_name),
4755
+ taskTitle: String(r.task_title),
4756
+ signature: JSON.parse(String(r.signature)),
4757
+ signatureHash: String(r.signature_hash),
4758
+ toolCount: Number(r.tool_count),
4759
+ skillId: null,
4760
+ createdAt: String(r.created_at)
4761
+ }));
4762
+ if (trajectories.length >= t) {
4763
+ clustersProcessed++;
4764
+ const skillId = await extractSkill(trajectories, model ?? config.skillModel);
4765
+ if (skillId) skillsExtracted++;
4766
+ }
4767
+ }
4768
+ return { clustersProcessed, skillsExtracted };
4769
+ }
4770
+ function editDistance(a, b) {
4771
+ const m = a.length;
4772
+ const n = b.length;
4773
+ const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
4774
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
4775
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
4776
+ for (let i = 1; i <= m; i++) {
4777
+ for (let j = 1; j <= n; j++) {
4778
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
4779
+ dp[i][j] = Math.min(
4780
+ dp[i - 1][j] + 1,
4781
+ dp[i][j - 1] + 1,
4782
+ dp[i - 1][j - 1] + cost
4783
+ );
4784
+ }
4785
+ }
4786
+ return dp[m][n];
4787
+ }
4788
+ var DEFAULT_SKILL_THRESHOLD;
4789
+ var init_skill_learning = __esm({
4790
+ "src/lib/skill-learning.ts"() {
4791
+ "use strict";
4792
+ init_database();
4793
+ init_behaviors();
4794
+ init_config();
4795
+ DEFAULT_SKILL_THRESHOLD = 3;
4796
+ }
4797
+ });
4798
+
4799
+ // src/lib/tasks.ts
4800
+ var tasks_exports = {};
4801
+ __export(tasks_exports, {
4802
+ cleanupOrphanedReviews: () => cleanupOrphanedReviews,
4803
+ countNewPendingReviewsSince: () => countNewPendingReviewsSince,
4804
+ countPendingReviews: () => countPendingReviews,
4805
+ createTask: () => createTask,
4806
+ createTaskCore: () => createTaskCore,
4807
+ deleteTask: () => deleteTask,
4808
+ deleteTaskCore: () => deleteTaskCore,
4809
+ ensureArchitectureDoc: () => ensureArchitectureDoc,
4810
+ ensureGitignoreExe: () => ensureGitignoreExe,
4811
+ getReviewChecklist: () => getReviewChecklist,
4812
+ listPendingReviews: () => listPendingReviews,
4813
+ listTasks: () => listTasks,
4814
+ resolveTask: () => resolveTask,
4815
+ slugify: () => slugify,
4816
+ updateTask: () => updateTask,
4817
+ updateTaskStatus: () => updateTaskStatus,
4818
+ writeCheckpoint: () => writeCheckpoint
4819
+ });
4820
+ import path18 from "path";
4821
+ import { writeFileSync as writeFileSync5, mkdirSync as mkdirSync6, unlinkSync as unlinkSync5 } from "fs";
4822
+ async function createTask(input2) {
4823
+ const result = await createTaskCore(input2);
4824
+ if (!input2.skipDispatch && result.status !== "blocked" && !process.env.VITEST) {
4825
+ dispatchTaskToEmployee({
4826
+ assignedTo: input2.assignedTo,
4827
+ title: input2.title,
4828
+ priority: input2.priority,
4829
+ taskFile: result.taskFile,
4830
+ initialStatus: result.status,
4831
+ projectName: input2.projectName
4832
+ });
4833
+ }
4834
+ return result;
4835
+ }
4836
+ async function updateTask(input2) {
4837
+ const { row, taskFile, now, taskId } = await updateTaskStatus(input2);
4838
+ try {
4839
+ const agent = String(row.assigned_to);
4840
+ const cacheDir = path18.join(EXE_AI_DIR, "session-cache");
4841
+ const cachePath = path18.join(cacheDir, `current-task-${agent}.json`);
4842
+ if (input2.status === "in_progress") {
4843
+ mkdirSync6(cacheDir, { recursive: true });
4844
+ writeFileSync5(cachePath, JSON.stringify({ taskId, title: String(row.title) }));
4845
+ } else if (input2.status === "done" || input2.status === "blocked" || input2.status === "cancelled") {
4846
+ try {
4847
+ unlinkSync5(cachePath);
4848
+ } catch {
4849
+ }
4850
+ }
4851
+ } catch {
4852
+ }
4853
+ if (input2.status === "done") {
4854
+ await cleanupReviewFile(row, taskFile, input2.baseDir);
4855
+ }
4856
+ if (input2.status === "done" || input2.status === "cancelled") {
4857
+ try {
4858
+ const client = getClient();
4859
+ const taskTitle = String(row.title);
4860
+ const escaped = taskTitle.replace(/%/g, "\\%").replace(/_/g, "\\_");
4861
+ await client.execute({
4862
+ sql: `UPDATE tasks SET status = 'cancelled', updated_at = ?
4863
+ WHERE title LIKE ? ESCAPE '\\' AND status IN ('open', 'in_progress')`,
4864
+ args: [now, `%left '${escaped}' as in\\_progress%`]
4865
+ });
4866
+ } catch {
4867
+ }
4868
+ try {
4869
+ const client = getClient();
4870
+ const cascaded = await client.execute({
4871
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
4872
+ WHERE parent_task_id = ? AND status = 'needs_review'`,
4873
+ args: [now, taskId]
4874
+ });
4875
+ if (cascaded.rowsAffected > 0) {
4876
+ process.stderr.write(
4877
+ `[cascade] Closed ${cascaded.rowsAffected} orphaned review task(s) for parent ${taskId}
4878
+ `
4879
+ );
4880
+ }
4881
+ } catch {
4882
+ }
4883
+ }
4884
+ const isTerminal = input2.status === "done" || input2.status === "needs_review";
4885
+ if (isTerminal) {
4886
+ const isExe = String(row.assigned_to) === "exe";
4887
+ if (!isExe) {
4888
+ notifyTaskDone();
4889
+ }
4890
+ await markTaskNotificationsRead(taskFile);
4891
+ if (input2.status === "done") {
4892
+ try {
4893
+ await cascadeUnblock(taskId, input2.baseDir, now);
4894
+ } catch {
4895
+ }
4896
+ orgBus.emit({
4897
+ type: "task_completed",
4898
+ taskId,
4899
+ employee: String(row.assigned_to),
4900
+ result: input2.result ?? "",
4901
+ timestamp: now
4902
+ });
4903
+ if (row.parent_task_id) {
4904
+ try {
4905
+ await checkSubtaskCompletion(String(row.parent_task_id), String(row.project_name));
4906
+ } catch {
4907
+ }
4908
+ }
4909
+ }
4910
+ }
4911
+ if (input2.status === "done" && String(row.assigned_to) !== "exe" && !process.env.VITEST) {
4912
+ Promise.resolve().then(() => (init_skill_learning(), skill_learning_exports)).then(
4913
+ ({ captureAndLearn: captureAndLearn2 }) => captureAndLearn2({
4914
+ taskId,
4915
+ agentId: String(row.assigned_to),
4916
+ projectName: String(row.project_name),
4917
+ taskTitle: String(row.title)
4918
+ })
4919
+ ).catch((err) => {
4920
+ process.stderr.write(
4921
+ `[updateTask] skill learning failed: ${err instanceof Error ? err.message : String(err)}
4922
+ `
4923
+ );
4924
+ });
4925
+ }
4926
+ let nextTask;
4927
+ if (isTerminal && String(row.assigned_to) !== "exe") {
4928
+ try {
4929
+ nextTask = await findNextTask(String(row.assigned_to));
4930
+ } catch {
4931
+ }
4932
+ }
4933
+ return {
4934
+ id: String(row.id),
4935
+ title: String(row.title),
4936
+ assignedTo: String(row.assigned_to),
4937
+ assignedBy: String(row.assigned_by),
4938
+ projectName: String(row.project_name),
4939
+ priority: String(row.priority),
4940
+ status: input2.status,
4941
+ taskFile,
4942
+ createdAt: String(row.created_at),
4943
+ updatedAt: now,
4944
+ budgetTokens: row.budget_tokens !== void 0 && row.budget_tokens !== null ? Number(row.budget_tokens) : null,
4945
+ budgetFallbackModel: row.budget_fallback_model !== void 0 && row.budget_fallback_model !== null ? String(row.budget_fallback_model) : null,
4946
+ tokensUsed: Number(row.tokens_used ?? 0),
4947
+ tokensWarnedAt: row.tokens_warned_at !== void 0 && row.tokens_warned_at !== null ? Number(row.tokens_warned_at) : null,
4948
+ nextTask
4949
+ };
4950
+ }
4951
+ async function deleteTask(taskId, baseDir) {
4952
+ const client = getClient();
4953
+ const { taskFile, assignedTo, assignedBy, taskSlug } = await deleteTaskCore(taskId, baseDir);
4954
+ const reviewer = assignedBy || "exe";
4955
+ const reviewSlug = `review-${assignedTo}-${taskSlug}`;
4956
+ const reviewFile = `exe/${reviewer}/${reviewSlug}.md`;
4957
+ await client.execute({
4958
+ sql: "DELETE FROM tasks WHERE task_file = ? OR task_file = ?",
4959
+ args: [reviewFile, `exe/exe/${reviewSlug}.md`]
4960
+ });
4961
+ await markAsReadByTaskFile(taskFile);
4962
+ await markAsReadByTaskFile(reviewFile);
4963
+ }
4964
+ var init_tasks = __esm({
4965
+ "src/lib/tasks.ts"() {
4966
+ "use strict";
4967
+ init_database();
4968
+ init_config();
4969
+ init_notifications();
4970
+ init_state_bus();
4971
+ init_tasks_crud();
4972
+ init_tasks_review();
4973
+ init_tasks_crud();
4974
+ init_tasks_chain();
4975
+ init_tasks_review();
4976
+ init_tasks_notify();
4977
+ }
4978
+ });
4979
+
4980
+ // src/lib/capacity-monitor.ts
4981
+ var capacity_monitor_exports = {};
4982
+ __export(capacity_monitor_exports, {
4983
+ CTX_FLOOR_PERCENT: () => CTX_FLOOR_PERCENT,
4984
+ _resetLastRelaunchCache: () => _resetLastRelaunchCache,
4985
+ _resetPendingCapacityKills: () => _resetPendingCapacityKills,
4986
+ confirmCapacityKill: () => confirmCapacityKill,
4987
+ createOrRefreshResumeTask: () => createOrRefreshResumeTask,
4988
+ extractContextPercent: () => extractContextPercent,
4989
+ isAtCapacity: () => isAtCapacity,
4990
+ isWithinRelaunchCooldown: () => isWithinRelaunchCooldown,
4991
+ pollCapacityDead: () => pollCapacityDead
4992
+ });
4993
+ function resumeTaskTitle(agentId) {
4994
+ return `${RESUME_TITLE_PREFIX} ${agentId} hit context capacity \u2014 continue open tasks`;
4995
+ }
4996
+ function buildResumeContext(agentId, openTasks) {
4997
+ const taskList = openTasks.map(
4998
+ (r, i) => `${i + 1}. [${String(r.priority).toUpperCase()}] ${String(r.title)} (${String(r.task_file)})`
4999
+ ).join("\n");
5000
+ return [
5001
+ "## Context",
5002
+ "",
5003
+ `${agentId} hit context capacity and was auto-relaunched by the capacity monitor.`,
5004
+ "Call recall_my_memory first \u2014 search for 'CONTEXT CHECKPOINT'. Pick up where the previous session stopped.",
5005
+ "",
5006
+ `You have ${openTasks.length} open task(s). Work through them in priority order:`,
5007
+ "",
5008
+ taskList,
5009
+ "",
5010
+ "Read each task file and chain through them. Build and commit after each one."
5011
+ ].join("\n");
5012
+ }
5013
+ function filterPaneContent(paneOutput) {
5014
+ return paneOutput.split("\n").filter((line) => {
5015
+ if (CONTENT_LINE_PREFIX.test(line)) return false;
5016
+ for (const marker of CONTENT_LINE_MARKERS) {
5017
+ if (line.includes(marker)) return false;
5018
+ }
5019
+ for (const re of SOURCE_CODE_MARKERS) {
5020
+ if (re.test(line)) return false;
5021
+ }
5022
+ return true;
5023
+ }).join("\n");
5024
+ }
5025
+ function extractContextPercent(paneOutput) {
5026
+ const match = paneOutput.match(CC_CONTEXT_BAR_RE);
5027
+ if (!match) return null;
5028
+ const parsed = Number.parseInt(match[2], 10);
5029
+ return Number.isFinite(parsed) ? parsed : null;
5030
+ }
5031
+ function isAtCapacity(paneOutput) {
5032
+ const filtered = filterPaneContent(paneOutput);
5033
+ return CAPACITY_PATTERNS.some((p) => p.test(filtered));
5034
+ }
5035
+ function confirmCapacityKill(agentId, now = Date.now()) {
5036
+ const pendingSince = _pendingCapacityKill.get(agentId);
5037
+ if (pendingSince === void 0) {
5038
+ _pendingCapacityKill.set(agentId, now);
5039
+ return false;
5040
+ }
5041
+ if (now - pendingSince > CONFIRMATION_WINDOW_MS) {
5042
+ _pendingCapacityKill.set(agentId, now);
5043
+ return false;
5044
+ }
5045
+ _pendingCapacityKill.delete(agentId);
5046
+ return true;
5047
+ }
5048
+ function _resetPendingCapacityKills() {
5049
+ _pendingCapacityKill.clear();
5050
+ }
5051
+ function _resetLastRelaunchCache() {
5052
+ _lastRelaunch.clear();
5053
+ }
5054
+ async function lastResumeCreatedAtMs(agentId) {
5055
+ const client = getClient();
5056
+ const result = await client.execute({
5057
+ sql: `SELECT MAX(created_at) AS last_created_at
5058
+ FROM tasks
5059
+ WHERE assigned_to = ? AND title LIKE ?`,
5060
+ args: [agentId, `${RESUME_TITLE_PREFIX} %`]
5061
+ });
5062
+ const raw = result.rows[0]?.last_created_at;
5063
+ if (raw === null || raw === void 0) return null;
5064
+ const parsed = Date.parse(String(raw));
5065
+ return Number.isNaN(parsed) ? null : parsed;
5066
+ }
5067
+ async function isWithinRelaunchCooldown(agentId, now = Date.now()) {
5068
+ const cached = _lastRelaunch.get(agentId);
5069
+ if (cached !== void 0) return now - cached < RELAUNCH_COOLDOWN_MS;
5070
+ const persisted = await lastResumeCreatedAtMs(agentId);
5071
+ if (persisted === null) return false;
5072
+ if (now - persisted >= RELAUNCH_COOLDOWN_MS) return false;
5073
+ _lastRelaunch.set(agentId, persisted);
5074
+ return true;
5075
+ }
5076
+ async function createOrRefreshResumeTask(agentId, projectDir, openTasks) {
5077
+ const client = getClient();
5078
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5079
+ const context = buildResumeContext(agentId, openTasks);
5080
+ const existing = await client.execute({
5081
+ sql: `SELECT id FROM tasks
5082
+ WHERE assigned_to = ?
5083
+ AND title LIKE ?
5084
+ AND status IN (${RESUME_ACTIVE_STATUSES.map(() => "?").join(", ")})
5085
+ ORDER BY created_at DESC
5086
+ LIMIT 1`,
5087
+ args: [agentId, RESUME_TITLE_LIKE_PATTERN, ...RESUME_ACTIVE_STATUSES]
5088
+ });
5089
+ if (existing.rows.length > 0) {
5090
+ const taskId = String(existing.rows[0].id);
5091
+ await client.execute({
5092
+ sql: `UPDATE tasks SET context = ?, updated_at = ? WHERE id = ?`,
5093
+ args: [context, now, taskId]
5094
+ });
5095
+ return { created: false, taskId };
5096
+ }
5097
+ const { createTask: createTask2 } = await Promise.resolve().then(() => (init_tasks(), tasks_exports));
5098
+ const task = await createTask2({
5099
+ title: resumeTaskTitle(agentId),
5100
+ assignedTo: agentId,
5101
+ assignedBy: "system",
5102
+ projectName: projectDir.split("/").pop() ?? "unknown",
5103
+ priority: "p0",
5104
+ context,
5105
+ baseDir: projectDir
5106
+ });
5107
+ return { created: true, taskId: task.id };
5108
+ }
5109
+ async function pollCapacityDead() {
5110
+ const transport = getTransport();
5111
+ const relaunched = [];
5112
+ const registered = listSessions().filter(
5113
+ (s) => s.agentId !== "exe"
5114
+ );
5115
+ if (registered.length === 0) return [];
5116
+ let liveSessions;
5117
+ try {
5118
+ liveSessions = transport.listSessions();
5119
+ } catch {
5120
+ return [];
5121
+ }
5122
+ for (const entry of registered) {
5123
+ const { windowName, agentId, projectDir } = entry;
5124
+ if (!liveSessions.includes(windowName)) continue;
5125
+ if (await isWithinRelaunchCooldown(agentId)) continue;
5126
+ let pane;
5127
+ try {
5128
+ pane = transport.capturePane(windowName, 15);
5129
+ } catch {
5130
+ continue;
5131
+ }
5132
+ if (!isAtCapacity(pane)) continue;
5133
+ const ctxPct = extractContextPercent(pane);
5134
+ if (ctxPct !== null && ctxPct < CTX_FLOOR_PERCENT) {
5135
+ process.stderr.write(
5136
+ `[capacity-monitor] ctx-floor: ${agentId} at ${ctxPct}% in ${windowName} \u2014 below ${CTX_FLOOR_PERCENT}%. Skipping capacity kill (likely self-referential content or false positive).
5137
+ `
5138
+ );
5139
+ continue;
5140
+ }
5141
+ if (!confirmCapacityKill(agentId)) {
5142
+ process.stderr.write(
5143
+ `[capacity-monitor] ${agentId} matched capacity pattern once in ${windowName}. Awaiting confirmation on next tick.
5144
+ `
5145
+ );
5146
+ continue;
5147
+ }
5148
+ const verify = await verifyPaneAtCapacity(windowName);
5149
+ if (!verify.atCapacity) {
5150
+ process.stderr.write(
5151
+ `[capacity-monitor] verifyPaneAtCapacity rejected kill for ${agentId} in ${windowName} (reason: ${verify.reason}). Skipping.
5152
+ `
5153
+ );
5154
+ void recordSessionKill({
5155
+ sessionName: windowName,
5156
+ agentId,
5157
+ reason: "capacity_false_positive_blocked"
5158
+ });
5159
+ continue;
5160
+ }
5161
+ process.stderr.write(
5162
+ `[capacity-monitor] Detected ${agentId} at capacity in session ${windowName} (confirmed). Auto-relaunching.
5163
+ `
5164
+ );
5165
+ try {
5166
+ transport.kill(windowName);
5167
+ void recordSessionKill({
5168
+ sessionName: windowName,
5169
+ agentId,
5170
+ reason: "capacity"
5171
+ });
5172
+ const client = getClient();
5173
+ const openTasks = await client.execute({
5174
+ sql: `SELECT id, title, priority, task_file, status
5175
+ FROM tasks
5176
+ WHERE assigned_to = ? AND status IN ('open', 'in_progress')
5177
+ ORDER BY
5178
+ CASE priority WHEN 'p0' THEN 0 WHEN 'p1' THEN 1 WHEN 'p2' THEN 2 ELSE 3 END,
5179
+ created_at ASC
5180
+ LIMIT 10`,
5181
+ args: [agentId]
5182
+ });
5183
+ if (openTasks.rows.length === 0) {
5184
+ process.stderr.write(
5185
+ `[capacity-monitor] ${agentId} has no open tasks \u2014 skipping relaunch.
5186
+ `
5187
+ );
5188
+ continue;
5189
+ }
5190
+ const { created } = await createOrRefreshResumeTask(
5191
+ agentId,
5192
+ projectDir,
5193
+ openTasks.rows
5194
+ );
5195
+ if (created) {
5196
+ await writeNotification({
5197
+ agentId: "system",
5198
+ agentRole: "daemon",
5199
+ event: "capacity_relaunch",
5200
+ project: projectDir.split("/").pop() ?? "unknown",
5201
+ summary: `${agentId} hit context capacity. Auto-relaunched with ${openTasks.rows.length} open task(s).`
5202
+ });
5203
+ }
5204
+ _lastRelaunch.set(agentId, Date.now());
5205
+ if (created) relaunched.push(agentId);
5206
+ } catch (err) {
5207
+ process.stderr.write(
5208
+ `[capacity-monitor] Failed to relaunch ${agentId}: ${err instanceof Error ? err.message : String(err)}
5209
+ `
5210
+ );
5211
+ }
5212
+ }
5213
+ return relaunched;
5214
+ }
5215
+ 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;
5216
+ var init_capacity_monitor = __esm({
5217
+ "src/lib/capacity-monitor.ts"() {
5218
+ "use strict";
5219
+ init_session_registry();
5220
+ init_transport();
5221
+ init_notifications();
5222
+ init_database();
5223
+ init_session_kill_telemetry();
5224
+ init_tmux_routing();
5225
+ CAPACITY_PATTERNS = [
5226
+ /conversation is too long/i,
5227
+ /maximum context length/i,
5228
+ /context window.*(?:limit|exceed|full)/i,
5229
+ /reached.*(?:token|context).*limit/i
5230
+ ];
5231
+ CONTENT_LINE_PREFIX = /^[\s>#\-*[]/;
5232
+ CONTENT_LINE_MARKERS = [
5233
+ "RESUME:",
5234
+ "intercom",
5235
+ "capacity-monitor",
5236
+ "CAPACITY_PATTERNS",
5237
+ "isAtCapacity",
5238
+ "CONTENT_LINE_MARKERS",
5239
+ "pollCapacityDead",
5240
+ "confirmCapacityKill",
5241
+ "session_kills",
5242
+ "capacity-monitor.test"
5243
+ ];
5244
+ SOURCE_CODE_MARKERS = [
5245
+ /["'`/].*(?:maximum context length|conversation is too long)/i,
5246
+ /(?:maximum context length|conversation is too long).*["'`/]/i
5247
+ ];
5248
+ RELAUNCH_COOLDOWN_MS = 5 * 60 * 1e3;
5249
+ _lastRelaunch = /* @__PURE__ */ new Map();
5250
+ RESUME_TITLE_PREFIX = "RESUME:";
5251
+ RESUME_TITLE_LIKE_PATTERN = `${RESUME_TITLE_PREFIX} % hit context capacity%`;
5252
+ RESUME_ACTIVE_STATUSES = ["open", "in_progress"];
5253
+ CONFIRMATION_WINDOW_MS = 3 * 60 * 1e3;
5254
+ _pendingCapacityKill = /* @__PURE__ */ new Map();
5255
+ CC_CONTEXT_BAR_RE = /([\u2588\u2591\u2592\u2593]{10})\s+(\d+)%/;
5256
+ CTX_FLOOR_PERCENT = 50;
5257
+ }
5258
+ });
5259
+
5260
+ // src/lib/tmux-routing.ts
5261
+ var tmux_routing_exports = {};
5262
+ __export(tmux_routing_exports, {
5263
+ acquireSpawnLock: () => acquireSpawnLock2,
5264
+ employeeSessionName: () => employeeSessionName,
5265
+ ensureEmployee: () => ensureEmployee,
5266
+ extractRootExe: () => extractRootExe,
5267
+ findFreeInstance: () => findFreeInstance,
5268
+ getDispatchedBy: () => getDispatchedBy,
5269
+ getMySession: () => getMySession,
5270
+ getParentExe: () => getParentExe,
5271
+ getSessionState: () => getSessionState,
5272
+ isEmployeeAlive: () => isEmployeeAlive,
5273
+ isExeSession: () => isExeSession,
5274
+ isSessionBusy: () => isSessionBusy,
5275
+ notifyParentExe: () => notifyParentExe,
5276
+ parseParentExe: () => parseParentExe,
5277
+ registerParentExe: () => registerParentExe,
5278
+ releaseSpawnLock: () => releaseSpawnLock2,
5279
+ resolveExeSession: () => resolveExeSession,
5280
+ sendIntercom: () => sendIntercom,
5281
+ spawnEmployee: () => spawnEmployee,
5282
+ verifyPaneAtCapacity: () => verifyPaneAtCapacity
5283
+ });
5284
+ import { execFileSync as execFileSync2, execSync as execSync8 } from "child_process";
5285
+ import { readFileSync as readFileSync12, writeFileSync as writeFileSync6, mkdirSync as mkdirSync7, existsSync as existsSync15, appendFileSync } from "fs";
5286
+ import path19 from "path";
5287
+ import os6 from "os";
5288
+ import { fileURLToPath as fileURLToPath2 } from "url";
5289
+ import { unlinkSync as unlinkSync6 } from "fs";
5290
+ function spawnLockPath(sessionName) {
5291
+ return path19.join(SPAWN_LOCK_DIR, `${sessionName}.lock`);
5292
+ }
5293
+ function isProcessAlive(pid) {
5294
+ try {
5295
+ process.kill(pid, 0);
5296
+ return true;
5297
+ } catch {
5298
+ return false;
5299
+ }
5300
+ }
5301
+ function acquireSpawnLock2(sessionName) {
5302
+ if (!existsSync15(SPAWN_LOCK_DIR)) {
5303
+ mkdirSync7(SPAWN_LOCK_DIR, { recursive: true });
5304
+ }
5305
+ const lockFile = spawnLockPath(sessionName);
5306
+ if (existsSync15(lockFile)) {
5307
+ try {
5308
+ const lock = JSON.parse(readFileSync12(lockFile, "utf8"));
5309
+ const age = Date.now() - lock.timestamp;
5310
+ if (isProcessAlive(lock.pid) && age < 6e4) {
5311
+ return false;
5312
+ }
5313
+ } catch {
5314
+ }
5315
+ }
5316
+ writeFileSync6(lockFile, JSON.stringify({ pid: process.pid, timestamp: Date.now() }));
5317
+ return true;
5318
+ }
5319
+ function releaseSpawnLock2(sessionName) {
5320
+ try {
5321
+ unlinkSync6(spawnLockPath(sessionName));
5322
+ } catch {
5323
+ }
5324
+ }
5325
+ function resolveBehaviorsExporterScript() {
5326
+ try {
5327
+ const thisFile = fileURLToPath2(import.meta.url);
5328
+ const scriptPath = path19.join(
5329
+ path19.dirname(thisFile),
5330
+ "..",
5331
+ "bin",
5332
+ "exe-export-behaviors.js"
5333
+ );
5334
+ return existsSync15(scriptPath) ? scriptPath : null;
5335
+ } catch {
5336
+ return null;
5337
+ }
5338
+ }
5339
+ function exportBehaviorsSync(agentId, projectName, sessionKey) {
5340
+ const script = resolveBehaviorsExporterScript();
5341
+ if (!script) return null;
5342
+ try {
5343
+ const output = execFileSync2(
5344
+ process.execPath,
5345
+ [script, agentId, projectName, sessionKey],
5346
+ { encoding: "utf-8", timeout: BEHAVIORS_EXPORT_TIMEOUT_MS }
5347
+ ).trim();
5348
+ return output.length > 0 ? output : null;
5349
+ } catch (err) {
5350
+ process.stderr.write(
5351
+ `[tmux-routing] behaviors export failed for ${agentId}: ${err instanceof Error ? err.message : String(err)}
5352
+ `
5353
+ );
5354
+ return null;
5355
+ }
5356
+ }
5357
+ function getMySession() {
5358
+ return getTransport().getMySession();
5359
+ }
5360
+ function employeeSessionName(employee, exeSession, instance) {
5361
+ if (!/^exe\d+$/.test(exeSession)) {
5362
+ const root = extractRootExe(exeSession);
5363
+ if (root) {
5364
+ process.stderr.write(
5365
+ `[tmux-routing] WARN: exeSession="${exeSession}" is not a root exe session, using "${root}" instead
5366
+ `
5367
+ );
5368
+ exeSession = root;
5369
+ } else {
5370
+ throw new Error(
5371
+ `Invalid exeSession "${exeSession}" \u2014 must be a root exe session (e.g., "exe1"), not an agent session`
5372
+ );
5373
+ }
5374
+ }
5375
+ const suffix = instance != null && instance > 0 ? String(instance) : "";
5376
+ const name = `${employee}${suffix}-${exeSession}`;
5377
+ if (!VALID_SESSION_NAME.test(name)) {
5378
+ throw new Error(
5379
+ `Invalid session name "${name}" \u2014 must match {agent}-exe{N} or {agent}{instance}-exe{N}`
5380
+ );
5381
+ }
5382
+ return name;
5383
+ }
5384
+ function parseParentExe(sessionName, agentId) {
5385
+ const escaped = agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5386
+ const regex = new RegExp(`^${escaped}\\d*-(.+)$`);
5387
+ const match = sessionName.match(regex);
5388
+ return match?.[1] ?? null;
5389
+ }
5390
+ function extractRootExe(name) {
5391
+ const match = name.match(/(exe\d+)$/);
5392
+ return match?.[1] ?? null;
5393
+ }
5394
+ function registerParentExe(sessionKey, parentExe, dispatchedBy) {
5395
+ if (!existsSync15(SESSION_CACHE)) {
5396
+ mkdirSync7(SESSION_CACHE, { recursive: true });
5397
+ }
5398
+ const rootExe = extractRootExe(parentExe) ?? parentExe;
5399
+ const filePath = path19.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`);
5400
+ writeFileSync6(filePath, JSON.stringify({
5401
+ parentExe: rootExe,
5402
+ dispatchedBy: dispatchedBy || rootExe,
5403
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString()
5404
+ }));
5405
+ }
5406
+ function getParentExe(sessionKey) {
5407
+ try {
5408
+ const data = JSON.parse(readFileSync12(path19.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
5409
+ return data.parentExe || null;
5410
+ } catch {
5411
+ return null;
5412
+ }
5413
+ }
5414
+ function getDispatchedBy(sessionKey) {
5415
+ try {
5416
+ const data = JSON.parse(readFileSync12(
5417
+ path19.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`),
5418
+ "utf8"
5419
+ ));
5420
+ return data.dispatchedBy ?? data.parentExe ?? null;
5421
+ } catch {
5422
+ return null;
5423
+ }
5424
+ }
5425
+ function resolveExeSession() {
5426
+ const mySession = getMySession();
5427
+ if (!mySession) return null;
5428
+ try {
5429
+ const key = getSessionKey();
5430
+ const parentExe = getParentExe(key);
5431
+ if (parentExe) {
5432
+ return extractRootExe(parentExe) ?? parentExe;
5433
+ }
5434
+ } catch {
5435
+ }
5436
+ return extractRootExe(mySession) ?? mySession;
5437
+ }
5438
+ function isEmployeeAlive(sessionName) {
5439
+ return getTransport().isAlive(sessionName);
5440
+ }
5441
+ function findFreeInstance(employeeName, exeSession, maxInstances = 10, isAlive = isEmployeeAlive) {
5442
+ const base = employeeSessionName(employeeName, exeSession);
5443
+ if (!isAlive(base) && acquireSpawnLock2(base)) return 0;
5444
+ for (let i = 2; i <= maxInstances; i++) {
5445
+ const candidate = employeeSessionName(employeeName, exeSession, i);
5446
+ if (!isAlive(candidate) && acquireSpawnLock2(candidate)) return i;
5447
+ }
5448
+ return null;
5449
+ }
5450
+ async function verifyPaneAtCapacity(sessionName) {
5451
+ const transport = getTransport();
5452
+ if (!transport.isAlive(sessionName)) {
5453
+ return { atCapacity: false, reason: `session ${sessionName} is not alive` };
5454
+ }
5455
+ let pane;
5456
+ try {
5457
+ pane = transport.capturePane(sessionName, VERIFY_PANE_LINES);
5458
+ } catch (err) {
5459
+ return {
5460
+ atCapacity: false,
5461
+ reason: `capture-pane failed: ${err instanceof Error ? err.message : String(err)}`
5462
+ };
5463
+ }
5464
+ const { isAtCapacity: isAtCapacity2 } = await Promise.resolve().then(() => (init_capacity_monitor(), capacity_monitor_exports));
5465
+ if (!isAtCapacity2(pane)) {
5466
+ return {
5467
+ atCapacity: false,
5468
+ reason: `last ${VERIFY_PANE_LINES} lines show normal work, no capacity banner`
5469
+ };
5470
+ }
5471
+ return {
5472
+ atCapacity: true,
5473
+ reason: "capacity banner matched in recent pane output"
5474
+ };
5475
+ }
5476
+ function readDebounceState() {
5477
+ try {
5478
+ if (!existsSync15(DEBOUNCE_FILE)) return {};
5479
+ return JSON.parse(readFileSync12(DEBOUNCE_FILE, "utf8"));
5480
+ } catch {
5481
+ return {};
5482
+ }
5483
+ }
5484
+ function writeDebounceState(state) {
5485
+ try {
5486
+ if (!existsSync15(SESSION_CACHE)) mkdirSync7(SESSION_CACHE, { recursive: true });
5487
+ writeFileSync6(DEBOUNCE_FILE, JSON.stringify(state));
5488
+ } catch {
5489
+ }
5490
+ }
5491
+ function isDebounced(targetSession) {
5492
+ const state = readDebounceState();
5493
+ const lastSent = state[targetSession] ?? 0;
5494
+ return Date.now() - lastSent < INTERCOM_DEBOUNCE_MS;
5495
+ }
5496
+ function recordDebounce(targetSession) {
5497
+ const state = readDebounceState();
5498
+ state[targetSession] = Date.now();
5499
+ const cutoff = Date.now() - DEBOUNCE_CLEANUP_AGE_MS;
5500
+ for (const key of Object.keys(state)) {
5501
+ if ((state[key] ?? 0) < cutoff) delete state[key];
5502
+ }
5503
+ writeDebounceState(state);
5504
+ }
5505
+ function logIntercom(msg) {
5506
+ const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${msg}
5507
+ `;
5508
+ process.stderr.write(`[intercom] ${msg}
5509
+ `);
5510
+ try {
5511
+ appendFileSync(INTERCOM_LOG2, line);
5512
+ } catch {
5513
+ }
5514
+ }
5515
+ function getSessionState(sessionName) {
5516
+ const transport = getTransport();
5517
+ if (!transport.isAlive(sessionName)) return "offline";
5518
+ try {
5519
+ const pane = transport.capturePane(sessionName, 5);
5520
+ if (!pane.includes("\u276F") && !pane.includes("Claude Code") && !BUSY_PATTERN.test(pane) && !/Running…/.test(pane)) {
5521
+ if (/\$\s*$/.test(pane) || /% $/.test(pane.trimEnd())) {
5522
+ return "no_claude";
5523
+ }
5524
+ }
5525
+ if (/Running…/.test(pane)) return "tool";
5526
+ if (BUSY_PATTERN.test(pane)) return "thinking";
5527
+ return "idle";
5528
+ } catch {
5529
+ return "offline";
5530
+ }
5531
+ }
5532
+ function isSessionBusy(sessionName) {
5533
+ const state = getSessionState(sessionName);
5534
+ return state === "thinking" || state === "tool";
5535
+ }
5536
+ function isExeSession(sessionName) {
5537
+ return /^exe\d*$/.test(sessionName);
5538
+ }
5539
+ function sendIntercom(targetSession) {
5540
+ const transport = getTransport();
5541
+ if (isExeSession(targetSession)) {
5542
+ logIntercom(`SKIP_EXE \u2192 ${targetSession} (exe sessions use prompt-submit hook)`);
5543
+ return "skipped_exe";
5544
+ }
5545
+ if (isDebounced(targetSession)) {
5546
+ logIntercom(`DEBOUNCE \u2192 ${targetSession} (cross-process file debounce)`);
5547
+ return "debounced";
5548
+ }
5549
+ try {
5550
+ const sessions = transport.listSessions();
5551
+ if (!sessions.includes(targetSession)) {
5552
+ logIntercom(`SKIP \u2192 ${targetSession} (session not found)`);
5553
+ return "failed";
5554
+ }
5555
+ const sessionState = getSessionState(targetSession);
5556
+ if (sessionState === "no_claude") {
5557
+ queueIntercom(targetSession, "claude not running in session");
5558
+ recordDebounce(targetSession);
5559
+ logIntercom(`QUEUED \u2192 ${targetSession} (no claude process \u2014 raw shell detected)`);
5560
+ return "queued";
5561
+ }
5562
+ if (sessionState === "thinking" || sessionState === "tool") {
5563
+ queueIntercom(targetSession, "session busy at send time");
5564
+ recordDebounce(targetSession);
5565
+ logIntercom(`QUEUED \u2192 ${targetSession} (session busy, will retry from queue)`);
5566
+ return "queued";
5567
+ }
5568
+ if (transport.isPaneInCopyMode(targetSession)) {
5569
+ logIntercom(`COPY_MODE \u2192 ${targetSession} (exiting copy mode first)`);
5570
+ transport.sendKeys(targetSession, "q");
5571
+ }
5572
+ transport.sendKeys(targetSession, "/exe-intercom");
5573
+ recordDebounce(targetSession);
5574
+ logIntercom(`DELIVERED \u2192 ${targetSession} (fire-and-forget)`);
5575
+ return "delivered";
5576
+ } catch {
5577
+ logIntercom(`FAIL \u2192 ${targetSession}`);
5578
+ return "failed";
5579
+ }
5580
+ }
5581
+ function notifyParentExe(sessionKey) {
5582
+ const target = getDispatchedBy(sessionKey);
5583
+ if (!target) {
5584
+ process.stderr.write(`[intercom] notifyParentExe: no dispatcher found for key ${sessionKey}
5585
+ `);
5586
+ return false;
5587
+ }
5588
+ process.stderr.write(`[intercom] notifyParentExe \u2192 ${target}
5589
+ `);
5590
+ const result = sendIntercom(target);
5591
+ if (result === "failed") {
5592
+ const rootExe = resolveExeSession();
5593
+ if (rootExe && rootExe !== target) {
5594
+ process.stderr.write(`[intercom] notifyParentExe: dispatcher ${target} dead, falling back to root exe ${rootExe}
5595
+ `);
5596
+ const fallback = sendIntercom(rootExe);
5597
+ return fallback !== "failed";
5598
+ }
5599
+ return false;
5600
+ }
5601
+ return true;
5602
+ }
5603
+ function ensureEmployee(employeeName, exeSession, projectDir, opts) {
5604
+ if (employeeName === "exe") {
5605
+ return { status: "failed", sessionName: "", error: "exe is the COO, not a dispatchable employee" };
5606
+ }
5607
+ try {
5608
+ assertEmployeeLimitSync();
5609
+ } catch (err) {
5610
+ if (err instanceof PlanLimitError) {
5611
+ return { status: "failed", sessionName: "", error: err.message };
5612
+ }
5613
+ }
5614
+ if (/-exe\d*$/.test(employeeName)) {
5615
+ const bare = employeeName.replace(/-exe\d*$/, "").replace(/\d+$/, "");
5616
+ return {
5617
+ status: "failed",
5618
+ sessionName: "",
5619
+ error: `Error: pass employee name ('${bare}'), not session name ('${employeeName}')`
5620
+ };
5621
+ }
5622
+ if (!/^exe\d+$/.test(exeSession)) {
5623
+ const root = extractRootExe(exeSession);
5624
+ if (root) {
5625
+ process.stderr.write(
5626
+ `[ensureEmployee] WARN: caller passed exeSession="${exeSession}" (not a root exe). Auto-correcting to "${root}".
5627
+ `
5628
+ );
5629
+ exeSession = root;
5630
+ } else {
5631
+ return {
5632
+ status: "failed",
5633
+ sessionName: "",
5634
+ error: `Invalid exeSession "${exeSession}" \u2014 must be a root exe session (e.g., "exe1")`
5635
+ };
5636
+ }
5637
+ }
5638
+ let effectiveInstance = opts?.instance;
5639
+ if (effectiveInstance === void 0 && opts?.autoInstance) {
5640
+ const free = findFreeInstance(
5641
+ employeeName,
5642
+ exeSession,
5643
+ opts.maxAutoInstances ?? 10
5644
+ );
5645
+ if (free === null) {
5646
+ return {
5647
+ status: "failed",
5648
+ sessionName: employeeSessionName(employeeName, exeSession),
5649
+ error: `All ${opts.maxAutoInstances ?? 10} instances of ${employeeName} are alive \u2014 cap reached`
5650
+ };
5651
+ }
5652
+ effectiveInstance = free === 0 ? void 0 : free;
5653
+ }
5654
+ const sessionName = employeeSessionName(employeeName, exeSession, effectiveInstance);
5655
+ if (isEmployeeAlive(sessionName)) {
5656
+ const result2 = sendIntercom(sessionName);
5657
+ if (result2 === "acknowledged" || result2 === "skipped_exe" || result2 === "debounced" || result2 === "queued") {
5658
+ return { status: "intercom_sent", sessionName };
5659
+ }
5660
+ if (result2 === "delivered") {
5661
+ return { status: "intercom_unprocessed", sessionName };
5662
+ }
5663
+ return { status: "failed", sessionName, error: "intercom delivery failed" };
5664
+ }
5665
+ const spawnOpts = { ...opts, instance: effectiveInstance };
5666
+ const result = spawnEmployee(employeeName, exeSession, projectDir, spawnOpts);
5667
+ if (result.error) {
5668
+ return { status: "failed", sessionName, error: result.error };
5669
+ }
5670
+ return { status: "spawned", sessionName };
5671
+ }
5672
+ function spawnEmployee(employeeName, exeSession, projectDir, opts) {
5673
+ const transport = getTransport();
5674
+ const sessionName = employeeSessionName(employeeName, exeSession, opts?.instance);
5675
+ const instanceLabel = opts?.instance != null && opts.instance > 0 ? `${employeeName}${opts.instance}` : employeeName;
5676
+ const logDir = path19.join(os6.homedir(), ".exe-os", "session-logs");
5677
+ const logFile = path19.join(logDir, `${instanceLabel}-${Date.now()}.log`);
5678
+ if (!existsSync15(logDir)) {
5679
+ mkdirSync7(logDir, { recursive: true });
5680
+ }
5681
+ transport.kill(sessionName);
5682
+ let cleanupSuffix = "";
5683
+ try {
5684
+ const thisFile = fileURLToPath2(import.meta.url);
5685
+ const cleanupScript = path19.join(path19.dirname(thisFile), "..", "bin", "exe-session-cleanup.js");
5686
+ if (existsSync15(cleanupScript)) {
5687
+ cleanupSuffix = `; ${process.execPath} "${cleanupScript}" "${employeeName}" "${exeSession}"`;
5688
+ }
5689
+ } catch {
5690
+ }
5691
+ try {
5692
+ const claudeJsonPath = path19.join(os6.homedir(), ".claude.json");
5693
+ let claudeJson = {};
5694
+ try {
5695
+ claudeJson = JSON.parse(readFileSync12(claudeJsonPath, "utf8"));
5696
+ } catch {
5697
+ }
5698
+ if (!claudeJson.projects) claudeJson.projects = {};
5699
+ const projects = claudeJson.projects;
5700
+ const trustDir = opts?.cwd ?? projectDir;
5701
+ if (!projects[trustDir]) projects[trustDir] = {};
5702
+ projects[trustDir].hasTrustDialogAccepted = true;
5703
+ writeFileSync6(claudeJsonPath, JSON.stringify(claudeJson, null, 2) + "\n");
5704
+ } catch {
5705
+ }
5706
+ try {
5707
+ const settingsDir = path19.join(os6.homedir(), ".claude", "projects");
5708
+ const normalizedKey = (opts?.cwd ?? projectDir).replace(/\//g, "-").replace(/^-/, "");
5709
+ const projSettingsDir = path19.join(settingsDir, normalizedKey);
5710
+ const settingsPath = path19.join(projSettingsDir, "settings.json");
5711
+ let settings = {};
5712
+ try {
5713
+ settings = JSON.parse(readFileSync12(settingsPath, "utf8"));
5714
+ } catch {
5715
+ }
5716
+ const perms = settings.permissions ?? {};
5717
+ const allow = perms.allow ?? [];
5718
+ const toolNames = [
5719
+ "recall_my_memory",
5720
+ "store_memory",
5721
+ "create_task",
5722
+ "update_task",
5723
+ "list_tasks",
5724
+ "get_task",
5725
+ "ask_team_memory",
5726
+ "store_behavior",
5727
+ "get_identity",
5728
+ "send_message"
5729
+ ];
5730
+ const requiredTools = expandDualPrefixTools(toolNames);
5731
+ let changed = false;
5732
+ for (const tool of requiredTools) {
5733
+ if (!allow.includes(tool)) {
5734
+ allow.push(tool);
5735
+ changed = true;
5736
+ }
5737
+ }
5738
+ if (changed) {
5739
+ perms.allow = allow;
5740
+ settings.permissions = perms;
5741
+ mkdirSync7(projSettingsDir, { recursive: true });
5742
+ writeFileSync6(settingsPath, JSON.stringify(settings, null, 2) + "\n");
5743
+ }
5744
+ } catch {
5745
+ }
5746
+ const spawnCwd = opts?.cwd ?? projectDir;
5747
+ const useExeAgent = !!(opts?.model && opts?.provider);
5748
+ const ccProvider = useExeAgent ? DEFAULT_PROVIDER : detectActiveProvider();
5749
+ const useBinSymlink = ccProvider !== DEFAULT_PROVIDER;
5750
+ let identityFlag = "";
5751
+ let behaviorsFlag = "";
5752
+ let legacyFallbackWarned = false;
5753
+ if (!useExeAgent && !useBinSymlink) {
5754
+ const identityPath = path19.join(
5755
+ os6.homedir(),
5756
+ ".exe-os",
5757
+ "identity",
5758
+ `${employeeName}.md`
5759
+ );
5760
+ _resetCcAgentSupportCache();
5761
+ const hasAgentFlag = claudeSupportsAgentFlag();
5762
+ if (hasAgentFlag) {
5763
+ identityFlag = ` --agent ${employeeName}`;
5764
+ } else if (existsSync15(identityPath)) {
5765
+ identityFlag = ` --append-system-prompt-file ${identityPath}`;
5766
+ legacyFallbackWarned = true;
5767
+ }
5768
+ const behaviorsFile = exportBehaviorsSync(
5769
+ employeeName,
5770
+ path19.basename(spawnCwd),
5771
+ sessionName
5772
+ );
5773
+ if (behaviorsFile) {
5774
+ behaviorsFlag = ` --append-system-prompt-file ${behaviorsFile}`;
4072
5775
  }
4073
5776
  }
4074
- return delivered;
4075
- }
4076
- var MAX_RETRIES3, _wsClientSend;
4077
- var init_messaging = __esm({
4078
- "src/lib/messaging.ts"() {
4079
- "use strict";
4080
- init_database();
4081
- init_tmux_routing();
4082
- MAX_RETRIES3 = 10;
4083
- _wsClientSend = null;
5777
+ if (legacyFallbackWarned) {
5778
+ process.stderr.write(
5779
+ `[tmux-routing] claude --agent not supported by installed CC. Falling back to --append-system-prompt-file for ${employeeName}. Upgrade Claude Code to enable native --agent launch.
5780
+ `
5781
+ );
4084
5782
  }
4085
- });
4086
-
4087
- // src/lib/notifications.ts
4088
- import crypto4 from "crypto";
4089
- import path15 from "path";
4090
- import os6 from "os";
4091
- import {
4092
- readFileSync as readFileSync11,
4093
- readdirSync as readdirSync4,
4094
- unlinkSync as unlinkSync4,
4095
- existsSync as existsSync13,
4096
- rmdirSync
4097
- } from "fs";
4098
- async function writeNotification(notification) {
5783
+ let sessionContextFlag = "";
4099
5784
  try {
4100
- const client = getClient();
4101
- const id = crypto4.randomUUID();
4102
- const now = (/* @__PURE__ */ new Date()).toISOString();
4103
- await client.execute({
4104
- sql: `INSERT INTO notifications (id, agent_id, agent_role, event, project, summary, task_file, read, created_at)
4105
- VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)`,
4106
- args: [
4107
- id,
4108
- notification.agentId,
4109
- notification.agentRole,
4110
- notification.event,
4111
- notification.project,
4112
- notification.summary,
4113
- notification.taskFile ?? null,
4114
- now
4115
- ]
4116
- });
4117
- } catch (err) {
4118
- process.stderr.write(`[notifications] WRITE FAILED: ${err instanceof Error ? err.message : String(err)}
4119
- `);
5785
+ const ctxDir = path19.join(os6.homedir(), ".exe-os", "session-cache");
5786
+ mkdirSync7(ctxDir, { recursive: true });
5787
+ const ctxFile = path19.join(ctxDir, `session-context-${sessionName}.md`);
5788
+ const ctxContent = [
5789
+ `## Session Context`,
5790
+ `You are running in tmux session: ${sessionName}.`,
5791
+ `Your parent exe session is ${exeSession}.`,
5792
+ `Your employees (if any) use the -${exeSession} suffix (e.g., tom-${exeSession}).`
5793
+ ].join("\n");
5794
+ writeFileSync6(ctxFile, ctxContent);
5795
+ sessionContextFlag = ` --append-system-prompt-file ${ctxFile}`;
5796
+ } catch {
4120
5797
  }
4121
- }
4122
- var init_notifications = __esm({
4123
- "src/lib/notifications.ts"() {
4124
- "use strict";
4125
- init_database();
5798
+ let envPrefix = `EXE_SESSION=${exeSession} EXE_SESSION_NAME=${sessionName}`;
5799
+ if (ccProvider !== DEFAULT_PROVIDER) {
5800
+ const cfg = PROVIDER_TABLE[ccProvider];
5801
+ if (cfg?.apiKeyEnv) {
5802
+ const keyVal = process.env[cfg.apiKeyEnv];
5803
+ if (keyVal) {
5804
+ envPrefix = `${envPrefix} ${cfg.apiKeyEnv}=${keyVal}`;
5805
+ }
5806
+ }
4126
5807
  }
4127
- });
4128
-
4129
- // src/lib/tasks-crud.ts
4130
- import crypto5 from "crypto";
4131
- import path16 from "path";
4132
- import { execSync as execSync8 } from "child_process";
4133
- import { mkdir as mkdir4, writeFile as writeFile4, appendFile } from "fs/promises";
4134
- import { existsSync as existsSync14, readFileSync as readFileSync12 } from "fs";
4135
- function extractParentFromContext(contextBody) {
4136
- if (!contextBody) return null;
4137
- const match = contextBody.match(
4138
- /Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
4139
- );
4140
- return match ? match[1].toLowerCase() : null;
4141
- }
4142
- function slugify(title) {
4143
- return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
4144
- }
4145
- async function resolveTask(client, identifier) {
4146
- let result = await client.execute({
4147
- sql: "SELECT * FROM tasks WHERE id = ?",
4148
- args: [identifier]
4149
- });
4150
- if (result.rows.length === 1) return result.rows[0];
4151
- result = await client.execute({
4152
- sql: "SELECT * FROM tasks WHERE task_file LIKE ?",
4153
- args: [`%${identifier}%`]
4154
- });
4155
- if (result.rows.length === 1) return result.rows[0];
4156
- if (result.rows.length > 1) {
4157
- const exact = result.rows.filter(
4158
- (r) => String(r.task_file).endsWith(`/${identifier}.md`)
4159
- );
4160
- if (exact.length === 1) return exact[0];
4161
- const candidates = exact.length > 1 ? exact : result.rows;
4162
- const active = candidates.filter(
4163
- (r) => !["done", "cancelled"].includes(String(r.status))
4164
- );
4165
- if (active.length === 1) return active[0];
4166
- const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
4167
- throw new Error(
4168
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
5808
+ let spawnCommand;
5809
+ if (useExeAgent) {
5810
+ spawnCommand = `${envPrefix} exe-agent --employee ${employeeName} --model ${opts.model} --provider ${opts.provider}${cleanupSuffix}`;
5811
+ } else if (useBinSymlink) {
5812
+ const binName = `${employeeName}-${ccProvider}`;
5813
+ process.stderr.write(
5814
+ `[tmux-routing] provider cascade: ${ccProvider} \u2192 spawning ${binName}
5815
+ `
4169
5816
  );
5817
+ spawnCommand = `${envPrefix} ${binName}${cleanupSuffix}`;
5818
+ } else {
5819
+ spawnCommand = `${envPrefix} claude --dangerously-skip-permissions${identityFlag}${behaviorsFlag}${sessionContextFlag}${cleanupSuffix}`;
4170
5820
  }
4171
- result = await client.execute({
4172
- sql: "SELECT * FROM tasks WHERE title LIKE ?",
4173
- args: [`%${identifier}%`]
5821
+ const spawnResult = transport.spawn(sessionName, {
5822
+ cwd: spawnCwd,
5823
+ command: spawnCommand
4174
5824
  });
4175
- if (result.rows.length === 1) return result.rows[0];
4176
- if (result.rows.length > 1) {
4177
- const active = result.rows.filter(
4178
- (r) => !["done", "cancelled"].includes(String(r.status))
4179
- );
4180
- if (active.length === 1) return active[0];
4181
- const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
4182
- throw new Error(
4183
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
4184
- );
5825
+ if (spawnResult.error) {
5826
+ releaseSpawnLock2(sessionName);
5827
+ return { sessionName, error: `tmux new-session failed: ${spawnResult.error}` };
4185
5828
  }
4186
- throw new Error(`Task not found: ${identifier}`);
4187
- }
4188
- async function createTaskCore(input2) {
4189
- const client = getClient();
4190
- const id = crypto5.randomUUID();
4191
- const now = (/* @__PURE__ */ new Date()).toISOString();
4192
- const slug = slugify(input2.title);
4193
- const taskFile = input2.taskFile ?? `exe/${input2.assignedTo}/${slug}.md`;
4194
- let blockedById = null;
4195
- const initialStatus = input2.blockedBy ? "blocked" : "open";
4196
- if (input2.blockedBy) {
4197
- const blocker = await resolveTask(client, input2.blockedBy);
4198
- blockedById = String(blocker.id);
5829
+ transport.pipeLog(sessionName, logFile);
5830
+ try {
5831
+ const mySession = getMySession();
5832
+ const dispatchInfo = path19.join(SESSION_CACHE, `dispatch-info-${sessionName}.json`);
5833
+ writeFileSync6(dispatchInfo, JSON.stringify({
5834
+ dispatchedBy: mySession,
5835
+ rootExe: exeSession,
5836
+ provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
5837
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
5838
+ }));
5839
+ } catch {
4199
5840
  }
4200
- let parentTaskId = null;
4201
- let parentRef = input2.parentTaskId;
4202
- if (!parentRef) {
4203
- const extracted = extractParentFromContext(input2.context);
4204
- if (extracted) {
4205
- parentRef = extracted;
4206
- process.stderr.write(
4207
- "[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
4208
- );
5841
+ let booted = false;
5842
+ for (let i = 0; i < 30; i++) {
5843
+ try {
5844
+ execSync8("sleep 0.5");
5845
+ } catch {
4209
5846
  }
4210
- }
4211
- if (parentRef) {
4212
5847
  try {
4213
- const parent = await resolveTask(client, parentRef);
4214
- parentTaskId = String(parent.id);
4215
- } catch (err) {
4216
- if (!input2.parentTaskId) {
4217
- throw new Error(
4218
- `create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
4219
- );
5848
+ const pane = transport.capturePane(sessionName);
5849
+ if (useExeAgent) {
5850
+ if (pane.includes("[exe-agent]") || pane.includes("online")) {
5851
+ booted = true;
5852
+ break;
5853
+ }
5854
+ } else {
5855
+ if (pane.includes("Claude Code") || pane.includes("\u276F")) {
5856
+ booted = true;
5857
+ break;
5858
+ }
4220
5859
  }
4221
- throw err;
5860
+ } catch {
4222
5861
  }
4223
5862
  }
4224
- let warning;
4225
- const dupCheck = await client.execute({
4226
- sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
4227
- args: [input2.title, input2.assignedTo]
4228
- });
4229
- if (dupCheck.rows.length > 0) {
4230
- warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
5863
+ if (!booted) {
5864
+ releaseSpawnLock2(sessionName);
5865
+ return { sessionName, error: `${useExeAgent ? "exe-agent" : "claude"} did not boot within 15s` };
4231
5866
  }
4232
- if (input2.baseDir) {
5867
+ if (!useExeAgent) {
4233
5868
  try {
4234
- await mkdir4(path16.join(input2.baseDir, "exe", "output"), { recursive: true });
4235
- await mkdir4(path16.join(input2.baseDir, "exe", "research"), { recursive: true });
4236
- await ensureArchitectureDoc(input2.baseDir, input2.projectName);
4237
- await ensureGitignoreExe(input2.baseDir);
5869
+ transport.sendKeys(sessionName, `/exe-call ${employeeName}`);
4238
5870
  } catch {
4239
5871
  }
4240
5872
  }
4241
- const complexity = input2.complexity ?? "standard";
5873
+ registerSession({
5874
+ windowName: sessionName,
5875
+ agentId: employeeName,
5876
+ projectDir: spawnCwd,
5877
+ parentExe: exeSession,
5878
+ pid: 0,
5879
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString()
5880
+ });
5881
+ releaseSpawnLock2(sessionName);
5882
+ return { sessionName };
5883
+ }
5884
+ 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;
5885
+ var init_tmux_routing = __esm({
5886
+ "src/lib/tmux-routing.ts"() {
5887
+ "use strict";
5888
+ init_session_registry();
5889
+ init_session_key();
5890
+ init_transport();
5891
+ init_cc_agent_support();
5892
+ init_mcp_prefix();
5893
+ init_provider_table();
5894
+ init_intercom_queue();
5895
+ init_plan_limits();
5896
+ SPAWN_LOCK_DIR = path19.join(os6.homedir(), ".exe-os", "spawn-locks");
5897
+ SESSION_CACHE = path19.join(os6.homedir(), ".exe-os", "session-cache");
5898
+ BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
5899
+ VALID_SESSION_NAME = /^[a-z]+-exe\d+$|^[a-z]+\d+-exe\d+$/;
5900
+ VERIFY_PANE_LINES = 200;
5901
+ INTERCOM_DEBOUNCE_MS = 3e4;
5902
+ INTERCOM_LOG2 = path19.join(os6.homedir(), ".exe-os", "intercom.log");
5903
+ DEBOUNCE_FILE = path19.join(SESSION_CACHE, "intercom-debounce.json");
5904
+ DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
5905
+ BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
5906
+ }
5907
+ });
5908
+
5909
+ // src/lib/messaging.ts
5910
+ var messaging_exports = {};
5911
+ __export(messaging_exports, {
5912
+ deliverLocalMessage: () => deliverLocalMessage,
5913
+ getFailedMessages: () => getFailedMessages,
5914
+ getMessageStatus: () => getMessageStatus,
5915
+ getPendingMessages: () => getPendingMessages,
5916
+ getReadMessages: () => getReadMessages,
5917
+ getUnacknowledgedMessages: () => getUnacknowledgedMessages,
5918
+ markAcknowledged: () => markAcknowledged,
5919
+ markFailed: () => markFailed,
5920
+ markProcessed: () => markProcessed,
5921
+ markRead: () => markRead,
5922
+ retryPendingMessages: () => retryPendingMessages,
5923
+ sendMessage: () => sendMessage,
5924
+ setWsClientSend: () => setWsClientSend
5925
+ });
5926
+ import crypto8 from "crypto";
5927
+ function generateUlid() {
5928
+ const timestamp = Date.now().toString(36).padStart(10, "0");
5929
+ const random = crypto8.randomBytes(10).toString("hex").slice(0, 16);
5930
+ return (timestamp + random).toUpperCase();
5931
+ }
5932
+ function rowToMessage(row) {
5933
+ return {
5934
+ id: row.id,
5935
+ fromAgent: row.from_agent,
5936
+ fromDevice: row.from_device,
5937
+ targetAgent: row.target_agent,
5938
+ targetProject: row.target_project ?? null,
5939
+ targetDevice: row.target_device,
5940
+ content: row.content,
5941
+ priority: row.priority ?? "normal",
5942
+ status: row.status ?? "pending",
5943
+ serverSeq: row.server_seq != null ? Number(row.server_seq) : null,
5944
+ retryCount: Number(row.retry_count ?? 0),
5945
+ createdAt: row.created_at,
5946
+ deliveredAt: row.delivered_at ?? null,
5947
+ processedAt: row.processed_at ?? null,
5948
+ failedAt: row.failed_at ?? null,
5949
+ failureReason: row.failure_reason ?? null
5950
+ };
5951
+ }
5952
+ async function sendMessage(input2) {
5953
+ const client = getClient();
5954
+ const id = generateUlid();
5955
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5956
+ const targetDevice = input2.targetDevice ?? "local";
4242
5957
  await client.execute({
4243
- 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)
4244
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
5958
+ sql: `INSERT INTO messages (id, from_agent, from_device, target_agent, target_project, target_device, content, priority, status, created_at)
5959
+ VALUES (?, ?, 'local', ?, ?, ?, ?, ?, 'pending', ?)`,
4245
5960
  args: [
4246
5961
  id,
4247
- input2.title,
4248
- input2.assignedTo,
4249
- input2.assignedBy,
4250
- input2.projectName,
4251
- input2.priority,
4252
- initialStatus,
4253
- taskFile,
4254
- blockedById,
4255
- parentTaskId,
4256
- input2.reviewer ?? null,
4257
- input2.context,
4258
- complexity,
4259
- input2.budgetTokens ?? null,
4260
- input2.budgetFallbackModel ?? null,
4261
- 0,
4262
- null,
4263
- now,
5962
+ input2.fromAgent,
5963
+ input2.targetAgent,
5964
+ input2.targetProject ?? null,
5965
+ targetDevice,
5966
+ input2.content,
5967
+ input2.priority ?? "normal",
4264
5968
  now
4265
5969
  ]
4266
5970
  });
4267
- return {
4268
- id,
4269
- title: input2.title,
4270
- assignedTo: input2.assignedTo,
4271
- assignedBy: input2.assignedBy,
4272
- projectName: input2.projectName,
4273
- priority: input2.priority,
4274
- status: initialStatus,
4275
- taskFile,
4276
- createdAt: now,
4277
- updatedAt: now,
4278
- warning,
4279
- budgetTokens: input2.budgetTokens ?? null,
4280
- budgetFallbackModel: input2.budgetFallbackModel ?? null,
4281
- tokensUsed: 0,
4282
- tokensWarnedAt: null
4283
- };
4284
- }
4285
- async function ensureArchitectureDoc(baseDir, projectName) {
4286
- const archPath = path16.join(baseDir, "exe", "ARCHITECTURE.md");
4287
5971
  try {
4288
- if (existsSync14(archPath)) return;
4289
- const template = [
4290
- `# ${projectName} \u2014 System Architecture`,
4291
- "",
4292
- "> Employees: read this before every task. Update it when you change system structure.",
4293
- `> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
4294
- "",
4295
- "## Overview",
4296
- "",
4297
- "<!-- Describe what this system does, its main components, and how they connect. -->",
4298
- "",
4299
- "## Key Components",
4300
- "",
4301
- "<!-- List the major modules, services, or subsystems. -->",
4302
- "",
4303
- "## Data Flow",
4304
- "",
4305
- "<!-- How does data move through the system? What writes where? -->",
4306
- "",
4307
- "## Invariants",
4308
- "",
4309
- "<!-- Rules that must never be violated. What breaks if these are wrong? -->",
4310
- "",
4311
- "## Dependencies",
4312
- "",
4313
- "<!-- What depends on what? If I change X, what else is affected? -->",
4314
- ""
4315
- ].join("\n");
4316
- await writeFile4(archPath, template, "utf-8");
5972
+ if (targetDevice !== "local") {
5973
+ await deliverCrossMachineMessage(id, targetDevice);
5974
+ } else {
5975
+ await deliverLocalMessage(id);
5976
+ }
4317
5977
  } catch {
4318
5978
  }
5979
+ const result = await client.execute({
5980
+ sql: "SELECT * FROM messages WHERE id = ?",
5981
+ args: [id]
5982
+ });
5983
+ return rowToMessage(result.rows[0]);
4319
5984
  }
4320
- async function ensureGitignoreExe(baseDir) {
4321
- const gitignorePath = path16.join(baseDir, ".gitignore");
5985
+ function setWsClientSend(fn) {
5986
+ _wsClientSend = fn;
5987
+ }
5988
+ async function deliverCrossMachineMessage(messageId, targetDevice) {
5989
+ const client = getClient();
5990
+ const result = await client.execute({
5991
+ sql: "SELECT * FROM messages WHERE id = ?",
5992
+ args: [messageId]
5993
+ });
5994
+ if (result.rows.length === 0) return false;
5995
+ const msg = rowToMessage(result.rows[0]);
5996
+ if (msg.status !== "pending") return false;
5997
+ if (!_wsClientSend) {
5998
+ return false;
5999
+ }
6000
+ const payload = JSON.stringify({
6001
+ id: msg.id,
6002
+ fromAgent: msg.fromAgent,
6003
+ targetAgent: msg.targetAgent,
6004
+ targetProject: msg.targetProject,
6005
+ content: msg.content,
6006
+ priority: msg.priority,
6007
+ createdAt: msg.createdAt
6008
+ });
6009
+ const sent = _wsClientSend(targetDevice, payload);
6010
+ if (sent) {
6011
+ await client.execute({
6012
+ sql: "UPDATE messages SET status = 'synced' WHERE id = ?",
6013
+ args: [messageId]
6014
+ });
6015
+ return true;
6016
+ }
6017
+ return false;
6018
+ }
6019
+ async function deliverLocalMessage(messageId) {
6020
+ const client = getClient();
6021
+ const result = await client.execute({
6022
+ sql: "SELECT * FROM messages WHERE id = ?",
6023
+ args: [messageId]
6024
+ });
6025
+ if (result.rows.length === 0) return false;
6026
+ const msg = rowToMessage(result.rows[0]);
6027
+ if (msg.status !== "pending") return false;
6028
+ const targetAgent = msg.targetAgent;
6029
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4322
6030
  try {
4323
- if (existsSync14(gitignorePath)) {
4324
- const content = readFileSync12(gitignorePath, "utf-8");
4325
- if (/^\/?exe\/?$/m.test(content)) return;
4326
- await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
4327
- } else {
4328
- await writeFile4(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
6031
+ const exeSession = resolveExeSession();
6032
+ if (!exeSession) {
6033
+ throw new Error("No exe session found");
6034
+ }
6035
+ const ensureResult = ensureEmployee(targetAgent, exeSession, process.cwd());
6036
+ if (ensureResult.status === "failed") {
6037
+ throw new Error(ensureResult.error ?? "ensureEmployee failed");
4329
6038
  }
6039
+ await client.execute({
6040
+ sql: "UPDATE messages SET status = 'delivered', delivered_at = ? WHERE id = ?",
6041
+ args: [now, messageId]
6042
+ });
6043
+ return true;
4330
6044
  } catch {
6045
+ const newRetryCount = msg.retryCount + 1;
6046
+ if (newRetryCount >= MAX_RETRIES3) {
6047
+ await markFailed(messageId, "session unavailable after 10 retries");
6048
+ } else {
6049
+ await client.execute({
6050
+ sql: "UPDATE messages SET retry_count = ? WHERE id = ?",
6051
+ args: [newRetryCount, messageId]
6052
+ });
6053
+ }
6054
+ return false;
4331
6055
  }
4332
6056
  }
4333
- var init_tasks_crud = __esm({
4334
- "src/lib/tasks-crud.ts"() {
4335
- "use strict";
4336
- init_database();
4337
- }
4338
- });
4339
-
4340
- // src/lib/tasks-review.ts
4341
- var tasks_review_exports = {};
4342
- __export(tasks_review_exports, {
4343
- cleanupOrphanedReviews: () => cleanupOrphanedReviews,
4344
- cleanupReviewFile: () => cleanupReviewFile,
4345
- countNewPendingReviewsSince: () => countNewPendingReviewsSince,
4346
- countPendingReviews: () => countPendingReviews,
4347
- createReviewForCompletedTask: () => createReviewForCompletedTask,
4348
- getReviewChecklist: () => getReviewChecklist,
4349
- listPendingReviews: () => listPendingReviews
4350
- });
4351
- import path17 from "path";
4352
- import { existsSync as existsSync15, readdirSync as readdirSync5, unlinkSync as unlinkSync5 } from "fs";
4353
- async function countPendingReviews() {
6057
+ async function getPendingMessages(targetAgent) {
4354
6058
  const client = getClient();
4355
6059
  const result = await client.execute({
4356
- sql: "SELECT COUNT(*) as cnt FROM tasks WHERE status = 'needs_review'",
4357
- args: []
6060
+ sql: `SELECT * FROM messages
6061
+ WHERE target_agent = ? AND status IN ('pending', 'delivered')
6062
+ ORDER BY id`,
6063
+ args: [targetAgent]
4358
6064
  });
4359
- return Number(result.rows[0]?.cnt) || 0;
6065
+ return result.rows.map((row) => rowToMessage(row));
4360
6066
  }
4361
- async function countNewPendingReviewsSince(sinceIso) {
6067
+ async function markRead(messageId) {
6068
+ const client = getClient();
6069
+ await client.execute({
6070
+ sql: "UPDATE messages SET status = 'read' WHERE id = ? AND status IN ('pending', 'delivered')",
6071
+ args: [messageId]
6072
+ });
6073
+ }
6074
+ async function markAcknowledged(messageId) {
6075
+ const client = getClient();
6076
+ await client.execute({
6077
+ sql: "UPDATE messages SET status = 'acknowledged', processed_at = ? WHERE id = ? AND status = 'read'",
6078
+ args: [(/* @__PURE__ */ new Date()).toISOString(), messageId]
6079
+ });
6080
+ }
6081
+ async function markProcessed(messageId) {
6082
+ const client = getClient();
6083
+ await client.execute({
6084
+ sql: "UPDATE messages SET status = 'processed', processed_at = ? WHERE id = ?",
6085
+ args: [(/* @__PURE__ */ new Date()).toISOString(), messageId]
6086
+ });
6087
+ }
6088
+ async function getMessageStatus(messageId) {
4362
6089
  const client = getClient();
4363
6090
  const result = await client.execute({
4364
- sql: `SELECT COUNT(*) as cnt FROM tasks
4365
- WHERE status = 'needs_review' AND updated_at > ?`,
4366
- args: [sinceIso]
6091
+ sql: "SELECT status FROM messages WHERE id = ?",
6092
+ args: [messageId]
6093
+ });
6094
+ return result.rows[0]?.status ?? null;
6095
+ }
6096
+ async function getUnacknowledgedMessages(targetAgent) {
6097
+ const client = getClient();
6098
+ const result = await client.execute({
6099
+ sql: `SELECT * FROM messages
6100
+ WHERE target_agent = ? AND status IN ('pending', 'delivered', 'read')
6101
+ ORDER BY id`,
6102
+ args: [targetAgent]
4367
6103
  });
4368
- return Number(result.rows[0]?.cnt) || 0;
6104
+ return result.rows.map((row) => rowToMessage(row));
4369
6105
  }
4370
- async function listPendingReviews(limit) {
6106
+ async function getReadMessages(targetAgent) {
4371
6107
  const client = getClient();
4372
6108
  const result = await client.execute({
4373
- sql: `SELECT title, assigned_to, project_name FROM tasks
4374
- WHERE status = 'needs_review'
4375
- ORDER BY priority ASC, created_at DESC LIMIT ?`,
4376
- args: [limit]
6109
+ sql: "SELECT * FROM messages WHERE target_agent = ? AND status = 'read' ORDER BY id",
6110
+ args: [targetAgent]
4377
6111
  });
4378
- return result.rows;
6112
+ return result.rows.map((row) => rowToMessage(row));
4379
6113
  }
4380
- async function cleanupOrphanedReviews() {
6114
+ async function markFailed(messageId, reason) {
4381
6115
  const client = getClient();
4382
- const now = (/* @__PURE__ */ new Date()).toISOString();
4383
- const r1 = await client.execute({
4384
- sql: `UPDATE tasks SET status = 'done', updated_at = ?
4385
- WHERE status = 'needs_review'
4386
- AND assigned_by = 'system'
4387
- AND title LIKE 'Review:%'
4388
- AND parent_task_id IN (SELECT id FROM tasks WHERE status IN ('done', 'cancelled'))`,
4389
- args: [now]
4390
- });
4391
- const staleThreshold = new Date(Date.now() - 60 * 60 * 1e3).toISOString();
4392
- const r2 = await client.execute({
4393
- sql: `UPDATE tasks SET status = 'done', updated_at = ?
4394
- WHERE status = 'needs_review'
4395
- AND result IS NOT NULL
4396
- AND updated_at < ?`,
4397
- args: [now, staleThreshold]
6116
+ await client.execute({
6117
+ sql: "UPDATE messages SET status = 'failed', failed_at = ?, failure_reason = ? WHERE id = ?",
6118
+ args: [(/* @__PURE__ */ new Date()).toISOString(), reason, messageId]
4398
6119
  });
4399
- const total = r1.rowsAffected + r2.rowsAffected;
4400
- if (total > 0) {
4401
- process.stderr.write(
4402
- `[cleanup] Closed ${total} orphaned review(s): ${r1.rowsAffected} cascade + ${r2.rowsAffected} stale
4403
- `
4404
- );
4405
- }
4406
- return total;
4407
- }
4408
- function getReviewChecklist(role, agent, taskSlug) {
4409
- const roleLower = role.toLowerCase();
4410
- if (roleLower.includes("engineer") || roleLower === "principal engineer") {
4411
- return {
4412
- lens: "Code Quality (Engineer)",
4413
- checklist: [
4414
- "1. Do all tests pass? Any new tests needed?",
4415
- "2. Is the code clean \u2014 no dead code, no TODOs left?",
4416
- "3. Does it follow existing patterns and conventions in the codebase?",
4417
- "4. Any regressions in the test suite?"
4418
- ]
4419
- };
4420
- }
4421
- if (roleLower === "cto" || roleLower.includes("architect")) {
4422
- return {
4423
- lens: "Architecture (CTO)",
4424
- checklist: [
4425
- "1. Does this fit the existing architecture? Consistent with ARCHITECTURE.md?",
4426
- "2. Is it backward compatible? Any breaking changes?",
4427
- "3. Does it introduce technical debt? Is that debt justified?",
4428
- "4. Security implications? Any new attack surface?",
4429
- "5. Does it scale? Performance considerations?",
4430
- "6. Coordination: does this affect other employees' work or other projects?"
4431
- ]
4432
- };
4433
- }
4434
- if (roleLower === "coo" || roleLower.includes("operations")) {
4435
- return {
4436
- lens: "Strategic (COO)",
4437
- checklist: [
4438
- "1. Does this serve the project mission?",
4439
- "2. Is this the right work at the right time?",
4440
- "3. Does the architectural assessment make sense for the business?",
4441
- "4. Any cross-project implications?"
4442
- ]
4443
- };
4444
- }
4445
- return {
4446
- lens: "General",
4447
- checklist: [
4448
- "1. Read the original task's acceptance criteria",
4449
- `2. Check git log for related commits: \`git log --oneline --author-date-order -10\``,
4450
- "3. Verify code changes match requirements",
4451
- "4. Check if tests were added/updated",
4452
- `5. Look for output files in exe/output/${agent}-${taskSlug}*`
4453
- ]
4454
- };
4455
6120
  }
4456
- async function createReviewForCompletedTask(row, result, _baseDir, now) {
4457
- const taskFile = String(row.task_file);
4458
- if (String(row.assigned_to) === "exe") return;
4459
- if (String(row.title).startsWith("Review:")) return;
4460
- const fileName = taskFile.split("/").pop() ?? "";
4461
- if (fileName.startsWith("review-") && String(row.assigned_by) === "system") return;
4462
- if (fileName.startsWith("review-") && String(row.assigned_to) === "system") return;
6121
+ async function getFailedMessages() {
4463
6122
  const client = getClient();
4464
- const agent = String(row.assigned_to);
4465
- const reviewer = String(row.reviewer || row.assigned_by) || "exe";
4466
- let reviewerRole = "unknown";
4467
- try {
4468
- const employees = await loadEmployees();
4469
- const emp = getEmployee(employees, reviewer);
4470
- if (emp) reviewerRole = emp.role;
4471
- } catch {
4472
- }
4473
- const taskTitle = String(row.title);
4474
- const taskSlug = taskFile.split("/").pop()?.replace(".md", "") ?? "unknown";
4475
- const { lens, checklist } = getReviewChecklist(reviewerRole, agent, taskSlug);
4476
- const reviewSlug = `review-${agent}-${taskSlug}`;
4477
- const reviewFile = `exe/${reviewer}/${reviewSlug}.md`;
4478
- await client.execute({
4479
- sql: "DELETE FROM tasks WHERE task_file = ?",
4480
- args: [reviewFile]
4481
- });
4482
- process.stderr.write(
4483
- `[review] Creating review for "${taskTitle}" \u2192 assigned to ${reviewer} (${reviewerRole})
4484
- `
4485
- );
4486
- const reviewContext = [
4487
- `${agent} marked this task as done:`,
4488
- `- Original task: ${taskFile}`,
4489
- `- Result: ${result ?? "No result summary provided"}`,
4490
- "",
4491
- `## Review lens: ${lens}`,
4492
- `You are reviewing as **${reviewer}** (${reviewerRole}).`,
4493
- "",
4494
- "## Review checklist",
4495
- ...checklist,
4496
- "",
4497
- "## Verdict",
4498
- "After review, update this task:",
4499
- "- **Approved:** mark this review task as done",
4500
- "- **Needs work:** re-open the original task with notes, mark this review as done"
4501
- ].join("\n");
4502
- const originalTaskId = String(row.id);
4503
- const reviewTask = await createTaskCore({
4504
- title: `Review: ${agent} completed "${taskTitle}"`,
4505
- assignedTo: reviewer,
4506
- assignedBy: "system",
4507
- projectName: String(row.project_name),
4508
- priority: "p1",
4509
- context: reviewContext,
4510
- taskFile: reviewFile,
4511
- parentTaskId: originalTaskId,
4512
- skipDispatch: true
6123
+ const result = await client.execute({
6124
+ sql: "SELECT * FROM messages WHERE status = 'failed' ORDER BY created_at DESC",
6125
+ args: []
4513
6126
  });
4514
- const reviewId = reviewTask.id;
4515
- await writeNotification({
4516
- agentId: agent,
4517
- agentRole: String(row.assigned_to),
4518
- event: "task_complete",
4519
- project: String(row.project_name),
4520
- summary: `completed "${taskTitle}" \u2014 review task created`,
4521
- taskFile: reviewFile
6127
+ return result.rows.map((row) => rowToMessage(row));
6128
+ }
6129
+ async function retryPendingMessages() {
6130
+ const client = getClient();
6131
+ const result = await client.execute({
6132
+ sql: `SELECT * FROM messages
6133
+ WHERE status = 'pending' AND retry_count < ?
6134
+ ORDER BY id`,
6135
+ args: [MAX_RETRIES3]
4522
6136
  });
4523
- const originalPriority = String(row.priority).toLowerCase();
4524
- const autoApprove = originalPriority === "p2" && result?.toLowerCase().includes("tests pass");
4525
- if (!autoApprove) {
6137
+ let delivered = 0;
6138
+ for (const row of result.rows) {
6139
+ const msg = rowToMessage(row);
4526
6140
  try {
4527
- const key = getSessionKey();
4528
- const exeSession = getParentExe(key);
4529
- if (exeSession) {
4530
- sendIntercom(exeSession);
4531
- }
6141
+ const success = await deliverLocalMessage(msg.id);
6142
+ if (success) delivered++;
4532
6143
  } catch {
4533
6144
  }
4534
6145
  }
4535
- if (autoApprove) {
4536
- process.stderr.write(
4537
- `[review] Auto-approving review for "${taskTitle}" (P2 + tests pass)
4538
- `
4539
- );
4540
- await client.execute({
4541
- sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ?",
4542
- args: [now, reviewId]
4543
- });
4544
- }
4545
- }
4546
- async function cleanupReviewFile(row, taskFile, _baseDir) {
4547
- if (String(row.assigned_by) !== "system" || !taskFile.includes("review-")) return;
4548
- try {
4549
- const client = getClient();
4550
- const now = (/* @__PURE__ */ new Date()).toISOString();
4551
- const parentId = row.parent_task_id ? String(row.parent_task_id) : null;
4552
- if (parentId) {
4553
- const result = await client.execute({
4554
- sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ? AND status = 'needs_review'",
4555
- args: [now, parentId]
4556
- });
4557
- if (result.rowsAffected > 0) {
4558
- process.stderr.write(
4559
- `[review-cleanup] Cascaded original task to done via parent_task_id: ${parentId}
4560
- `
4561
- );
4562
- }
4563
- } else {
4564
- const fileName = taskFile.split("/").pop() ?? "";
4565
- const reviewPrefix = fileName.replace(".md", "");
4566
- const parts = reviewPrefix.split("-");
4567
- if (parts.length >= 3 && parts[0] === "review") {
4568
- const agent = parts[1];
4569
- const slug = parts.slice(2).join("-");
4570
- const originalTaskFile = `exe/${agent}/${slug}.md`;
4571
- const result = await client.execute({
4572
- sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE task_file = ? AND status = 'needs_review'",
4573
- args: [now, originalTaskFile]
4574
- });
4575
- if (result.rowsAffected > 0) {
4576
- process.stderr.write(
4577
- `[review-cleanup] Cascaded original task to done (legacy path): ${originalTaskFile}
4578
- `
4579
- );
4580
- }
4581
- }
4582
- }
4583
- } catch (err) {
4584
- process.stderr.write(
4585
- `[review-cleanup] Failed to cascade original task: ${err instanceof Error ? err.message : String(err)}
4586
- `
4587
- );
4588
- }
4589
- try {
4590
- const cacheDir = path17.join(EXE_AI_DIR, "session-cache");
4591
- if (existsSync15(cacheDir)) {
4592
- for (const f of readdirSync5(cacheDir)) {
4593
- if (f.startsWith("review-notified-")) {
4594
- unlinkSync5(path17.join(cacheDir, f));
4595
- }
4596
- }
4597
- }
4598
- } catch {
4599
- }
6146
+ return delivered;
4600
6147
  }
4601
- var init_tasks_review = __esm({
4602
- "src/lib/tasks-review.ts"() {
6148
+ var MAX_RETRIES3, _wsClientSend;
6149
+ var init_messaging = __esm({
6150
+ "src/lib/messaging.ts"() {
4603
6151
  "use strict";
4604
6152
  init_database();
4605
- init_config();
4606
- init_employees();
4607
- init_notifications();
4608
- init_tasks_crud();
4609
6153
  init_tmux_routing();
4610
- init_session_key();
6154
+ MAX_RETRIES3 = 10;
6155
+ _wsClientSend = null;
4611
6156
  }
4612
6157
  });
4613
6158
 
@@ -4616,8 +6161,8 @@ init_config();
4616
6161
  init_config();
4617
6162
  init_store();
4618
6163
  import { spawn as spawn2 } from "child_process";
4619
- import { readFileSync as readFileSync13, writeFileSync as writeFileSync6, mkdirSync as mkdirSync7, existsSync as existsSync16, openSync as openSync2, closeSync as closeSync2 } from "fs";
4620
- import path18 from "path";
6164
+ import { readFileSync as readFileSync13, writeFileSync as writeFileSync7, mkdirSync as mkdirSync8, existsSync as existsSync16, openSync as openSync2, closeSync as closeSync2 } from "fs";
6165
+ import path20 from "path";
4621
6166
  import { fileURLToPath as fileURLToPath3 } from "url";
4622
6167
 
4623
6168
  // src/lib/hybrid-search.ts
@@ -5048,7 +6593,7 @@ if (!process.env.AGENT_ID) {
5048
6593
  if (!loadConfigSync().autoRetrieval) {
5049
6594
  process.exit(0);
5050
6595
  }
5051
- var WORKER_LOG_PATH = path18.join(EXE_AI_DIR, "workers.log");
6596
+ var WORKER_LOG_PATH = path20.join(EXE_AI_DIR, "workers.log");
5052
6597
  function openWorkerLog() {
5053
6598
  try {
5054
6599
  return openSync2(WORKER_LOG_PATH, "a");
@@ -5056,10 +6601,10 @@ function openWorkerLog() {
5056
6601
  return "ignore";
5057
6602
  }
5058
6603
  }
5059
- var CACHE_DIR2 = path18.join(EXE_AI_DIR, "session-cache");
6604
+ var CACHE_DIR2 = path20.join(EXE_AI_DIR, "session-cache");
5060
6605
  function loadInjectedIds(sessionId) {
5061
6606
  try {
5062
- const raw = readFileSync13(path18.join(CACHE_DIR2, `${sessionId}.json`), "utf8");
6607
+ const raw = readFileSync13(path20.join(CACHE_DIR2, `${sessionId}.json`), "utf8");
5063
6608
  return new Set(JSON.parse(raw));
5064
6609
  } catch {
5065
6610
  return /* @__PURE__ */ new Set();
@@ -5067,9 +6612,9 @@ function loadInjectedIds(sessionId) {
5067
6612
  }
5068
6613
  function saveInjectedIds(sessionId, ids) {
5069
6614
  try {
5070
- mkdirSync7(CACHE_DIR2, { recursive: true });
5071
- writeFileSync6(
5072
- path18.join(CACHE_DIR2, `${sessionId}.json`),
6615
+ mkdirSync8(CACHE_DIR2, { recursive: true });
6616
+ writeFileSync7(
6617
+ path20.join(CACHE_DIR2, `${sessionId}.json`),
5073
6618
  JSON.stringify([...ids])
5074
6619
  );
5075
6620
  } catch {
@@ -5152,7 +6697,7 @@ ${fresh.map(
5152
6697
  try {
5153
6698
  const { countPendingReviews: countPendingReviews2, countNewPendingReviewsSince: countNewPendingReviewsSince2 } = await Promise.resolve().then(() => (init_tasks_review(), tasks_review_exports));
5154
6699
  const sessionKey = getSessionKey();
5155
- const lastCheckPath = path18.join(CACHE_DIR2, `review-lastcheck-${sessionKey}.json`);
6700
+ const lastCheckPath = path20.join(CACHE_DIR2, `review-lastcheck-${sessionKey}.json`);
5156
6701
  let lastCheckedAt = "";
5157
6702
  try {
5158
6703
  lastCheckedAt = readFileSync13(lastCheckPath, "utf8").trim();
@@ -5213,8 +6758,8 @@ IMPORTANT: After completing your current task, you MUST address the pending revi
5213
6758
  function spawnPromptWorker(prompt, sessionId, agent) {
5214
6759
  if (!loadConfigSync().autoIngestion) return;
5215
6760
  try {
5216
- const workerPath = path18.resolve(
5217
- path18.dirname(fileURLToPath3(import.meta.url)),
6761
+ const workerPath = path20.resolve(
6762
+ path20.dirname(fileURLToPath3(import.meta.url)),
5218
6763
  "prompt-ingest-worker.js"
5219
6764
  );
5220
6765
  if (!existsSync16(workerPath)) {