@askexenow/exe-os 0.8.41 → 0.8.42

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 (74) 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 +1326 -655
  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 +2508 -1802
  9. package/dist/bin/exe-call.js +39 -1
  10. package/dist/bin/exe-dispatch.js +39 -2
  11. package/dist/bin/exe-doctor.js +790 -633
  12. package/dist/bin/exe-export-behaviors.js +792 -637
  13. package/dist/bin/exe-forget.js +145 -0
  14. package/dist/bin/exe-gateway.js +2487 -1878
  15. package/dist/bin/exe-heartbeat.js +147 -1
  16. package/dist/bin/exe-kill.js +795 -640
  17. package/dist/bin/exe-launch-agent.js +2168 -2008
  18. package/dist/bin/exe-link.js +9 -1
  19. package/dist/bin/exe-new-employee.js +6 -2
  20. package/dist/bin/exe-pending-messages.js +146 -1
  21. package/dist/bin/exe-pending-notifications.js +788 -631
  22. package/dist/bin/exe-pending-reviews.js +147 -1
  23. package/dist/bin/exe-rename.js +23 -0
  24. package/dist/bin/exe-review.js +490 -327
  25. package/dist/bin/exe-search.js +154 -3
  26. package/dist/bin/exe-session-cleanup.js +2466 -413
  27. package/dist/bin/exe-status.js +474 -317
  28. package/dist/bin/exe-team.js +474 -317
  29. package/dist/bin/git-sweep.js +2690 -150
  30. package/dist/bin/graph-backfill.js +794 -637
  31. package/dist/bin/graph-export.js +798 -641
  32. package/dist/bin/scan-tasks.js +2951 -44
  33. package/dist/bin/setup.js +47 -25
  34. package/dist/bin/shard-migrate.js +792 -637
  35. package/dist/bin/wiki-sync.js +794 -637
  36. package/dist/gateway/index.js +2504 -1895
  37. package/dist/hooks/bug-report-worker.js +2118 -576
  38. package/dist/hooks/commit-complete.js +2689 -149
  39. package/dist/hooks/error-recall.js +154 -3
  40. package/dist/hooks/ingest-worker.js +1420 -814
  41. package/dist/hooks/instructions-loaded.js +151 -0
  42. package/dist/hooks/notification.js +153 -2
  43. package/dist/hooks/post-compact.js +164 -0
  44. package/dist/hooks/pre-compact.js +3073 -101
  45. package/dist/hooks/pre-tool-use.js +151 -0
  46. package/dist/hooks/prompt-ingest-worker.js +1700 -1541
  47. package/dist/hooks/prompt-submit.js +2658 -1113
  48. package/dist/hooks/response-ingest-worker.js +151 -5
  49. package/dist/hooks/session-end.js +153 -2
  50. package/dist/hooks/session-start.js +154 -3
  51. package/dist/hooks/stop.js +151 -0
  52. package/dist/hooks/subagent-stop.js +151 -0
  53. package/dist/hooks/summary-worker.js +160 -6
  54. package/dist/index.js +278 -100
  55. package/dist/lib/cloud-sync.js +9 -1
  56. package/dist/lib/consolidation.js +69 -2
  57. package/dist/lib/database.js +19 -0
  58. package/dist/lib/device-registry.js +19 -0
  59. package/dist/lib/employee-templates.js +20 -1
  60. package/dist/lib/exe-daemon.js +236 -16
  61. package/dist/lib/hybrid-search.js +154 -3
  62. package/dist/lib/messaging.js +39 -2
  63. package/dist/lib/schedules.js +792 -637
  64. package/dist/lib/store.js +796 -636
  65. package/dist/lib/tasks.js +1614 -1091
  66. package/dist/lib/tmux-routing.js +149 -9
  67. package/dist/mcp/server.js +1810 -1137
  68. package/dist/mcp/tools/create-task.js +2280 -828
  69. package/dist/mcp/tools/list-tasks.js +2788 -159
  70. package/dist/mcp/tools/send-message.js +39 -2
  71. package/dist/mcp/tools/update-task.js +64 -0
  72. package/dist/runtime/index.js +235 -67
  73. package/dist/tui/App.js +1440 -646
  74. package/package.json +3 -2
@@ -26,6 +26,61 @@ var __copyProps = (to, from, except, desc) => {
26
26
  };
27
27
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
28
 
29
+ // src/lib/state-bus.ts
30
+ var StateBus, orgBus;
31
+ var init_state_bus = __esm({
32
+ "src/lib/state-bus.ts"() {
33
+ "use strict";
34
+ StateBus = class {
35
+ handlers = /* @__PURE__ */ new Map();
36
+ globalHandlers = /* @__PURE__ */ new Set();
37
+ /** Emit an event to all subscribers */
38
+ emit(event) {
39
+ const typeHandlers = this.handlers.get(event.type);
40
+ if (typeHandlers) {
41
+ for (const handler of typeHandlers) {
42
+ try {
43
+ handler(event);
44
+ } catch {
45
+ }
46
+ }
47
+ }
48
+ for (const handler of this.globalHandlers) {
49
+ try {
50
+ handler(event);
51
+ } catch {
52
+ }
53
+ }
54
+ }
55
+ /** Subscribe to a specific event type */
56
+ on(type, handler) {
57
+ if (!this.handlers.has(type)) {
58
+ this.handlers.set(type, /* @__PURE__ */ new Set());
59
+ }
60
+ this.handlers.get(type).add(handler);
61
+ }
62
+ /** Subscribe to ALL events */
63
+ onAny(handler) {
64
+ this.globalHandlers.add(handler);
65
+ }
66
+ /** Unsubscribe from a specific event type */
67
+ off(type, handler) {
68
+ this.handlers.get(type)?.delete(handler);
69
+ }
70
+ /** Unsubscribe from ALL events */
71
+ offAny(handler) {
72
+ this.globalHandlers.delete(handler);
73
+ }
74
+ /** Remove all listeners */
75
+ clear() {
76
+ this.handlers.clear();
77
+ this.globalHandlers.clear();
78
+ }
79
+ };
80
+ orgBus = new StateBus();
81
+ }
82
+ });
83
+
29
84
  // src/gateway/crm-bridge.ts
30
85
  var crm_bridge_exports = {};
31
86
  __export(crm_bridge_exports, {
@@ -575,6 +630,13 @@ async function ensureSchema() {
575
630
  });
576
631
  } catch {
577
632
  }
633
+ try {
634
+ await client.execute({
635
+ sql: `ALTER TABLE tasks ADD COLUMN session_scope TEXT`,
636
+ args: []
637
+ });
638
+ } catch {
639
+ }
578
640
  try {
579
641
  await client.execute({
580
642
  sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
@@ -1021,6 +1083,18 @@ async function ensureSchema() {
1021
1083
  CREATE INDEX IF NOT EXISTS idx_session_kills_agent
1022
1084
  ON session_kills(agent_id);
1023
1085
  `);
1086
+ await client.execute(`
1087
+ CREATE TABLE IF NOT EXISTS global_procedures (
1088
+ id TEXT PRIMARY KEY,
1089
+ title TEXT NOT NULL,
1090
+ content TEXT NOT NULL,
1091
+ priority TEXT NOT NULL DEFAULT 'p0',
1092
+ domain TEXT,
1093
+ active INTEGER NOT NULL DEFAULT 1,
1094
+ created_at TEXT NOT NULL,
1095
+ updated_at TEXT NOT NULL
1096
+ )
1097
+ `);
1024
1098
  await client.executeMultiple(`
1025
1099
  CREATE TABLE IF NOT EXISTS conversations (
1026
1100
  id TEXT PRIMARY KEY,
@@ -2135,6 +2209,71 @@ var init_shard_manager = __esm({
2135
2209
  }
2136
2210
  });
2137
2211
 
2212
+ // src/lib/global-procedures.ts
2213
+ var global_procedures_exports = {};
2214
+ __export(global_procedures_exports, {
2215
+ deactivateGlobalProcedure: () => deactivateGlobalProcedure,
2216
+ getGlobalProceduresBlock: () => getGlobalProceduresBlock,
2217
+ loadGlobalProcedures: () => loadGlobalProcedures,
2218
+ storeGlobalProcedure: () => storeGlobalProcedure
2219
+ });
2220
+ import { randomUUID as randomUUID2 } from "crypto";
2221
+ async function loadGlobalProcedures() {
2222
+ const client = getClient();
2223
+ const result = await client.execute({
2224
+ sql: "SELECT * FROM global_procedures WHERE active = 1 ORDER BY priority ASC, created_at ASC",
2225
+ args: []
2226
+ });
2227
+ const procedures = result.rows;
2228
+ if (procedures.length > 0) {
2229
+ _cache = procedures.map((p) => `### ${p.title}
2230
+ ${p.content}`).join("\n\n");
2231
+ } else {
2232
+ _cache = "";
2233
+ }
2234
+ _cacheLoaded = true;
2235
+ return procedures;
2236
+ }
2237
+ function getGlobalProceduresBlock() {
2238
+ if (!_cacheLoaded) return "";
2239
+ if (!_cache) return "";
2240
+ return `## Organization-Wide Procedures (MANDATORY \u2014 supersedes all other rules)
2241
+
2242
+ ${_cache}
2243
+ `;
2244
+ }
2245
+ async function storeGlobalProcedure(input) {
2246
+ const id = randomUUID2();
2247
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2248
+ const client = getClient();
2249
+ await client.execute({
2250
+ sql: `INSERT INTO global_procedures (id, title, content, priority, domain, active, created_at, updated_at)
2251
+ VALUES (?, ?, ?, ?, ?, 1, ?, ?)`,
2252
+ args: [id, input.title, input.content, input.priority ?? "p0", input.domain ?? null, now, now]
2253
+ });
2254
+ await loadGlobalProcedures();
2255
+ return id;
2256
+ }
2257
+ async function deactivateGlobalProcedure(id) {
2258
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2259
+ const client = getClient();
2260
+ const result = await client.execute({
2261
+ sql: "UPDATE global_procedures SET active = 0, updated_at = ? WHERE id = ?",
2262
+ args: [now, id]
2263
+ });
2264
+ await loadGlobalProcedures();
2265
+ return result.rowsAffected > 0;
2266
+ }
2267
+ var _cache, _cacheLoaded;
2268
+ var init_global_procedures = __esm({
2269
+ "src/lib/global-procedures.ts"() {
2270
+ "use strict";
2271
+ init_database();
2272
+ _cache = "";
2273
+ _cacheLoaded = false;
2274
+ }
2275
+ });
2276
+
2138
2277
  // src/lib/store.ts
2139
2278
  var store_exports = {};
2140
2279
  __export(store_exports, {
@@ -2214,6 +2353,11 @@ async function initStore(options) {
2214
2353
  "version-query"
2215
2354
  );
2216
2355
  _nextVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
2356
+ try {
2357
+ const { loadGlobalProcedures: loadGlobalProcedures2 } = await Promise.resolve().then(() => (init_global_procedures(), global_procedures_exports));
2358
+ await loadGlobalProcedures2();
2359
+ } catch {
2360
+ }
2217
2361
  }
2218
2362
  function classifyTier(record) {
2219
2363
  if (record.tool_name === "commit_to_long_term_memory" && (record.importance ?? 0) >= 8) return 1;
@@ -2255,6 +2399,12 @@ async function writeMemory(record) {
2255
2399
  supersedes_id: record.supersedes_id ?? null
2256
2400
  };
2257
2401
  _pendingRecords.push(dbRow);
2402
+ orgBus.emit({
2403
+ type: "memory_stored",
2404
+ agentId: record.agent_id,
2405
+ project: record.project_name,
2406
+ timestamp: record.timestamp
2407
+ });
2258
2408
  const MAX_PENDING = 1e3;
2259
2409
  if (_pendingRecords.length > MAX_PENDING) {
2260
2410
  const dropped = _pendingRecords.length - MAX_PENDING;
@@ -2600,6 +2750,7 @@ var init_store = __esm({
2600
2750
  init_database();
2601
2751
  init_keychain();
2602
2752
  init_config();
2753
+ init_state_bus();
2603
2754
  INIT_MAX_RETRIES = 3;
2604
2755
  INIT_RETRY_DELAY_MS = 1e3;
2605
2756
  _pendingRecords = [];
@@ -2771,7 +2922,7 @@ __export(license_exports, {
2771
2922
  validateLicense: () => validateLicense
2772
2923
  });
2773
2924
  import { readFileSync as readFileSync3, writeFileSync, existsSync as existsSync5, mkdirSync as mkdirSync2 } from "fs";
2774
- import { randomUUID as randomUUID2 } from "crypto";
2925
+ import { randomUUID as randomUUID3 } from "crypto";
2775
2926
  import path5 from "path";
2776
2927
  import { jwtVerify, importSPKI } from "jose";
2777
2928
  async function fetchRetry(url, init) {
@@ -2798,7 +2949,7 @@ function loadDeviceId() {
2798
2949
  }
2799
2950
  } catch {
2800
2951
  }
2801
- const id = randomUUID2();
2952
+ const id = randomUUID3();
2802
2953
  mkdirSync2(EXE_AI_DIR, { recursive: true });
2803
2954
  writeFileSync(DEVICE_ID_PATH, id, "utf8");
2804
2955
  return id;
@@ -3099,7 +3250,7 @@ var whatsapp_exports = {};
3099
3250
  __export(whatsapp_exports, {
3100
3251
  WhatsAppAdapter: () => WhatsAppAdapter
3101
3252
  });
3102
- import { randomUUID as randomUUID3 } from "crypto";
3253
+ import { randomUUID as randomUUID4 } from "crypto";
3103
3254
  import { homedir } from "os";
3104
3255
  import { join } from "path";
3105
3256
  import { mkdirSync as mkdirSync3 } from "fs";
@@ -3285,7 +3436,7 @@ var init_whatsapp = __esm({
3285
3436
  const location = this.extractLocation(msg.message);
3286
3437
  const dataCategory = location ? "location" : "message";
3287
3438
  return {
3288
- messageId: msg.key.id ?? randomUUID3(),
3439
+ messageId: msg.key.id ?? randomUUID4(),
3289
3440
  platform: "whatsapp",
3290
3441
  senderId,
3291
3442
  senderName: msg.pushName ?? void 0,
@@ -3330,7 +3481,7 @@ var init_whatsapp = __esm({
3330
3481
  }
3331
3482
  const timestamp = receipt.readTimestamp ?? receipt.receiptTimestamp ?? Date.now() / 1e3;
3332
3483
  return {
3333
- messageId: randomUUID3(),
3484
+ messageId: randomUUID4(),
3334
3485
  platform: "whatsapp",
3335
3486
  senderId: remoteJid.replace("@s.whatsapp.net", "").replace("@g.us", ""),
3336
3487
  channelId: remoteJid,
@@ -3353,7 +3504,7 @@ var init_whatsapp = __esm({
3353
3504
  const phone = id.replace("@s.whatsapp.net", "").replace("@g.us", "");
3354
3505
  const name = contact.name ?? contact.notify ?? phone;
3355
3506
  return {
3356
- messageId: randomUUID3(),
3507
+ messageId: randomUUID4(),
3357
3508
  platform: "whatsapp",
3358
3509
  senderId: phone,
3359
3510
  senderName: name,
@@ -3377,7 +3528,7 @@ var init_whatsapp = __esm({
3377
3528
  const participants = (group.participants ?? []).map((p) => p.id ?? p);
3378
3529
  const admins = (group.participants ?? []).filter((p) => p.admin === "admin" || p.admin === "superadmin").map((p) => p.id ?? p);
3379
3530
  return {
3380
- messageId: randomUUID3(),
3531
+ messageId: randomUUID4(),
3381
3532
  platform: "whatsapp",
3382
3533
  senderId: groupId,
3383
3534
  channelId: groupId,
@@ -3402,7 +3553,7 @@ var init_whatsapp = __esm({
3402
3553
  if (!reactionData) return null;
3403
3554
  const remoteJid = key.remoteJid ?? "";
3404
3555
  return {
3405
- messageId: randomUUID3(),
3556
+ messageId: randomUUID4(),
3406
3557
  platform: "whatsapp",
3407
3558
  senderId: reactionData.key?.participant ?? reactionData.key?.remoteJid?.replace("@s.whatsapp.net", "") ?? "",
3408
3559
  channelId: remoteJid,
@@ -3424,7 +3575,7 @@ var init_whatsapp = __esm({
3424
3575
  if (!chatId) return null;
3425
3576
  const caller = call.from?.replace("@s.whatsapp.net", "") ?? "";
3426
3577
  return {
3427
- messageId: randomUUID3(),
3578
+ messageId: randomUUID4(),
3428
3579
  platform: "whatsapp",
3429
3580
  senderId: caller,
3430
3581
  channelId: chatId,
@@ -3770,7 +3921,7 @@ var slack_exports = {};
3770
3921
  __export(slack_exports, {
3771
3922
  SlackAdapter: () => SlackAdapter
3772
3923
  });
3773
- import { randomUUID as randomUUID4 } from "crypto";
3924
+ import { randomUUID as randomUUID5 } from "crypto";
3774
3925
  var SlackAdapter;
3775
3926
  var init_slack = __esm({
3776
3927
  "src/gateway/adapters/slack.ts"() {
@@ -3812,7 +3963,7 @@ var init_slack = __esm({
3812
3963
  if (event.subtype) return;
3813
3964
  const isGroup = event.channel_type !== "im";
3814
3965
  const normalized = {
3815
- messageId: event.client_msg_id ?? event.ts ?? randomUUID4(),
3966
+ messageId: event.client_msg_id ?? event.ts ?? randomUUID5(),
3816
3967
  platform: "slack",
3817
3968
  senderId: event.user ?? "",
3818
3969
  channelId: event.channel ?? "",
@@ -3874,7 +4025,7 @@ var init_slack = __esm({
3874
4025
  if (!event.text) return;
3875
4026
  const isGroup = event.channel_type !== "im";
3876
4027
  const normalized = {
3877
- messageId: event.ts ?? randomUUID4(),
4028
+ messageId: event.ts ?? randomUUID5(),
3878
4029
  platform: "slack",
3879
4030
  senderId: event.user ?? "",
3880
4031
  senderName: event.user_profile?.display_name ?? event.user_profile?.real_name ?? void 0,
@@ -4097,7 +4248,7 @@ var email_exports = {};
4097
4248
  __export(email_exports, {
4098
4249
  EmailAdapter: () => EmailAdapter
4099
4250
  });
4100
- import { randomUUID as randomUUID5 } from "crypto";
4251
+ import { randomUUID as randomUUID6 } from "crypto";
4101
4252
  import { createTransport } from "nodemailer";
4102
4253
  function extractEmailAddress(from) {
4103
4254
  const match = from.match(/<([^>]+)>/);
@@ -4179,7 +4330,7 @@ var init_email = __esm({
4179
4330
  const senderEmail = extractEmailAddress(from);
4180
4331
  const media = this.extractMedia(payload);
4181
4332
  const normalized = {
4182
- messageId: payload.message_id ?? randomUUID5(),
4333
+ messageId: payload.message_id ?? randomUUID6(),
4183
4334
  platform: "email",
4184
4335
  senderId: senderEmail,
4185
4336
  senderName: extractSenderName(from),
@@ -4240,7 +4391,7 @@ var webhook_exports = {};
4240
4391
  __export(webhook_exports, {
4241
4392
  WebhookAdapter: () => WebhookAdapter
4242
4393
  });
4243
- import { randomUUID as randomUUID6 } from "crypto";
4394
+ import { randomUUID as randomUUID7 } from "crypto";
4244
4395
  function resolvePath(obj, path20) {
4245
4396
  let current = obj;
4246
4397
  for (const segment of path20.split(".")) {
@@ -4296,7 +4447,7 @@ var init_webhook = __esm({
4296
4447
  if (!text || !senderId) return;
4297
4448
  const channelId = this.fieldMap.channelId ? String(resolvePath(rawPayload, this.fieldMap.channelId) ?? senderId) : senderId;
4298
4449
  const senderName = this.fieldMap.senderName ? String(resolvePath(rawPayload, this.fieldMap.senderName) ?? "") || void 0 : void 0;
4299
- const messageId = this.fieldMap.messageId ? String(resolvePath(rawPayload, this.fieldMap.messageId) ?? randomUUID6()) : randomUUID6();
4450
+ const messageId = this.fieldMap.messageId ? String(resolvePath(rawPayload, this.fieldMap.messageId) ?? randomUUID7()) : randomUUID7();
4300
4451
  const timestamp = this.fieldMap.timestamp ? String(resolvePath(rawPayload, this.fieldMap.timestamp) ?? (/* @__PURE__ */ new Date()).toISOString()) : (/* @__PURE__ */ new Date()).toISOString();
4301
4452
  const normalized = {
4302
4453
  messageId,
@@ -4799,2159 +4950,2607 @@ var init_plan_limits = __esm({
4799
4950
  }
4800
4951
  });
4801
4952
 
4802
- // src/lib/tmux-routing.ts
4803
- import { execFileSync as execFileSync2, execSync as execSync4 } from "child_process";
4804
- import { readFileSync as readFileSync9, writeFileSync as writeFileSync4, mkdirSync as mkdirSync6, existsSync as existsSync10, appendFileSync } from "fs";
4953
+ // src/lib/notifications.ts
4954
+ import crypto3 from "crypto";
4805
4955
  import path11 from "path";
4806
4956
  import os6 from "os";
4807
- import { fileURLToPath as fileURLToPath2 } from "url";
4808
- import { unlinkSync as unlinkSync2 } from "fs";
4809
- function spawnLockPath(sessionName) {
4810
- return path11.join(SPAWN_LOCK_DIR, `${sessionName}.lock`);
4811
- }
4812
- function isProcessAlive(pid) {
4957
+ import {
4958
+ readFileSync as readFileSync9,
4959
+ readdirSync as readdirSync2,
4960
+ unlinkSync as unlinkSync2,
4961
+ existsSync as existsSync10,
4962
+ rmdirSync
4963
+ } from "fs";
4964
+ async function writeNotification(notification) {
4813
4965
  try {
4814
- process.kill(pid, 0);
4815
- return true;
4816
- } catch {
4817
- return false;
4818
- }
4819
- }
4820
- function acquireSpawnLock2(sessionName) {
4821
- if (!existsSync10(SPAWN_LOCK_DIR)) {
4822
- mkdirSync6(SPAWN_LOCK_DIR, { recursive: true });
4823
- }
4824
- const lockFile = spawnLockPath(sessionName);
4825
- if (existsSync10(lockFile)) {
4826
- try {
4827
- const lock = JSON.parse(readFileSync9(lockFile, "utf8"));
4828
- const age = Date.now() - lock.timestamp;
4829
- if (isProcessAlive(lock.pid) && age < 6e4) {
4830
- return false;
4831
- }
4832
- } catch {
4833
- }
4966
+ const client = getClient();
4967
+ const id = crypto3.randomUUID();
4968
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4969
+ await client.execute({
4970
+ sql: `INSERT INTO notifications (id, agent_id, agent_role, event, project, summary, task_file, read, created_at)
4971
+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)`,
4972
+ args: [
4973
+ id,
4974
+ notification.agentId,
4975
+ notification.agentRole,
4976
+ notification.event,
4977
+ notification.project,
4978
+ notification.summary,
4979
+ notification.taskFile ?? null,
4980
+ now
4981
+ ]
4982
+ });
4983
+ } catch (err) {
4984
+ process.stderr.write(`[notifications] WRITE FAILED: ${err instanceof Error ? err.message : String(err)}
4985
+ `);
4834
4986
  }
4835
- writeFileSync4(lockFile, JSON.stringify({ pid: process.pid, timestamp: Date.now() }));
4836
- return true;
4837
4987
  }
4838
- function releaseSpawnLock2(sessionName) {
4988
+ async function markAsReadByTaskFile(taskFile) {
4839
4989
  try {
4840
- unlinkSync2(spawnLockPath(sessionName));
4990
+ const client = getClient();
4991
+ await client.execute({
4992
+ sql: "UPDATE notifications SET read = 1 WHERE task_file = ? AND read = 0",
4993
+ args: [taskFile]
4994
+ });
4841
4995
  } catch {
4842
4996
  }
4843
4997
  }
4844
- function resolveBehaviorsExporterScript() {
4845
- try {
4846
- const thisFile = fileURLToPath2(import.meta.url);
4847
- const scriptPath = path11.join(
4848
- path11.dirname(thisFile),
4849
- "..",
4850
- "bin",
4851
- "exe-export-behaviors.js"
4852
- );
4853
- return existsSync10(scriptPath) ? scriptPath : null;
4854
- } catch {
4855
- return null;
4998
+ var init_notifications = __esm({
4999
+ "src/lib/notifications.ts"() {
5000
+ "use strict";
5001
+ init_database();
4856
5002
  }
4857
- }
4858
- function exportBehaviorsSync(agentId, projectName, sessionKey) {
4859
- const script = resolveBehaviorsExporterScript();
4860
- if (!script) return null;
5003
+ });
5004
+
5005
+ // src/lib/session-kill-telemetry.ts
5006
+ import crypto4 from "crypto";
5007
+ async function recordSessionKill(input) {
4861
5008
  try {
4862
- const output = execFileSync2(
4863
- process.execPath,
4864
- [script, agentId, projectName, sessionKey],
4865
- { encoding: "utf-8", timeout: BEHAVIORS_EXPORT_TIMEOUT_MS }
4866
- ).trim();
4867
- return output.length > 0 ? output : null;
5009
+ const client = getClient();
5010
+ await client.execute({
5011
+ sql: `INSERT INTO session_kills
5012
+ (id, session_name, agent_id, killed_at, reason,
5013
+ ticks_idle, estimated_tokens_saved)
5014
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
5015
+ args: [
5016
+ crypto4.randomUUID(),
5017
+ input.sessionName,
5018
+ input.agentId,
5019
+ (/* @__PURE__ */ new Date()).toISOString(),
5020
+ input.reason,
5021
+ input.ticksIdle ?? null,
5022
+ input.estimatedTokensSaved ?? null
5023
+ ]
5024
+ });
4868
5025
  } catch (err) {
4869
5026
  process.stderr.write(
4870
- `[tmux-routing] behaviors export failed for ${agentId}: ${err instanceof Error ? err.message : String(err)}
5027
+ `[session-kill-telemetry] write failed: ${err instanceof Error ? err.message : String(err)}
4871
5028
  `
4872
5029
  );
4873
- return null;
4874
5030
  }
4875
5031
  }
4876
- function getMySession() {
4877
- return getTransport().getMySession();
4878
- }
4879
- function employeeSessionName(employee, exeSession, instance) {
4880
- const suffix = instance != null && instance > 0 ? String(instance) : "";
4881
- return `${employee}${suffix}-${exeSession}`;
4882
- }
4883
- function extractRootExe(name) {
4884
- const match = name.match(/(exe\d+)$/);
4885
- return match?.[1] ?? null;
4886
- }
4887
- function getParentExe(sessionKey) {
4888
- try {
4889
- const data = JSON.parse(readFileSync9(path11.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
4890
- return data.parentExe || null;
4891
- } catch {
4892
- return null;
5032
+ var init_session_kill_telemetry = __esm({
5033
+ "src/lib/session-kill-telemetry.ts"() {
5034
+ "use strict";
5035
+ init_database();
4893
5036
  }
4894
- }
4895
- function getDispatchedBy(sessionKey) {
4896
- try {
4897
- const data = JSON.parse(readFileSync9(
4898
- path11.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`),
4899
- "utf8"
4900
- ));
4901
- return data.dispatchedBy ?? data.parentExe ?? null;
4902
- } catch {
4903
- return null;
5037
+ });
5038
+
5039
+ // src/lib/tasks-crud.ts
5040
+ import crypto5 from "crypto";
5041
+ import path12 from "path";
5042
+ import { execSync as execSync4 } from "child_process";
5043
+ import { mkdir as mkdir4, writeFile as writeFile4, appendFile } from "fs/promises";
5044
+ import { existsSync as existsSync11, readFileSync as readFileSync10 } from "fs";
5045
+ async function writeCheckpoint(input) {
5046
+ const client = getClient();
5047
+ const row = await resolveTask(client, input.taskId);
5048
+ const taskId = String(row.id);
5049
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5050
+ const blockedByIds = [];
5051
+ if (row.blocked_by) {
5052
+ blockedByIds.push(String(row.blocked_by));
4904
5053
  }
4905
- }
4906
- function resolveExeSession() {
4907
- const mySession = getMySession();
4908
- if (!mySession) return null;
4909
- try {
4910
- const key = getSessionKey();
4911
- const parentExe = getParentExe(key);
4912
- if (parentExe) {
4913
- return extractRootExe(parentExe) ?? parentExe;
4914
- }
4915
- } catch {
5054
+ const checkpoint = {
5055
+ step: input.step,
5056
+ context_summary: input.contextSummary,
5057
+ files_touched: input.filesTouched ?? [],
5058
+ blocked_by_ids: blockedByIds,
5059
+ last_checkpoint_at: now
5060
+ };
5061
+ const result = await client.execute({
5062
+ sql: `UPDATE tasks SET checkpoint = ?, checkpoint_count = checkpoint_count + 1, updated_at = ? WHERE id = ?`,
5063
+ args: [JSON.stringify(checkpoint), now, taskId]
5064
+ });
5065
+ if (result.rowsAffected === 0) {
5066
+ throw new Error(`Checkpoint write failed: task ${taskId} not found`);
4916
5067
  }
4917
- return extractRootExe(mySession) ?? mySession;
4918
- }
4919
- function isEmployeeAlive(sessionName) {
4920
- return getTransport().isAlive(sessionName);
5068
+ const countResult = await client.execute({
5069
+ sql: "SELECT checkpoint_count FROM tasks WHERE id = ?",
5070
+ args: [taskId]
5071
+ });
5072
+ const checkpointCount = Number(countResult.rows[0]?.checkpoint_count ?? 1);
5073
+ return { checkpointCount };
4921
5074
  }
4922
- function findFreeInstance(employeeName, exeSession, maxInstances = 10, isAlive = isEmployeeAlive) {
4923
- const base = employeeSessionName(employeeName, exeSession);
4924
- if (!isAlive(base) && acquireSpawnLock2(base)) return 0;
4925
- for (let i = 2; i <= maxInstances; i++) {
4926
- const candidate = employeeSessionName(employeeName, exeSession, i);
4927
- if (!isAlive(candidate) && acquireSpawnLock2(candidate)) return i;
4928
- }
4929
- return null;
5075
+ function extractParentFromContext(contextBody) {
5076
+ if (!contextBody) return null;
5077
+ const match = contextBody.match(
5078
+ /Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
5079
+ );
5080
+ return match ? match[1].toLowerCase() : null;
4930
5081
  }
4931
- function readDebounceState() {
4932
- try {
4933
- if (!existsSync10(DEBOUNCE_FILE)) return {};
4934
- return JSON.parse(readFileSync9(DEBOUNCE_FILE, "utf8"));
4935
- } catch {
4936
- return {};
4937
- }
5082
+ function slugify(title) {
5083
+ return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
4938
5084
  }
4939
- function writeDebounceState(state) {
4940
- try {
4941
- if (!existsSync10(SESSION_CACHE)) mkdirSync6(SESSION_CACHE, { recursive: true });
4942
- writeFileSync4(DEBOUNCE_FILE, JSON.stringify(state));
4943
- } catch {
5085
+ async function resolveTask(client, identifier) {
5086
+ let result = await client.execute({
5087
+ sql: "SELECT * FROM tasks WHERE id = ?",
5088
+ args: [identifier]
5089
+ });
5090
+ if (result.rows.length === 1) return result.rows[0];
5091
+ result = await client.execute({
5092
+ sql: "SELECT * FROM tasks WHERE task_file LIKE ?",
5093
+ args: [`%${identifier}%`]
5094
+ });
5095
+ if (result.rows.length === 1) return result.rows[0];
5096
+ if (result.rows.length > 1) {
5097
+ const exact = result.rows.filter(
5098
+ (r) => String(r.task_file).endsWith(`/${identifier}.md`)
5099
+ );
5100
+ if (exact.length === 1) return exact[0];
5101
+ const candidates = exact.length > 1 ? exact : result.rows;
5102
+ const active = candidates.filter(
5103
+ (r) => !["done", "cancelled"].includes(String(r.status))
5104
+ );
5105
+ if (active.length === 1) return active[0];
5106
+ const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
5107
+ throw new Error(
5108
+ `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
5109
+ );
4944
5110
  }
4945
- }
4946
- function isDebounced(targetSession) {
4947
- const state = readDebounceState();
4948
- const lastSent = state[targetSession] ?? 0;
4949
- return Date.now() - lastSent < INTERCOM_DEBOUNCE_MS;
4950
- }
4951
- function recordDebounce(targetSession) {
4952
- const state = readDebounceState();
4953
- state[targetSession] = Date.now();
4954
- const cutoff = Date.now() - DEBOUNCE_CLEANUP_AGE_MS;
4955
- for (const key of Object.keys(state)) {
4956
- if ((state[key] ?? 0) < cutoff) delete state[key];
5111
+ result = await client.execute({
5112
+ sql: "SELECT * FROM tasks WHERE title LIKE ?",
5113
+ args: [`%${identifier}%`]
5114
+ });
5115
+ if (result.rows.length === 1) return result.rows[0];
5116
+ if (result.rows.length > 1) {
5117
+ const active = result.rows.filter(
5118
+ (r) => !["done", "cancelled"].includes(String(r.status))
5119
+ );
5120
+ if (active.length === 1) return active[0];
5121
+ const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
5122
+ throw new Error(
5123
+ `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
5124
+ );
4957
5125
  }
4958
- writeDebounceState(state);
5126
+ throw new Error(`Task not found: ${identifier}`);
4959
5127
  }
4960
- function logIntercom(msg) {
4961
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${msg}
4962
- `;
4963
- process.stderr.write(`[intercom] ${msg}
4964
- `);
4965
- try {
4966
- appendFileSync(INTERCOM_LOG2, line);
4967
- } catch {
5128
+ async function createTaskCore(input) {
5129
+ const client = getClient();
5130
+ const id = crypto5.randomUUID();
5131
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5132
+ const slug = slugify(input.title);
5133
+ const taskFile = input.taskFile ?? `exe/${input.assignedTo}/${slug}.md`;
5134
+ let blockedById = null;
5135
+ const initialStatus = input.blockedBy ? "blocked" : "open";
5136
+ if (input.blockedBy) {
5137
+ const blocker = await resolveTask(client, input.blockedBy);
5138
+ blockedById = String(blocker.id);
4968
5139
  }
4969
- }
4970
- function getSessionState(sessionName) {
4971
- const transport = getTransport();
4972
- if (!transport.isAlive(sessionName)) return "offline";
4973
- try {
4974
- const pane = transport.capturePane(sessionName, 5);
4975
- if (!pane.includes("\u276F") && !pane.includes("Claude Code") && !BUSY_PATTERN.test(pane) && !/Running…/.test(pane)) {
4976
- if (/\$\s*$/.test(pane) || /% $/.test(pane.trimEnd())) {
4977
- return "no_claude";
5140
+ let parentTaskId = null;
5141
+ let parentRef = input.parentTaskId;
5142
+ if (!parentRef) {
5143
+ const extracted = extractParentFromContext(input.context);
5144
+ if (extracted) {
5145
+ parentRef = extracted;
5146
+ process.stderr.write(
5147
+ "[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
5148
+ );
5149
+ }
5150
+ }
5151
+ if (parentRef) {
5152
+ try {
5153
+ const parent = await resolveTask(client, parentRef);
5154
+ parentTaskId = String(parent.id);
5155
+ } catch (err) {
5156
+ if (!input.parentTaskId) {
5157
+ throw new Error(
5158
+ `create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
5159
+ );
4978
5160
  }
5161
+ throw err;
4979
5162
  }
4980
- if (/Running…/.test(pane)) return "tool";
4981
- if (BUSY_PATTERN.test(pane)) return "thinking";
4982
- return "idle";
4983
- } catch {
4984
- return "offline";
4985
5163
  }
4986
- }
4987
- function isExeSession(sessionName) {
4988
- return /^exe\d*$/.test(sessionName);
4989
- }
4990
- function sendIntercom(targetSession) {
4991
- const transport = getTransport();
4992
- if (isExeSession(targetSession)) {
4993
- logIntercom(`SKIP_EXE \u2192 ${targetSession} (exe sessions use prompt-submit hook)`);
4994
- return "skipped_exe";
5164
+ let warning;
5165
+ const dupCheck = await client.execute({
5166
+ sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
5167
+ args: [input.title, input.assignedTo]
5168
+ });
5169
+ if (dupCheck.rows.length > 0) {
5170
+ warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
4995
5171
  }
4996
- if (isDebounced(targetSession)) {
4997
- logIntercom(`DEBOUNCE \u2192 ${targetSession} (cross-process file debounce)`);
4998
- return "debounced";
5172
+ if (input.baseDir) {
5173
+ try {
5174
+ await mkdir4(path12.join(input.baseDir, "exe", "output"), { recursive: true });
5175
+ await mkdir4(path12.join(input.baseDir, "exe", "research"), { recursive: true });
5176
+ await ensureArchitectureDoc(input.baseDir, input.projectName);
5177
+ await ensureGitignoreExe(input.baseDir);
5178
+ } catch {
5179
+ }
4999
5180
  }
5181
+ const complexity = input.complexity ?? "standard";
5182
+ let sessionScope = null;
5000
5183
  try {
5001
- const sessions = transport.listSessions();
5002
- if (!sessions.includes(targetSession)) {
5003
- logIntercom(`SKIP \u2192 ${targetSession} (session not found)`);
5004
- return "failed";
5005
- }
5006
- const sessionState = getSessionState(targetSession);
5007
- if (sessionState === "no_claude") {
5008
- queueIntercom(targetSession, "claude not running in session");
5009
- recordDebounce(targetSession);
5010
- logIntercom(`QUEUED \u2192 ${targetSession} (no claude process \u2014 raw shell detected)`);
5011
- return "queued";
5012
- }
5013
- if (sessionState === "thinking" || sessionState === "tool") {
5014
- queueIntercom(targetSession, "session busy at send time");
5015
- recordDebounce(targetSession);
5016
- logIntercom(`QUEUED \u2192 ${targetSession} (session busy, will retry from queue)`);
5017
- return "queued";
5018
- }
5019
- if (transport.isPaneInCopyMode(targetSession)) {
5020
- logIntercom(`COPY_MODE \u2192 ${targetSession} (exiting copy mode first)`);
5021
- transport.sendKeys(targetSession, "q");
5022
- }
5023
- transport.sendKeys(targetSession, "/exe-intercom");
5024
- recordDebounce(targetSession);
5025
- logIntercom(`DELIVERED \u2192 ${targetSession} (fire-and-forget)`);
5026
- return "delivered";
5184
+ const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
5185
+ sessionScope = resolveExeSession2();
5027
5186
  } catch {
5028
- logIntercom(`FAIL \u2192 ${targetSession}`);
5029
- return "failed";
5030
5187
  }
5188
+ await client.execute({
5189
+ 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)
5190
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
5191
+ args: [
5192
+ id,
5193
+ input.title,
5194
+ input.assignedTo,
5195
+ input.assignedBy,
5196
+ input.projectName,
5197
+ input.priority,
5198
+ initialStatus,
5199
+ taskFile,
5200
+ blockedById,
5201
+ parentTaskId,
5202
+ input.reviewer ?? null,
5203
+ input.context,
5204
+ complexity,
5205
+ input.budgetTokens ?? null,
5206
+ input.budgetFallbackModel ?? null,
5207
+ 0,
5208
+ null,
5209
+ sessionScope,
5210
+ now,
5211
+ now
5212
+ ]
5213
+ });
5214
+ return {
5215
+ id,
5216
+ title: input.title,
5217
+ assignedTo: input.assignedTo,
5218
+ assignedBy: input.assignedBy,
5219
+ projectName: input.projectName,
5220
+ priority: input.priority,
5221
+ status: initialStatus,
5222
+ taskFile,
5223
+ createdAt: now,
5224
+ updatedAt: now,
5225
+ warning,
5226
+ budgetTokens: input.budgetTokens ?? null,
5227
+ budgetFallbackModel: input.budgetFallbackModel ?? null,
5228
+ tokensUsed: 0,
5229
+ tokensWarnedAt: null
5230
+ };
5031
5231
  }
5032
- function notifyParentExe(sessionKey) {
5033
- const target = getDispatchedBy(sessionKey);
5034
- if (!target) {
5035
- process.stderr.write(`[intercom] notifyParentExe: no dispatcher found for key ${sessionKey}
5036
- `);
5037
- return false;
5232
+ async function listTasks(input) {
5233
+ const client = getClient();
5234
+ const conditions = [];
5235
+ const args = [];
5236
+ if (input.assignedTo) {
5237
+ conditions.push("assigned_to = ?");
5238
+ args.push(input.assignedTo);
5038
5239
  }
5039
- process.stderr.write(`[intercom] notifyParentExe \u2192 ${target}
5040
- `);
5041
- const result = sendIntercom(target);
5042
- if (result === "failed") {
5043
- const rootExe = resolveExeSession();
5044
- if (rootExe && rootExe !== target) {
5045
- process.stderr.write(`[intercom] notifyParentExe: dispatcher ${target} dead, falling back to root exe ${rootExe}
5046
- `);
5047
- const fallback = sendIntercom(rootExe);
5048
- return fallback !== "failed";
5049
- }
5050
- return false;
5240
+ if (input.status) {
5241
+ conditions.push("status = ?");
5242
+ args.push(input.status);
5243
+ } else {
5244
+ conditions.push("status IN ('open', 'in_progress', 'blocked')");
5051
5245
  }
5052
- return true;
5053
- }
5054
- function ensureEmployee(employeeName, exeSession, projectDir, opts) {
5055
- if (employeeName === "exe") {
5056
- return { status: "failed", sessionName: "", error: "exe is the COO, not a dispatchable employee" };
5246
+ if (input.projectName) {
5247
+ conditions.push("project_name = ?");
5248
+ args.push(input.projectName);
5249
+ }
5250
+ if (input.priority) {
5251
+ conditions.push("priority = ?");
5252
+ args.push(input.priority);
5057
5253
  }
5058
5254
  try {
5059
- assertEmployeeLimitSync();
5060
- } catch (err) {
5061
- if (err instanceof PlanLimitError) {
5062
- return { status: "failed", sessionName: "", error: err.message };
5255
+ const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
5256
+ const session = resolveExeSession2();
5257
+ if (session) {
5258
+ conditions.push("(session_scope IS NULL OR session_scope = ?)");
5259
+ args.push(session);
5063
5260
  }
5261
+ } catch {
5064
5262
  }
5065
- if (/-exe\d*$/.test(employeeName)) {
5066
- const bare = employeeName.replace(/-exe\d*$/, "").replace(/\d+$/, "");
5067
- return {
5068
- status: "failed",
5069
- sessionName: "",
5070
- error: `Error: pass employee name ('${bare}'), not session name ('${employeeName}')`
5071
- };
5263
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
5264
+ const result = await client.execute({
5265
+ 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`,
5266
+ args
5267
+ });
5268
+ return result.rows.map((r) => ({
5269
+ id: String(r.id),
5270
+ title: String(r.title),
5271
+ assignedTo: String(r.assigned_to),
5272
+ assignedBy: String(r.assigned_by),
5273
+ projectName: String(r.project_name),
5274
+ priority: String(r.priority),
5275
+ status: String(r.status),
5276
+ taskFile: String(r.task_file),
5277
+ createdAt: String(r.created_at),
5278
+ updatedAt: String(r.updated_at),
5279
+ checkpointCount: Number(r.checkpoint_count ?? 0),
5280
+ budgetTokens: r.budget_tokens !== null ? Number(r.budget_tokens) : null,
5281
+ budgetFallbackModel: r.budget_fallback_model !== null ? String(r.budget_fallback_model) : null,
5282
+ tokensUsed: Number(r.tokens_used ?? 0),
5283
+ tokensWarnedAt: r.tokens_warned_at !== null ? Number(r.tokens_warned_at) : null
5284
+ }));
5285
+ }
5286
+ function checkStaleCompletion(taskContext, taskCreatedAt) {
5287
+ if (!taskContext) return null;
5288
+ if (!DELEGATION_KEYWORDS.test(taskContext)) return null;
5289
+ try {
5290
+ const since = new Date(taskCreatedAt).toISOString();
5291
+ const branch = execSync4(
5292
+ "git rev-parse --abbrev-ref HEAD 2>/dev/null",
5293
+ { encoding: "utf8", timeout: 3e3 }
5294
+ ).trim();
5295
+ const branchArg = branch && branch !== "HEAD" ? branch : "";
5296
+ const commitCount = execSync4(
5297
+ `git log --oneline --since="${since}" ${branchArg} 2>/dev/null | wc -l`,
5298
+ { encoding: "utf8", timeout: 5e3 }
5299
+ ).trim();
5300
+ const count = parseInt(commitCount, 10);
5301
+ if (count === 0) {
5302
+ return "WARNING: task closed with no new commits since creation. Verify work was actually produced.";
5303
+ }
5304
+ return null;
5305
+ } catch {
5306
+ return null;
5072
5307
  }
5073
- let effectiveInstance = opts?.instance;
5074
- if (effectiveInstance === void 0 && opts?.autoInstance) {
5075
- const free = findFreeInstance(
5076
- employeeName,
5077
- exeSession,
5078
- opts.maxAutoInstances ?? 10
5308
+ }
5309
+ async function updateTaskStatus(input) {
5310
+ const client = getClient();
5311
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5312
+ const row = await resolveTask(client, input.taskId);
5313
+ const taskId = String(row.id);
5314
+ const taskFile = String(row.task_file);
5315
+ if (input.status === "done" && String(row.assigned_by) === "system" && taskFile.includes("review-")) {
5316
+ process.stderr.write(
5317
+ `[updateTask] Review task "${String(row.title)}" being marked done (assigned to ${String(row.assigned_to)})
5318
+ `
5079
5319
  );
5080
- if (free === null) {
5081
- return {
5082
- status: "failed",
5083
- sessionName: employeeSessionName(employeeName, exeSession),
5084
- error: `All ${opts.maxAutoInstances ?? 10} instances of ${employeeName} are alive \u2014 cap reached`
5085
- };
5320
+ }
5321
+ if (input.status === "done") {
5322
+ const existingRow = await client.execute({
5323
+ sql: "SELECT context, created_at FROM tasks WHERE id = ?",
5324
+ args: [taskId]
5325
+ });
5326
+ if (existingRow.rows.length > 0) {
5327
+ const ctx = existingRow.rows[0];
5328
+ const warning = checkStaleCompletion(ctx.context, ctx.created_at);
5329
+ if (warning) {
5330
+ input.result = input.result ? `\u26A0\uFE0F ${warning}
5331
+
5332
+ ${input.result}` : `\u26A0\uFE0F ${warning}`;
5333
+ process.stderr.write(`[tasks] ${warning} (task: ${taskId})
5334
+ `);
5335
+ }
5086
5336
  }
5087
- effectiveInstance = free === 0 ? void 0 : free;
5088
5337
  }
5089
- const sessionName = employeeSessionName(employeeName, exeSession, effectiveInstance);
5090
- if (isEmployeeAlive(sessionName)) {
5091
- const result2 = sendIntercom(sessionName);
5092
- if (result2 === "acknowledged" || result2 === "skipped_exe" || result2 === "debounced" || result2 === "queued") {
5093
- return { status: "intercom_sent", sessionName };
5338
+ if (input.status === "in_progress") {
5339
+ const tmuxSession = process.env.TMUX_PANE ?? process.env.MY_TMUX_SESSION ?? "unknown";
5340
+ const claim = await client.execute({
5341
+ sql: `UPDATE tasks
5342
+ SET status = 'in_progress', assigned_tmux = ?, updated_at = ?
5343
+ WHERE id = ? AND status = 'open'`,
5344
+ args: [tmuxSession, now, taskId]
5345
+ });
5346
+ if (claim.rowsAffected === 0) {
5347
+ const current = await client.execute({
5348
+ sql: "SELECT status, assigned_tmux FROM tasks WHERE id = ?",
5349
+ args: [taskId]
5350
+ });
5351
+ const cur = current.rows[0];
5352
+ const status = cur?.status ?? "unknown";
5353
+ const claimedBy = cur?.assigned_tmux ? ` (claimed by ${cur.assigned_tmux})` : "";
5354
+ throw new Error(`${TASK_ALREADY_CLAIMED_PREFIX}: task ${taskId} is ${status}${claimedBy}`);
5094
5355
  }
5095
- if (result2 === "delivered") {
5096
- return { status: "intercom_unprocessed", sessionName };
5356
+ try {
5357
+ await writeCheckpoint({
5358
+ taskId,
5359
+ step: "claimed",
5360
+ contextSummary: `Task claimed by session. Transitioning open \u2192 in_progress.`
5361
+ });
5362
+ } catch {
5097
5363
  }
5098
- return { status: "failed", sessionName, error: "intercom delivery failed" };
5099
- }
5100
- const spawnOpts = { ...opts, instance: effectiveInstance };
5101
- const result = spawnEmployee(employeeName, exeSession, projectDir, spawnOpts);
5102
- if (result.error) {
5103
- return { status: "failed", sessionName, error: result.error };
5364
+ return { row, taskFile, now, taskId };
5104
5365
  }
5105
- return { status: "spawned", sessionName };
5106
- }
5107
- function spawnEmployee(employeeName, exeSession, projectDir, opts) {
5108
- const transport = getTransport();
5109
- const sessionName = employeeSessionName(employeeName, exeSession, opts?.instance);
5110
- const instanceLabel = opts?.instance != null && opts.instance > 0 ? `${employeeName}${opts.instance}` : employeeName;
5111
- const logDir = path11.join(os6.homedir(), ".exe-os", "session-logs");
5112
- const logFile = path11.join(logDir, `${instanceLabel}-${Date.now()}.log`);
5113
- if (!existsSync10(logDir)) {
5114
- mkdirSync6(logDir, { recursive: true });
5366
+ if (input.result) {
5367
+ await client.execute({
5368
+ sql: "UPDATE tasks SET status = ?, result = ?, updated_at = ? WHERE id = ?",
5369
+ args: [input.status, input.result, now, taskId]
5370
+ });
5371
+ } else {
5372
+ await client.execute({
5373
+ sql: "UPDATE tasks SET status = ?, updated_at = ? WHERE id = ?",
5374
+ args: [input.status, now, taskId]
5375
+ });
5115
5376
  }
5116
- transport.kill(sessionName);
5117
- let cleanupSuffix = "";
5118
5377
  try {
5119
- const thisFile = fileURLToPath2(import.meta.url);
5120
- const cleanupScript = path11.join(path11.dirname(thisFile), "..", "bin", "exe-session-cleanup.js");
5121
- if (existsSync10(cleanupScript)) {
5122
- cleanupSuffix = `; ${process.execPath} "${cleanupScript}" "${employeeName}" "${exeSession}"`;
5123
- }
5378
+ await writeCheckpoint({
5379
+ taskId,
5380
+ step: `status_transition:${input.status}`,
5381
+ contextSummary: input.result ? `Transitioned to ${input.status}. Result: ${input.result.slice(0, 500)}` : `Transitioned to ${input.status}.`
5382
+ });
5124
5383
  } catch {
5125
5384
  }
5385
+ return { row, taskFile, now, taskId };
5386
+ }
5387
+ async function deleteTaskCore(taskId, _baseDir) {
5388
+ const client = getClient();
5389
+ const row = await resolveTask(client, taskId);
5390
+ const id = String(row.id);
5391
+ const taskFile = String(row.task_file);
5392
+ const assignedTo = String(row.assigned_to);
5393
+ const assignedBy = String(row.assigned_by);
5394
+ await client.execute({ sql: "DELETE FROM tasks WHERE id = ?", args: [id] });
5395
+ const taskSlug = taskFile.split("/").pop()?.replace(".md", "") ?? "";
5396
+ return { taskFile, assignedTo, assignedBy, taskSlug };
5397
+ }
5398
+ async function ensureArchitectureDoc(baseDir, projectName) {
5399
+ const archPath = path12.join(baseDir, "exe", "ARCHITECTURE.md");
5126
5400
  try {
5127
- const claudeJsonPath = path11.join(os6.homedir(), ".claude.json");
5128
- let claudeJson = {};
5129
- try {
5130
- claudeJson = JSON.parse(readFileSync9(claudeJsonPath, "utf8"));
5131
- } catch {
5132
- }
5133
- if (!claudeJson.projects) claudeJson.projects = {};
5134
- const projects = claudeJson.projects;
5135
- const trustDir = opts?.cwd ?? projectDir;
5136
- if (!projects[trustDir]) projects[trustDir] = {};
5137
- projects[trustDir].hasTrustDialogAccepted = true;
5138
- writeFileSync4(claudeJsonPath, JSON.stringify(claudeJson, null, 2) + "\n");
5401
+ if (existsSync11(archPath)) return;
5402
+ const template = [
5403
+ `# ${projectName} \u2014 System Architecture`,
5404
+ "",
5405
+ "> Employees: read this before every task. Update it when you change system structure.",
5406
+ `> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
5407
+ "",
5408
+ "## Overview",
5409
+ "",
5410
+ "<!-- Describe what this system does, its main components, and how they connect. -->",
5411
+ "",
5412
+ "## Key Components",
5413
+ "",
5414
+ "<!-- List the major modules, services, or subsystems. -->",
5415
+ "",
5416
+ "## Data Flow",
5417
+ "",
5418
+ "<!-- How does data move through the system? What writes where? -->",
5419
+ "",
5420
+ "## Invariants",
5421
+ "",
5422
+ "<!-- Rules that must never be violated. What breaks if these are wrong? -->",
5423
+ "",
5424
+ "## Dependencies",
5425
+ "",
5426
+ "<!-- What depends on what? If I change X, what else is affected? -->",
5427
+ ""
5428
+ ].join("\n");
5429
+ await writeFile4(archPath, template, "utf-8");
5139
5430
  } catch {
5140
5431
  }
5432
+ }
5433
+ async function ensureGitignoreExe(baseDir) {
5434
+ const gitignorePath = path12.join(baseDir, ".gitignore");
5141
5435
  try {
5142
- const settingsDir = path11.join(os6.homedir(), ".claude", "projects");
5143
- const normalizedKey = (opts?.cwd ?? projectDir).replace(/\//g, "-").replace(/^-/, "");
5144
- const projSettingsDir = path11.join(settingsDir, normalizedKey);
5145
- const settingsPath = path11.join(projSettingsDir, "settings.json");
5146
- let settings = {};
5147
- try {
5148
- settings = JSON.parse(readFileSync9(settingsPath, "utf8"));
5149
- } catch {
5150
- }
5151
- const perms = settings.permissions ?? {};
5152
- const allow = perms.allow ?? [];
5153
- const toolNames = [
5154
- "recall_my_memory",
5155
- "store_memory",
5156
- "create_task",
5157
- "update_task",
5158
- "list_tasks",
5159
- "get_task",
5160
- "ask_team_memory",
5161
- "store_behavior",
5162
- "get_identity",
5163
- "send_message"
5164
- ];
5165
- const requiredTools = expandDualPrefixTools(toolNames);
5166
- let changed = false;
5167
- for (const tool of requiredTools) {
5168
- if (!allow.includes(tool)) {
5169
- allow.push(tool);
5170
- changed = true;
5171
- }
5172
- }
5173
- if (changed) {
5174
- perms.allow = allow;
5175
- settings.permissions = perms;
5176
- mkdirSync6(projSettingsDir, { recursive: true });
5177
- writeFileSync4(settingsPath, JSON.stringify(settings, null, 2) + "\n");
5436
+ if (existsSync11(gitignorePath)) {
5437
+ const content = readFileSync10(gitignorePath, "utf-8");
5438
+ if (/^\/?exe\/?$/m.test(content)) return;
5439
+ await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
5440
+ } else {
5441
+ await writeFile4(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
5178
5442
  }
5179
5443
  } catch {
5180
5444
  }
5181
- const spawnCwd = opts?.cwd ?? projectDir;
5182
- const useExeAgent = !!(opts?.model && opts?.provider);
5183
- const ccProvider = useExeAgent ? DEFAULT_PROVIDER : detectActiveProvider();
5184
- const useBinSymlink = ccProvider !== DEFAULT_PROVIDER;
5185
- let identityFlag = "";
5186
- let behaviorsFlag = "";
5187
- let legacyFallbackWarned = false;
5188
- if (!useExeAgent && !useBinSymlink) {
5189
- const identityPath = path11.join(
5190
- os6.homedir(),
5191
- ".exe-os",
5192
- "identity",
5193
- `${employeeName}.md`
5194
- );
5195
- _resetCcAgentSupportCache();
5196
- const hasAgentFlag = claudeSupportsAgentFlag();
5197
- if (hasAgentFlag) {
5198
- identityFlag = ` --agent ${employeeName}`;
5199
- } else if (existsSync10(identityPath)) {
5200
- identityFlag = ` --append-system-prompt-file ${identityPath}`;
5201
- legacyFallbackWarned = true;
5202
- }
5203
- const behaviorsFile = exportBehaviorsSync(
5204
- employeeName,
5205
- path11.basename(spawnCwd),
5206
- sessionName
5207
- );
5208
- if (behaviorsFile) {
5209
- behaviorsFlag = ` --append-system-prompt-file ${behaviorsFile}`;
5210
- }
5445
+ }
5446
+ var DELEGATION_KEYWORDS, TASK_ALREADY_CLAIMED_PREFIX;
5447
+ var init_tasks_crud = __esm({
5448
+ "src/lib/tasks-crud.ts"() {
5449
+ "use strict";
5450
+ init_database();
5451
+ DELEGATION_KEYWORDS = /parallel|delegate|wave|tom\d*-exe/i;
5452
+ TASK_ALREADY_CLAIMED_PREFIX = "TASK_ALREADY_CLAIMED";
5211
5453
  }
5212
- if (legacyFallbackWarned) {
5454
+ });
5455
+
5456
+ // src/lib/tasks-review.ts
5457
+ import path13 from "path";
5458
+ import { existsSync as existsSync12, readdirSync as readdirSync3, unlinkSync as unlinkSync3 } from "fs";
5459
+ async function countPendingReviews() {
5460
+ const client = getClient();
5461
+ const result = await client.execute({
5462
+ sql: "SELECT COUNT(*) as cnt FROM tasks WHERE status = 'needs_review'",
5463
+ args: []
5464
+ });
5465
+ return Number(result.rows[0]?.cnt) || 0;
5466
+ }
5467
+ async function countNewPendingReviewsSince(sinceIso) {
5468
+ const client = getClient();
5469
+ const result = await client.execute({
5470
+ sql: `SELECT COUNT(*) as cnt FROM tasks
5471
+ WHERE status = 'needs_review' AND updated_at > ?`,
5472
+ args: [sinceIso]
5473
+ });
5474
+ return Number(result.rows[0]?.cnt) || 0;
5475
+ }
5476
+ async function listPendingReviews(limit) {
5477
+ const client = getClient();
5478
+ const result = await client.execute({
5479
+ sql: `SELECT title, assigned_to, project_name FROM tasks
5480
+ WHERE status = 'needs_review'
5481
+ ORDER BY priority ASC, created_at DESC LIMIT ?`,
5482
+ args: [limit]
5483
+ });
5484
+ return result.rows;
5485
+ }
5486
+ async function cleanupOrphanedReviews() {
5487
+ const client = getClient();
5488
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5489
+ const r1 = await client.execute({
5490
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
5491
+ WHERE status = 'needs_review'
5492
+ AND assigned_by = 'system'
5493
+ AND title LIKE 'Review:%'
5494
+ AND parent_task_id IN (SELECT id FROM tasks WHERE status IN ('done', 'cancelled'))`,
5495
+ args: [now]
5496
+ });
5497
+ const staleThreshold = new Date(Date.now() - 60 * 60 * 1e3).toISOString();
5498
+ const r2 = await client.execute({
5499
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
5500
+ WHERE status = 'needs_review'
5501
+ AND result IS NOT NULL
5502
+ AND updated_at < ?`,
5503
+ args: [now, staleThreshold]
5504
+ });
5505
+ const total = r1.rowsAffected + r2.rowsAffected;
5506
+ if (total > 0) {
5213
5507
  process.stderr.write(
5214
- `[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.
5508
+ `[cleanup] Closed ${total} orphaned review(s): ${r1.rowsAffected} cascade + ${r2.rowsAffected} stale
5215
5509
  `
5216
5510
  );
5217
5511
  }
5218
- let sessionContextFlag = "";
5219
- try {
5220
- const ctxDir = path11.join(os6.homedir(), ".exe-os", "session-cache");
5221
- mkdirSync6(ctxDir, { recursive: true });
5222
- const ctxFile = path11.join(ctxDir, `session-context-${sessionName}.md`);
5223
- const ctxContent = [
5224
- `## Session Context`,
5225
- `You are running in tmux session: ${sessionName}.`,
5226
- `Your parent exe session is ${exeSession}.`,
5227
- `Your employees (if any) use the -${exeSession} suffix (e.g., tom-${exeSession}).`
5228
- ].join("\n");
5229
- writeFileSync4(ctxFile, ctxContent);
5230
- sessionContextFlag = ` --append-system-prompt-file ${ctxFile}`;
5231
- } catch {
5512
+ return total;
5513
+ }
5514
+ function getReviewChecklist(role, agent, taskSlug) {
5515
+ const roleLower = role.toLowerCase();
5516
+ if (roleLower.includes("engineer") || roleLower === "principal engineer") {
5517
+ return {
5518
+ lens: "Code Quality (Engineer)",
5519
+ checklist: [
5520
+ "1. Do all tests pass? Any new tests needed?",
5521
+ "2. Is the code clean \u2014 no dead code, no TODOs left?",
5522
+ "3. Does it follow existing patterns and conventions in the codebase?",
5523
+ "4. Any regressions in the test suite?"
5524
+ ]
5525
+ };
5232
5526
  }
5233
- let envPrefix = `EXE_SESSION=${exeSession} EXE_SESSION_NAME=${sessionName}`;
5234
- if (ccProvider !== DEFAULT_PROVIDER) {
5235
- const cfg = PROVIDER_TABLE[ccProvider];
5236
- if (cfg?.apiKeyEnv) {
5237
- const keyVal = process.env[cfg.apiKeyEnv];
5238
- if (keyVal) {
5239
- envPrefix = `${envPrefix} ${cfg.apiKeyEnv}=${keyVal}`;
5527
+ if (roleLower === "cto" || roleLower.includes("architect")) {
5528
+ return {
5529
+ lens: "Architecture (CTO)",
5530
+ checklist: [
5531
+ "1. Does this fit the existing architecture? Consistent with ARCHITECTURE.md?",
5532
+ "2. Is it backward compatible? Any breaking changes?",
5533
+ "3. Does it introduce technical debt? Is that debt justified?",
5534
+ "4. Security implications? Any new attack surface?",
5535
+ "5. Does it scale? Performance considerations?",
5536
+ "6. Coordination: does this affect other employees' work or other projects?"
5537
+ ]
5538
+ };
5539
+ }
5540
+ if (roleLower === "coo" || roleLower.includes("operations")) {
5541
+ return {
5542
+ lens: "Strategic (COO)",
5543
+ checklist: [
5544
+ "1. Does this serve the project mission?",
5545
+ "2. Is this the right work at the right time?",
5546
+ "3. Does the architectural assessment make sense for the business?",
5547
+ "4. Any cross-project implications?"
5548
+ ]
5549
+ };
5550
+ }
5551
+ return {
5552
+ lens: "General",
5553
+ checklist: [
5554
+ "1. Read the original task's acceptance criteria",
5555
+ `2. Check git log for related commits: \`git log --oneline --author-date-order -10\``,
5556
+ "3. Verify code changes match requirements",
5557
+ "4. Check if tests were added/updated",
5558
+ `5. Look for output files in exe/output/${agent}-${taskSlug}*`
5559
+ ]
5560
+ };
5561
+ }
5562
+ async function cleanupReviewFile(row, taskFile, _baseDir) {
5563
+ if (String(row.assigned_by) !== "system" || !taskFile.includes("review-")) return;
5564
+ try {
5565
+ const client = getClient();
5566
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5567
+ const parentId = row.parent_task_id ? String(row.parent_task_id) : null;
5568
+ if (parentId) {
5569
+ const result = await client.execute({
5570
+ sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ? AND status = 'needs_review'",
5571
+ args: [now, parentId]
5572
+ });
5573
+ if (result.rowsAffected > 0) {
5574
+ process.stderr.write(
5575
+ `[review-cleanup] Cascaded original task to done via parent_task_id: ${parentId}
5576
+ `
5577
+ );
5578
+ }
5579
+ } else {
5580
+ const fileName = taskFile.split("/").pop() ?? "";
5581
+ const reviewPrefix = fileName.replace(".md", "");
5582
+ const parts = reviewPrefix.split("-");
5583
+ if (parts.length >= 3 && parts[0] === "review") {
5584
+ const agent = parts[1];
5585
+ const slug = parts.slice(2).join("-");
5586
+ const originalTaskFile = `exe/${agent}/${slug}.md`;
5587
+ const result = await client.execute({
5588
+ sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE task_file = ? AND status = 'needs_review'",
5589
+ args: [now, originalTaskFile]
5590
+ });
5591
+ if (result.rowsAffected > 0) {
5592
+ process.stderr.write(
5593
+ `[review-cleanup] Cascaded original task to done (legacy path): ${originalTaskFile}
5594
+ `
5595
+ );
5596
+ }
5240
5597
  }
5241
5598
  }
5242
- }
5243
- let spawnCommand;
5244
- if (useExeAgent) {
5245
- spawnCommand = `${envPrefix} exe-agent --employee ${employeeName} --model ${opts.model} --provider ${opts.provider}${cleanupSuffix}`;
5246
- } else if (useBinSymlink) {
5247
- const binName = `${employeeName}-${ccProvider}`;
5599
+ } catch (err) {
5248
5600
  process.stderr.write(
5249
- `[tmux-routing] provider cascade: ${ccProvider} \u2192 spawning ${binName}
5601
+ `[review-cleanup] Failed to cascade original task: ${err instanceof Error ? err.message : String(err)}
5250
5602
  `
5251
5603
  );
5252
- spawnCommand = `${envPrefix} ${binName}${cleanupSuffix}`;
5253
- } else {
5254
- spawnCommand = `${envPrefix} claude --dangerously-skip-permissions${identityFlag}${behaviorsFlag}${sessionContextFlag}${cleanupSuffix}`;
5255
- }
5256
- const spawnResult = transport.spawn(sessionName, {
5257
- cwd: spawnCwd,
5258
- command: spawnCommand
5259
- });
5260
- if (spawnResult.error) {
5261
- releaseSpawnLock2(sessionName);
5262
- return { sessionName, error: `tmux new-session failed: ${spawnResult.error}` };
5263
5604
  }
5264
- transport.pipeLog(sessionName, logFile);
5265
5605
  try {
5266
- const mySession = getMySession();
5267
- const dispatchInfo = path11.join(SESSION_CACHE, `dispatch-info-${sessionName}.json`);
5268
- writeFileSync4(dispatchInfo, JSON.stringify({
5269
- dispatchedBy: mySession,
5270
- rootExe: exeSession,
5271
- provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
5272
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
5273
- }));
5274
- } catch {
5275
- }
5276
- let booted = false;
5277
- for (let i = 0; i < 30; i++) {
5278
- try {
5279
- execSync4("sleep 0.5");
5280
- } catch {
5281
- }
5282
- try {
5283
- const pane = transport.capturePane(sessionName);
5284
- if (useExeAgent) {
5285
- if (pane.includes("[exe-agent]") || pane.includes("online")) {
5286
- booted = true;
5287
- break;
5288
- }
5289
- } else {
5290
- if (pane.includes("Claude Code") || pane.includes("\u276F")) {
5291
- booted = true;
5292
- break;
5606
+ const cacheDir = path13.join(EXE_AI_DIR, "session-cache");
5607
+ if (existsSync12(cacheDir)) {
5608
+ for (const f of readdirSync3(cacheDir)) {
5609
+ if (f.startsWith("review-notified-")) {
5610
+ unlinkSync3(path13.join(cacheDir, f));
5293
5611
  }
5294
5612
  }
5295
- } catch {
5296
- }
5297
- }
5298
- if (!booted) {
5299
- releaseSpawnLock2(sessionName);
5300
- return { sessionName, error: `${useExeAgent ? "exe-agent" : "claude"} did not boot within 15s` };
5301
- }
5302
- if (!useExeAgent) {
5303
- try {
5304
- transport.sendKeys(sessionName, `/exe-call ${employeeName}`);
5305
- } catch {
5306
5613
  }
5614
+ } catch {
5307
5615
  }
5308
- registerSession({
5309
- windowName: sessionName,
5310
- agentId: employeeName,
5311
- projectDir: spawnCwd,
5312
- parentExe: exeSession,
5313
- pid: 0,
5314
- registeredAt: (/* @__PURE__ */ new Date()).toISOString()
5315
- });
5316
- releaseSpawnLock2(sessionName);
5317
- return { sessionName };
5318
5616
  }
5319
- var SPAWN_LOCK_DIR, SESSION_CACHE, BEHAVIORS_EXPORT_TIMEOUT_MS, INTERCOM_DEBOUNCE_MS, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS, BUSY_PATTERN;
5320
- var init_tmux_routing = __esm({
5321
- "src/lib/tmux-routing.ts"() {
5617
+ var init_tasks_review = __esm({
5618
+ "src/lib/tasks-review.ts"() {
5322
5619
  "use strict";
5323
- init_session_registry();
5620
+ init_database();
5621
+ init_config();
5622
+ init_employees();
5623
+ init_notifications();
5624
+ init_tasks_crud();
5625
+ init_tmux_routing();
5324
5626
  init_session_key();
5325
- init_transport();
5326
- init_cc_agent_support();
5327
- init_mcp_prefix();
5328
- init_provider_table();
5329
- init_intercom_queue();
5330
- init_plan_limits();
5331
- SPAWN_LOCK_DIR = path11.join(os6.homedir(), ".exe-os", "spawn-locks");
5332
- SESSION_CACHE = path11.join(os6.homedir(), ".exe-os", "session-cache");
5333
- BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
5334
- INTERCOM_DEBOUNCE_MS = 3e4;
5335
- INTERCOM_LOG2 = path11.join(os6.homedir(), ".exe-os", "intercom.log");
5336
- DEBOUNCE_FILE = path11.join(SESSION_CACHE, "intercom-debounce.json");
5337
- DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
5338
- BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
5627
+ init_state_bus();
5339
5628
  }
5340
5629
  });
5341
5630
 
5342
- // src/lib/messaging.ts
5343
- var messaging_exports = {};
5344
- __export(messaging_exports, {
5345
- deliverLocalMessage: () => deliverLocalMessage,
5346
- getFailedMessages: () => getFailedMessages,
5347
- getMessageStatus: () => getMessageStatus,
5348
- getPendingMessages: () => getPendingMessages,
5349
- getReadMessages: () => getReadMessages,
5350
- getUnacknowledgedMessages: () => getUnacknowledgedMessages,
5351
- markAcknowledged: () => markAcknowledged,
5352
- markFailed: () => markFailed,
5353
- markProcessed: () => markProcessed,
5354
- markRead: () => markRead,
5355
- retryPendingMessages: () => retryPendingMessages,
5356
- sendMessage: () => sendMessage,
5357
- setWsClientSend: () => setWsClientSend
5358
- });
5359
- import crypto3 from "crypto";
5360
- function generateUlid() {
5361
- const timestamp = Date.now().toString(36).padStart(10, "0");
5362
- const random = crypto3.randomBytes(10).toString("hex").slice(0, 16);
5363
- return (timestamp + random).toUpperCase();
5364
- }
5365
- function rowToMessage(row) {
5366
- return {
5367
- id: row.id,
5368
- fromAgent: row.from_agent,
5369
- fromDevice: row.from_device,
5370
- targetAgent: row.target_agent,
5371
- targetProject: row.target_project ?? null,
5372
- targetDevice: row.target_device,
5373
- content: row.content,
5374
- priority: row.priority ?? "normal",
5375
- status: row.status ?? "pending",
5376
- serverSeq: row.server_seq != null ? Number(row.server_seq) : null,
5377
- retryCount: Number(row.retry_count ?? 0),
5378
- createdAt: row.created_at,
5379
- deliveredAt: row.delivered_at ?? null,
5380
- processedAt: row.processed_at ?? null,
5381
- failedAt: row.failed_at ?? null,
5382
- failureReason: row.failure_reason ?? null
5383
- };
5384
- }
5385
- async function sendMessage(input) {
5631
+ // src/lib/tasks-chain.ts
5632
+ import path14 from "path";
5633
+ import { readFile as readFile4, writeFile as writeFile5 } from "fs/promises";
5634
+ async function cascadeUnblock(taskId, baseDir, now) {
5386
5635
  const client = getClient();
5387
- const id = generateUlid();
5388
- const now = (/* @__PURE__ */ new Date()).toISOString();
5389
- const targetDevice = input.targetDevice ?? "local";
5390
- await client.execute({
5391
- sql: `INSERT INTO messages (id, from_agent, from_device, target_agent, target_project, target_device, content, priority, status, created_at)
5392
- VALUES (?, ?, 'local', ?, ?, ?, ?, ?, 'pending', ?)`,
5393
- args: [
5394
- id,
5395
- input.fromAgent,
5396
- input.targetAgent,
5397
- input.targetProject ?? null,
5398
- targetDevice,
5399
- input.content,
5400
- input.priority ?? "normal",
5401
- now
5402
- ]
5636
+ const unblocked = await client.execute({
5637
+ sql: `UPDATE tasks SET status = 'open', blocked_by = NULL, updated_at = ?
5638
+ WHERE blocked_by = ? AND status = 'blocked'`,
5639
+ args: [now, taskId]
5403
5640
  });
5404
- try {
5405
- if (targetDevice !== "local") {
5406
- await deliverCrossMachineMessage(id, targetDevice);
5407
- } else {
5408
- await deliverLocalMessage(id);
5641
+ if (baseDir && unblocked.rowsAffected > 0) {
5642
+ const unblockedRows = await client.execute({
5643
+ sql: `SELECT task_file FROM tasks WHERE blocked_by IS NULL AND updated_at = ?`,
5644
+ args: [now]
5645
+ });
5646
+ for (const ur of unblockedRows.rows) {
5647
+ try {
5648
+ const ubFile = path14.join(baseDir, String(ur.task_file));
5649
+ let ubContent = await readFile4(ubFile, "utf-8");
5650
+ ubContent = ubContent.replace(/\*\*Status:\*\* blocked/, "**Status:** open");
5651
+ ubContent = ubContent.replace(/\n\*\*Blocked by:\*\*.*\n/, "\n");
5652
+ await writeFile5(ubFile, ubContent, "utf-8");
5653
+ } catch {
5654
+ }
5409
5655
  }
5410
- } catch {
5411
5656
  }
5412
- const result = await client.execute({
5413
- sql: "SELECT * FROM messages WHERE id = ?",
5414
- args: [id]
5415
- });
5416
- return rowToMessage(result.rows[0]);
5417
- }
5418
- function setWsClientSend(fn) {
5419
- _wsClientSend = fn;
5420
5657
  }
5421
- async function deliverCrossMachineMessage(messageId, targetDevice) {
5658
+ async function findNextTask(assignedTo) {
5422
5659
  const client = getClient();
5423
- const result = await client.execute({
5424
- sql: "SELECT * FROM messages WHERE id = ?",
5425
- args: [messageId]
5660
+ const nextResult = await client.execute({
5661
+ sql: `SELECT title, task_file, priority FROM tasks
5662
+ WHERE assigned_to = ? AND status = 'open'
5663
+ ORDER BY priority ASC, created_at ASC
5664
+ LIMIT 1`,
5665
+ args: [assignedTo]
5426
5666
  });
5427
- if (result.rows.length === 0) return false;
5428
- const msg = rowToMessage(result.rows[0]);
5429
- if (msg.status !== "pending") return false;
5430
- if (!_wsClientSend) {
5431
- return false;
5667
+ if (nextResult.rows.length === 1) {
5668
+ const nr = nextResult.rows[0];
5669
+ return {
5670
+ title: String(nr.title),
5671
+ priority: String(nr.priority),
5672
+ taskFile: String(nr.task_file)
5673
+ };
5432
5674
  }
5433
- const payload = JSON.stringify({
5434
- id: msg.id,
5435
- fromAgent: msg.fromAgent,
5436
- targetAgent: msg.targetAgent,
5437
- targetProject: msg.targetProject,
5438
- content: msg.content,
5439
- priority: msg.priority,
5440
- createdAt: msg.createdAt
5675
+ return void 0;
5676
+ }
5677
+ async function checkSubtaskCompletion(parentTaskId, projectName) {
5678
+ const client = getClient();
5679
+ const remaining = await client.execute({
5680
+ sql: `SELECT COUNT(*) as cnt FROM tasks
5681
+ WHERE parent_task_id = ? AND status NOT IN ('done', 'cancelled')`,
5682
+ args: [parentTaskId]
5441
5683
  });
5442
- const sent = _wsClientSend(targetDevice, payload);
5443
- if (sent) {
5444
- await client.execute({
5445
- sql: "UPDATE messages SET status = 'synced' WHERE id = ?",
5446
- args: [messageId]
5684
+ const cnt = Number(remaining.rows[0]?.cnt ?? 1);
5685
+ if (cnt === 0) {
5686
+ const parentRow = await client.execute({
5687
+ sql: `SELECT assigned_to, title, task_file, project_name FROM tasks WHERE id = ?`,
5688
+ args: [parentTaskId]
5447
5689
  });
5448
- return true;
5690
+ if (parentRow.rows.length === 1) {
5691
+ const pr = parentRow.rows[0];
5692
+ const parentProject = pr.project_name == null ? projectName : String(pr.project_name);
5693
+ await writeNotification({
5694
+ agentId: String(pr.assigned_to),
5695
+ agentRole: "system",
5696
+ event: "subtasks_complete",
5697
+ project: parentProject,
5698
+ summary: `All subtasks complete for "${String(pr.title)}" \u2014 ready for rollup review`,
5699
+ taskFile: String(pr.task_file)
5700
+ });
5701
+ }
5449
5702
  }
5450
- return false;
5451
5703
  }
5452
- async function deliverLocalMessage(messageId) {
5453
- const client = getClient();
5454
- const result = await client.execute({
5455
- sql: "SELECT * FROM messages WHERE id = ?",
5456
- args: [messageId]
5457
- });
5458
- if (result.rows.length === 0) return false;
5459
- const msg = rowToMessage(result.rows[0]);
5460
- if (msg.status !== "pending") return false;
5461
- const targetAgent = msg.targetAgent;
5462
- const now = (/* @__PURE__ */ new Date()).toISOString();
5704
+ var init_tasks_chain = __esm({
5705
+ "src/lib/tasks-chain.ts"() {
5706
+ "use strict";
5707
+ init_database();
5708
+ init_notifications();
5709
+ }
5710
+ });
5711
+
5712
+ // src/lib/project-name.ts
5713
+ import { execSync as execSync5 } from "child_process";
5714
+ import path15 from "path";
5715
+ function getProjectName(cwd) {
5716
+ const dir = cwd ?? process.cwd();
5717
+ if (_cached2 && _cachedCwd === dir) return _cached2;
5463
5718
  try {
5464
- const exeSession = resolveExeSession();
5465
- if (!exeSession) {
5466
- throw new Error("No exe session found");
5467
- }
5468
- const ensureResult = ensureEmployee(targetAgent, exeSession, process.cwd());
5469
- if (ensureResult.status === "failed") {
5470
- throw new Error(ensureResult.error ?? "ensureEmployee failed");
5719
+ let repoRoot;
5720
+ try {
5721
+ const gitCommonDir = execSync5("git rev-parse --path-format=absolute --git-common-dir", {
5722
+ cwd: dir,
5723
+ encoding: "utf8",
5724
+ timeout: 2e3,
5725
+ stdio: ["pipe", "pipe", "pipe"]
5726
+ }).trim();
5727
+ repoRoot = path15.dirname(gitCommonDir);
5728
+ } catch {
5729
+ repoRoot = execSync5("git rev-parse --show-toplevel", {
5730
+ cwd: dir,
5731
+ encoding: "utf8",
5732
+ timeout: 2e3,
5733
+ stdio: ["pipe", "pipe", "pipe"]
5734
+ }).trim();
5471
5735
  }
5472
- await client.execute({
5473
- sql: "UPDATE messages SET status = 'delivered', delivered_at = ? WHERE id = ?",
5474
- args: [now, messageId]
5475
- });
5476
- return true;
5736
+ _cached2 = path15.basename(repoRoot);
5737
+ _cachedCwd = dir;
5738
+ return _cached2;
5477
5739
  } catch {
5478
- const newRetryCount = msg.retryCount + 1;
5479
- if (newRetryCount >= MAX_RETRIES2) {
5480
- await markFailed(messageId, "session unavailable after 10 retries");
5481
- } else {
5482
- await client.execute({
5483
- sql: "UPDATE messages SET retry_count = ? WHERE id = ?",
5484
- args: [newRetryCount, messageId]
5485
- });
5486
- }
5487
- return false;
5740
+ _cached2 = path15.basename(dir);
5741
+ _cachedCwd = dir;
5742
+ return _cached2;
5488
5743
  }
5489
5744
  }
5490
- async function getPendingMessages(targetAgent) {
5491
- const client = getClient();
5492
- const result = await client.execute({
5493
- sql: `SELECT * FROM messages
5494
- WHERE target_agent = ? AND status IN ('pending', 'delivered')
5495
- ORDER BY id`,
5496
- args: [targetAgent]
5497
- });
5498
- return result.rows.map((row) => rowToMessage(row));
5745
+ var _cached2, _cachedCwd;
5746
+ var init_project_name = __esm({
5747
+ "src/lib/project-name.ts"() {
5748
+ "use strict";
5749
+ _cached2 = null;
5750
+ _cachedCwd = null;
5751
+ }
5752
+ });
5753
+
5754
+ // src/lib/session-scope.ts
5755
+ var session_scope_exports = {};
5756
+ __export(session_scope_exports, {
5757
+ assertSessionScope: () => assertSessionScope,
5758
+ findSessionForProject: () => findSessionForProject,
5759
+ getSessionProject: () => getSessionProject
5760
+ });
5761
+ function getSessionProject(sessionName) {
5762
+ const sessions = listSessions();
5763
+ const entry = sessions.find((s) => s.windowName === sessionName);
5764
+ if (!entry) return null;
5765
+ const parts = entry.projectDir.split("/").filter(Boolean);
5766
+ return parts[parts.length - 1] ?? null;
5499
5767
  }
5500
- async function markRead(messageId) {
5501
- const client = getClient();
5502
- await client.execute({
5503
- sql: "UPDATE messages SET status = 'read' WHERE id = ? AND status IN ('pending', 'delivered')",
5504
- args: [messageId]
5505
- });
5506
- }
5507
- async function markAcknowledged(messageId) {
5508
- const client = getClient();
5509
- await client.execute({
5510
- sql: "UPDATE messages SET status = 'acknowledged', processed_at = ? WHERE id = ? AND status = 'read'",
5511
- args: [(/* @__PURE__ */ new Date()).toISOString(), messageId]
5512
- });
5513
- }
5514
- async function markProcessed(messageId) {
5515
- const client = getClient();
5516
- await client.execute({
5517
- sql: "UPDATE messages SET status = 'processed', processed_at = ? WHERE id = ?",
5518
- args: [(/* @__PURE__ */ new Date()).toISOString(), messageId]
5519
- });
5520
- }
5521
- async function getMessageStatus(messageId) {
5522
- const client = getClient();
5523
- const result = await client.execute({
5524
- sql: "SELECT status FROM messages WHERE id = ?",
5525
- args: [messageId]
5526
- });
5527
- return result.rows[0]?.status ?? null;
5528
- }
5529
- async function getUnacknowledgedMessages(targetAgent) {
5530
- const client = getClient();
5531
- const result = await client.execute({
5532
- sql: `SELECT * FROM messages
5533
- WHERE target_agent = ? AND status IN ('pending', 'delivered', 'read')
5534
- ORDER BY id`,
5535
- args: [targetAgent]
5536
- });
5537
- return result.rows.map((row) => rowToMessage(row));
5538
- }
5539
- async function getReadMessages(targetAgent) {
5540
- const client = getClient();
5541
- const result = await client.execute({
5542
- sql: "SELECT * FROM messages WHERE target_agent = ? AND status = 'read' ORDER BY id",
5543
- args: [targetAgent]
5544
- });
5545
- return result.rows.map((row) => rowToMessage(row));
5546
- }
5547
- async function markFailed(messageId, reason) {
5548
- const client = getClient();
5549
- await client.execute({
5550
- sql: "UPDATE messages SET status = 'failed', failed_at = ?, failure_reason = ? WHERE id = ?",
5551
- args: [(/* @__PURE__ */ new Date()).toISOString(), reason, messageId]
5552
- });
5553
- }
5554
- async function getFailedMessages() {
5555
- const client = getClient();
5556
- const result = await client.execute({
5557
- sql: "SELECT * FROM messages WHERE status = 'failed' ORDER BY created_at DESC",
5558
- args: []
5559
- });
5560
- return result.rows.map((row) => rowToMessage(row));
5768
+ function findSessionForProject(projectName) {
5769
+ const sessions = listSessions();
5770
+ for (const s of sessions) {
5771
+ const proj = s.projectDir.split("/").filter(Boolean).pop();
5772
+ if (proj === projectName && s.agentId === "exe") return s;
5773
+ }
5774
+ return null;
5561
5775
  }
5562
- async function retryPendingMessages() {
5563
- const client = getClient();
5564
- const result = await client.execute({
5565
- sql: `SELECT * FROM messages
5566
- WHERE status = 'pending' AND retry_count < ?
5567
- ORDER BY id`,
5568
- args: [MAX_RETRIES2]
5569
- });
5570
- let delivered = 0;
5571
- for (const row of result.rows) {
5572
- const msg = rowToMessage(row);
5573
- try {
5574
- const success = await deliverLocalMessage(msg.id);
5575
- if (success) delivered++;
5576
- } catch {
5776
+ function assertSessionScope(actionType, targetProject) {
5777
+ try {
5778
+ const currentProject = getProjectName();
5779
+ const exeSession = resolveExeSession();
5780
+ if (!exeSession) {
5781
+ return { allowed: true, reason: "no_session" };
5782
+ }
5783
+ if (currentProject === targetProject) {
5784
+ return {
5785
+ allowed: true,
5786
+ reason: "same_session",
5787
+ currentProject,
5788
+ targetProject
5789
+ };
5577
5790
  }
5791
+ process.stderr.write(
5792
+ `[session-scope] BLOCKED cross-project ${actionType}: session project="${currentProject}" \u2260 target project="${targetProject}"
5793
+ `
5794
+ );
5795
+ return {
5796
+ allowed: false,
5797
+ reason: "cross_session_denied",
5798
+ currentProject,
5799
+ targetProject,
5800
+ targetSession: findSessionForProject(targetProject)?.windowName
5801
+ };
5802
+ } catch {
5803
+ return { allowed: true, reason: "no_session" };
5578
5804
  }
5579
- return delivered;
5580
5805
  }
5581
- var MAX_RETRIES2, _wsClientSend;
5582
- var init_messaging = __esm({
5583
- "src/lib/messaging.ts"() {
5806
+ var init_session_scope = __esm({
5807
+ "src/lib/session-scope.ts"() {
5584
5808
  "use strict";
5585
- init_database();
5809
+ init_session_registry();
5810
+ init_project_name();
5586
5811
  init_tmux_routing();
5587
- MAX_RETRIES2 = 10;
5588
- _wsClientSend = null;
5589
5812
  }
5590
5813
  });
5591
5814
 
5592
- // src/lib/notifications.ts
5593
- import crypto4 from "crypto";
5594
- import path12 from "path";
5595
- import os7 from "os";
5596
- import {
5597
- readFileSync as readFileSync10,
5598
- readdirSync as readdirSync2,
5599
- unlinkSync as unlinkSync3,
5600
- existsSync as existsSync11,
5601
- rmdirSync
5602
- } from "fs";
5603
- async function writeNotification(notification) {
5815
+ // src/lib/tasks-notify.ts
5816
+ async function dispatchTaskToEmployee(input) {
5817
+ if (input.assignedTo === "exe") return { dispatched: "skipped" };
5818
+ let crossProject = false;
5819
+ if (input.projectName) {
5820
+ try {
5821
+ const { assertSessionScope: assertSessionScope2 } = (init_session_scope(), __toCommonJS(session_scope_exports));
5822
+ const check = assertSessionScope2("dispatch_task", input.projectName);
5823
+ if (check.reason === "cross_session_denied") {
5824
+ crossProject = true;
5825
+ return { dispatched: "skipped", crossProject: true };
5826
+ }
5827
+ } catch {
5828
+ }
5829
+ }
5604
5830
  try {
5605
- const client = getClient();
5606
- const id = crypto4.randomUUID();
5607
- const now = (/* @__PURE__ */ new Date()).toISOString();
5608
- await client.execute({
5609
- sql: `INSERT INTO notifications (id, agent_id, agent_role, event, project, summary, task_file, read, created_at)
5610
- VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)`,
5611
- args: [
5612
- id,
5613
- notification.agentId,
5614
- notification.agentRole,
5615
- notification.event,
5616
- notification.project,
5617
- notification.summary,
5618
- notification.taskFile ?? null,
5619
- now
5620
- ]
5621
- });
5622
- } catch (err) {
5623
- process.stderr.write(`[notifications] WRITE FAILED: ${err instanceof Error ? err.message : String(err)}
5624
- `);
5831
+ const transport = getTransport();
5832
+ const exeSession = resolveExeSession();
5833
+ if (!exeSession) return { dispatched: "session_missing" };
5834
+ const sessionName = employeeSessionName(input.assignedTo, exeSession);
5835
+ if (transport.isAlive(sessionName)) {
5836
+ const result = sendIntercom(sessionName);
5837
+ const dispatched = result === "acknowledged" || result === "debounced" || result === "queued" ? "verified" : result === "delivered" ? "sent_unverified" : "session_dead";
5838
+ return { dispatched, session: sessionName, crossProject };
5839
+ } else {
5840
+ const projectDir = input.projectDir ?? process.cwd();
5841
+ const result = ensureEmployee(input.assignedTo, exeSession, projectDir, {
5842
+ autoInstance: isMultiInstance(input.assignedTo)
5843
+ });
5844
+ if (result.status === "failed") {
5845
+ process.stderr.write(
5846
+ `[dispatch] Failed to spawn ${input.assignedTo}: ${result.error}
5847
+ `
5848
+ );
5849
+ return { dispatched: "session_missing" };
5850
+ }
5851
+ return { dispatched: "spawned", session: result.sessionName, crossProject };
5852
+ }
5853
+ } catch {
5854
+ return { dispatched: "session_missing" };
5625
5855
  }
5626
5856
  }
5627
- async function markAsReadByTaskFile(taskFile) {
5857
+ function notifyTaskDone() {
5628
5858
  try {
5629
- const client = getClient();
5630
- await client.execute({
5631
- sql: "UPDATE notifications SET read = 1 WHERE task_file = ? AND read = 0",
5632
- args: [taskFile]
5633
- });
5859
+ const key = getSessionKey();
5860
+ if (key && !process.env.VITEST) notifyParentExe(key);
5634
5861
  } catch {
5635
5862
  }
5636
5863
  }
5637
- var init_notifications = __esm({
5638
- "src/lib/notifications.ts"() {
5864
+ async function markTaskNotificationsRead(taskFile) {
5865
+ try {
5866
+ await markAsReadByTaskFile(taskFile);
5867
+ } catch {
5868
+ }
5869
+ }
5870
+ var init_tasks_notify = __esm({
5871
+ "src/lib/tasks-notify.ts"() {
5639
5872
  "use strict";
5640
- init_database();
5873
+ init_tmux_routing();
5874
+ init_session_key();
5875
+ init_notifications();
5876
+ init_transport();
5877
+ init_employees();
5641
5878
  }
5642
5879
  });
5643
5880
 
5644
- // src/lib/tasks-crud.ts
5645
- import crypto5 from "crypto";
5646
- import path13 from "path";
5647
- import { execSync as execSync5 } from "child_process";
5648
- import { mkdir as mkdir4, writeFile as writeFile4, appendFile } from "fs/promises";
5649
- import { existsSync as existsSync12, readFileSync as readFileSync11 } from "fs";
5650
- async function writeCheckpoint(input) {
5881
+ // src/lib/behaviors.ts
5882
+ import crypto6 from "crypto";
5883
+ async function storeBehavior(opts) {
5651
5884
  const client = getClient();
5652
- const row = await resolveTask(client, input.taskId);
5653
- const taskId = String(row.id);
5885
+ const id = crypto6.randomUUID();
5654
5886
  const now = (/* @__PURE__ */ new Date()).toISOString();
5655
- const blockedByIds = [];
5656
- if (row.blocked_by) {
5657
- blockedByIds.push(String(row.blocked_by));
5658
- }
5659
- const checkpoint = {
5660
- step: input.step,
5661
- context_summary: input.contextSummary,
5662
- files_touched: input.filesTouched ?? [],
5663
- blocked_by_ids: blockedByIds,
5664
- last_checkpoint_at: now
5665
- };
5666
- const result = await client.execute({
5667
- sql: `UPDATE tasks SET checkpoint = ?, checkpoint_count = checkpoint_count + 1, updated_at = ? WHERE id = ?`,
5668
- args: [JSON.stringify(checkpoint), now, taskId]
5669
- });
5670
- if (result.rowsAffected === 0) {
5671
- throw new Error(`Checkpoint write failed: task ${taskId} not found`);
5672
- }
5673
- const countResult = await client.execute({
5674
- sql: "SELECT checkpoint_count FROM tasks WHERE id = ?",
5675
- args: [taskId]
5887
+ await client.execute({
5888
+ sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, priority, content, active, created_at, updated_at)
5889
+ VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)`,
5890
+ args: [id, opts.agentId, opts.projectName ?? null, opts.domain ?? null, opts.priority ?? "p1", opts.content, now, now]
5676
5891
  });
5677
- const checkpointCount = Number(countResult.rows[0]?.checkpoint_count ?? 1);
5678
- return { checkpointCount };
5679
- }
5680
- function extractParentFromContext(contextBody) {
5681
- if (!contextBody) return null;
5682
- const match = contextBody.match(
5683
- /Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
5684
- );
5685
- return match ? match[1].toLowerCase() : null;
5892
+ return id;
5686
5893
  }
5687
- function slugify(title) {
5688
- return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
5689
- }
5690
- async function resolveTask(client, identifier) {
5691
- let result = await client.execute({
5692
- sql: "SELECT * FROM tasks WHERE id = ?",
5693
- args: [identifier]
5694
- });
5695
- if (result.rows.length === 1) return result.rows[0];
5696
- result = await client.execute({
5697
- sql: "SELECT * FROM tasks WHERE task_file LIKE ?",
5698
- args: [`%${identifier}%`]
5699
- });
5700
- if (result.rows.length === 1) return result.rows[0];
5701
- if (result.rows.length > 1) {
5702
- const exact = result.rows.filter(
5703
- (r) => String(r.task_file).endsWith(`/${identifier}.md`)
5704
- );
5705
- if (exact.length === 1) return exact[0];
5706
- const candidates = exact.length > 1 ? exact : result.rows;
5707
- const active = candidates.filter(
5708
- (r) => !["done", "cancelled"].includes(String(r.status))
5709
- );
5710
- if (active.length === 1) return active[0];
5711
- const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
5712
- throw new Error(
5713
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
5714
- );
5715
- }
5716
- result = await client.execute({
5717
- sql: "SELECT * FROM tasks WHERE title LIKE ?",
5718
- args: [`%${identifier}%`]
5719
- });
5720
- if (result.rows.length === 1) return result.rows[0];
5721
- if (result.rows.length > 1) {
5722
- const active = result.rows.filter(
5723
- (r) => !["done", "cancelled"].includes(String(r.status))
5724
- );
5725
- if (active.length === 1) return active[0];
5726
- const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
5727
- throw new Error(
5728
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
5729
- );
5894
+ var init_behaviors = __esm({
5895
+ "src/lib/behaviors.ts"() {
5896
+ "use strict";
5897
+ init_database();
5730
5898
  }
5731
- throw new Error(`Task not found: ${identifier}`);
5732
- }
5733
- async function createTaskCore(input) {
5899
+ });
5900
+
5901
+ // src/lib/skill-learning.ts
5902
+ var skill_learning_exports = {};
5903
+ __export(skill_learning_exports, {
5904
+ captureAndLearn: () => captureAndLearn,
5905
+ captureTrajectory: () => captureTrajectory,
5906
+ editDistance: () => editDistance,
5907
+ extractSkill: () => extractSkill,
5908
+ extractTrajectory: () => extractTrajectory,
5909
+ findSimilarTrajectories: () => findSimilarTrajectories,
5910
+ hashSignature: () => hashSignature,
5911
+ storeTrajectory: () => storeTrajectory,
5912
+ sweepTrajectories: () => sweepTrajectories
5913
+ });
5914
+ import crypto7 from "crypto";
5915
+ async function extractTrajectory(taskId, agentId) {
5734
5916
  const client = getClient();
5735
- const id = crypto5.randomUUID();
5736
- const now = (/* @__PURE__ */ new Date()).toISOString();
5737
- const slug = slugify(input.title);
5738
- const taskFile = input.taskFile ?? `exe/${input.assignedTo}/${slug}.md`;
5739
- let blockedById = null;
5740
- const initialStatus = input.blockedBy ? "blocked" : "open";
5741
- if (input.blockedBy) {
5742
- const blocker = await resolveTask(client, input.blockedBy);
5743
- blockedById = String(blocker.id);
5744
- }
5745
- let parentTaskId = null;
5746
- let parentRef = input.parentTaskId;
5747
- if (!parentRef) {
5748
- const extracted = extractParentFromContext(input.context);
5749
- if (extracted) {
5750
- parentRef = extracted;
5751
- process.stderr.write(
5752
- "[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
5753
- );
5754
- }
5755
- }
5756
- if (parentRef) {
5757
- try {
5758
- const parent = await resolveTask(client, parentRef);
5759
- parentTaskId = String(parent.id);
5760
- } catch (err) {
5761
- if (!input.parentTaskId) {
5762
- throw new Error(
5763
- `create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
5764
- );
5765
- }
5766
- throw err;
5917
+ const result = await client.execute({
5918
+ sql: `SELECT tool_name, raw_text
5919
+ FROM memories
5920
+ WHERE task_id = ? AND agent_id = ?
5921
+ ORDER BY timestamp ASC`,
5922
+ args: [taskId, agentId]
5923
+ });
5924
+ if (result.rows.length === 0) return [];
5925
+ const rawTools = result.rows.map((r) => {
5926
+ const toolName = String(r.tool_name);
5927
+ if (toolName === "Bash") {
5928
+ const text = String(r.raw_text);
5929
+ const cmdMatch = text.match(/(?:command|Command).*?[:\s]+"?(\w+)/);
5930
+ return cmdMatch ? `Bash:${cmdMatch[1]}` : "Bash";
5767
5931
  }
5768
- }
5769
- let warning;
5770
- const dupCheck = await client.execute({
5771
- sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
5772
- args: [input.title, input.assignedTo]
5932
+ return toolName;
5773
5933
  });
5774
- if (dupCheck.rows.length > 0) {
5775
- warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
5776
- }
5777
- if (input.baseDir) {
5778
- try {
5779
- await mkdir4(path13.join(input.baseDir, "exe", "output"), { recursive: true });
5780
- await mkdir4(path13.join(input.baseDir, "exe", "research"), { recursive: true });
5781
- await ensureArchitectureDoc(input.baseDir, input.projectName);
5782
- await ensureGitignoreExe(input.baseDir);
5783
- } catch {
5934
+ const signature = [];
5935
+ for (const tool of rawTools) {
5936
+ if (signature.length === 0 || signature[signature.length - 1] !== tool) {
5937
+ signature.push(tool);
5784
5938
  }
5785
5939
  }
5786
- const complexity = input.complexity ?? "standard";
5940
+ return signature;
5941
+ }
5942
+ function hashSignature(signature) {
5943
+ return crypto7.createHash("sha256").update(signature.join("|")).digest("hex").slice(0, 16);
5944
+ }
5945
+ async function storeTrajectory(opts) {
5946
+ const client = getClient();
5947
+ const id = crypto7.randomUUID();
5948
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5949
+ const signatureHash = hashSignature(opts.signature);
5787
5950
  await client.execute({
5788
- 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)
5789
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
5951
+ sql: `INSERT INTO trajectories (id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at)
5952
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
5790
5953
  args: [
5791
5954
  id,
5792
- input.title,
5793
- input.assignedTo,
5794
- input.assignedBy,
5795
- input.projectName,
5796
- input.priority,
5797
- initialStatus,
5798
- taskFile,
5799
- blockedById,
5800
- parentTaskId,
5801
- input.reviewer ?? null,
5802
- input.context,
5803
- complexity,
5804
- input.budgetTokens ?? null,
5805
- input.budgetFallbackModel ?? null,
5806
- 0,
5807
- null,
5808
- now,
5955
+ opts.taskId,
5956
+ opts.agentId,
5957
+ opts.projectName,
5958
+ opts.taskTitle,
5959
+ JSON.stringify(opts.signature),
5960
+ signatureHash,
5961
+ opts.signature.length,
5809
5962
  now
5810
5963
  ]
5811
5964
  });
5812
- return {
5813
- id,
5814
- title: input.title,
5815
- assignedTo: input.assignedTo,
5816
- assignedBy: input.assignedBy,
5817
- projectName: input.projectName,
5818
- priority: input.priority,
5819
- status: initialStatus,
5820
- taskFile,
5821
- createdAt: now,
5822
- updatedAt: now,
5823
- warning,
5824
- budgetTokens: input.budgetTokens ?? null,
5825
- budgetFallbackModel: input.budgetFallbackModel ?? null,
5826
- tokensUsed: 0,
5827
- tokensWarnedAt: null
5828
- };
5965
+ return id;
5829
5966
  }
5830
- async function listTasks(input) {
5967
+ async function findSimilarTrajectories(signature, threshold = DEFAULT_SKILL_THRESHOLD) {
5831
5968
  const client = getClient();
5832
- const conditions = [];
5833
- const args = [];
5834
- if (input.assignedTo) {
5835
- conditions.push("assigned_to = ?");
5836
- args.push(input.assignedTo);
5837
- }
5838
- if (input.status) {
5839
- conditions.push("status = ?");
5840
- args.push(input.status);
5841
- } else {
5842
- conditions.push("status IN ('open', 'in_progress', 'blocked')");
5843
- }
5844
- if (input.projectName) {
5845
- conditions.push("project_name = ?");
5846
- args.push(input.projectName);
5847
- }
5848
- if (input.priority) {
5849
- conditions.push("priority = ?");
5850
- args.push(input.priority);
5851
- }
5852
- const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
5969
+ const hash = hashSignature(signature);
5853
5970
  const result = await client.execute({
5854
- 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`,
5855
- args
5971
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
5972
+ FROM trajectories
5973
+ WHERE signature_hash = ?
5974
+ ORDER BY created_at DESC
5975
+ LIMIT 20`,
5976
+ args: [hash]
5856
5977
  });
5857
- return result.rows.map((r) => ({
5978
+ const mapRow = (r) => ({
5858
5979
  id: String(r.id),
5859
- title: String(r.title),
5860
- assignedTo: String(r.assigned_to),
5861
- assignedBy: String(r.assigned_by),
5980
+ taskId: String(r.task_id),
5981
+ agentId: String(r.agent_id),
5862
5982
  projectName: String(r.project_name),
5863
- priority: String(r.priority),
5864
- status: String(r.status),
5865
- taskFile: String(r.task_file),
5866
- createdAt: String(r.created_at),
5867
- updatedAt: String(r.updated_at),
5868
- checkpointCount: Number(r.checkpoint_count ?? 0),
5869
- budgetTokens: r.budget_tokens !== null ? Number(r.budget_tokens) : null,
5870
- budgetFallbackModel: r.budget_fallback_model !== null ? String(r.budget_fallback_model) : null,
5871
- tokensUsed: Number(r.tokens_used ?? 0),
5872
- tokensWarnedAt: r.tokens_warned_at !== null ? Number(r.tokens_warned_at) : null
5873
- }));
5874
- }
5875
- function checkStaleCompletion(taskContext, taskCreatedAt) {
5876
- if (!taskContext) return null;
5877
- if (!DELEGATION_KEYWORDS.test(taskContext)) return null;
5878
- try {
5879
- const since = new Date(taskCreatedAt).toISOString();
5880
- const branch = execSync5(
5881
- "git rev-parse --abbrev-ref HEAD 2>/dev/null",
5882
- { encoding: "utf8", timeout: 3e3 }
5883
- ).trim();
5884
- const branchArg = branch && branch !== "HEAD" ? branch : "";
5885
- const commitCount = execSync5(
5886
- `git log --oneline --since="${since}" ${branchArg} 2>/dev/null | wc -l`,
5887
- { encoding: "utf8", timeout: 5e3 }
5888
- ).trim();
5889
- const count = parseInt(commitCount, 10);
5890
- if (count === 0) {
5891
- return "WARNING: task closed with no new commits since creation. Verify work was actually produced.";
5892
- }
5893
- return null;
5894
- } catch {
5895
- return null;
5896
- }
5897
- }
5898
- async function updateTaskStatus(input) {
5899
- const client = getClient();
5900
- const now = (/* @__PURE__ */ new Date()).toISOString();
5901
- const row = await resolveTask(client, input.taskId);
5902
- const taskId = String(row.id);
5903
- const taskFile = String(row.task_file);
5904
- if (input.status === "done" && String(row.assigned_by) === "system" && taskFile.includes("review-")) {
5905
- process.stderr.write(
5906
- `[updateTask] Review task "${String(row.title)}" being marked done (assigned to ${String(row.assigned_to)})
5907
- `
5908
- );
5909
- }
5910
- if (input.status === "done") {
5911
- const existingRow = await client.execute({
5912
- sql: "SELECT context, created_at FROM tasks WHERE id = ?",
5913
- args: [taskId]
5914
- });
5915
- if (existingRow.rows.length > 0) {
5916
- const ctx = existingRow.rows[0];
5917
- const warning = checkStaleCompletion(ctx.context, ctx.created_at);
5918
- if (warning) {
5919
- input.result = input.result ? `\u26A0\uFE0F ${warning}
5920
-
5921
- ${input.result}` : `\u26A0\uFE0F ${warning}`;
5922
- process.stderr.write(`[tasks] ${warning} (task: ${taskId})
5923
- `);
5924
- }
5983
+ taskTitle: String(r.task_title),
5984
+ signature: JSON.parse(String(r.signature)),
5985
+ signatureHash: String(r.signature_hash),
5986
+ toolCount: Number(r.tool_count),
5987
+ skillId: r.skill_id ? String(r.skill_id) : null,
5988
+ createdAt: String(r.created_at)
5989
+ });
5990
+ const matches = result.rows.map(mapRow);
5991
+ if (matches.length >= threshold) return matches;
5992
+ const nearResult = await client.execute({
5993
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
5994
+ FROM trajectories
5995
+ WHERE tool_count BETWEEN ? AND ?
5996
+ AND signature_hash != ?
5997
+ ORDER BY created_at DESC
5998
+ LIMIT 50`,
5999
+ args: [
6000
+ Math.max(1, signature.length - 3),
6001
+ signature.length + 3,
6002
+ hash
6003
+ ]
6004
+ });
6005
+ for (const r of nearResult.rows) {
6006
+ const candidateSig = JSON.parse(String(r.signature));
6007
+ if (editDistance(signature, candidateSig) <= 2) {
6008
+ matches.push(mapRow(r));
5925
6009
  }
5926
6010
  }
5927
- if (input.status === "in_progress") {
5928
- const tmuxSession = process.env.TMUX_PANE ?? process.env.MY_TMUX_SESSION ?? "unknown";
5929
- const claim = await client.execute({
5930
- sql: `UPDATE tasks
5931
- SET status = 'in_progress', assigned_tmux = ?, updated_at = ?
5932
- WHERE id = ? AND status = 'open'`,
5933
- args: [tmuxSession, now, taskId]
5934
- });
5935
- if (claim.rowsAffected === 0) {
5936
- const current = await client.execute({
5937
- sql: "SELECT status, assigned_tmux FROM tasks WHERE id = ?",
5938
- args: [taskId]
5939
- });
5940
- const cur = current.rows[0];
5941
- const status = cur?.status ?? "unknown";
5942
- const claimedBy = cur?.assigned_tmux ? ` (claimed by ${cur.assigned_tmux})` : "";
5943
- throw new Error(`${TASK_ALREADY_CLAIMED_PREFIX}: task ${taskId} is ${status}${claimedBy}`);
5944
- }
5945
- try {
5946
- await writeCheckpoint({
5947
- taskId,
5948
- step: "claimed",
5949
- contextSummary: `Task claimed by session. Transitioning open \u2192 in_progress.`
5950
- });
5951
- } catch {
5952
- }
5953
- return { row, taskFile, now, taskId };
6011
+ return matches;
6012
+ }
6013
+ async function captureTrajectory(opts) {
6014
+ const signature = await extractTrajectory(opts.taskId, opts.agentId);
6015
+ if (signature.length < 3) {
6016
+ return { trajectoryId: "", similarCount: 0, similar: [] };
5954
6017
  }
5955
- if (input.result) {
5956
- await client.execute({
5957
- sql: "UPDATE tasks SET status = ?, result = ?, updated_at = ? WHERE id = ?",
5958
- args: [input.status, input.result, now, taskId]
5959
- });
5960
- } else {
5961
- await client.execute({
5962
- sql: "UPDATE tasks SET status = ?, updated_at = ? WHERE id = ?",
5963
- args: [input.status, now, taskId]
6018
+ const trajectoryId = await storeTrajectory({
6019
+ taskId: opts.taskId,
6020
+ agentId: opts.agentId,
6021
+ projectName: opts.projectName,
6022
+ taskTitle: opts.taskTitle,
6023
+ signature
6024
+ });
6025
+ const similar = await findSimilarTrajectories(
6026
+ signature,
6027
+ opts.skillThreshold ?? DEFAULT_SKILL_THRESHOLD
6028
+ );
6029
+ return { trajectoryId, similarCount: similar.length, similar };
6030
+ }
6031
+ function buildExtractionPrompt(trajectories) {
6032
+ const items = trajectories.map((t, i) => {
6033
+ const sig = t.signature.join(" \u2192 ");
6034
+ return `Task ${i + 1}: "${t.taskTitle}" (${t.agentId}, ${t.projectName}) \u2014 ${t.toolCount} tool calls
6035
+ Signature: ${sig}`;
6036
+ }).join("\n\n");
6037
+ return `You are analyzing ${trajectories.length} completed tasks that followed similar procedures:
6038
+
6039
+ ${items}
6040
+
6041
+ Extract the reusable procedure. Format your response EXACTLY like this:
6042
+
6043
+ SKILL: {name \u2014 short, descriptive}
6044
+ TRIGGER: {when to use this \u2014 one sentence}
6045
+ STEPS:
6046
+ 1. ...
6047
+ 2. ...
6048
+ PITFALLS: {common mistakes to avoid}
6049
+
6050
+ Be specific and actionable. Include tool names, file patterns, and concrete commands where applicable.`;
6051
+ }
6052
+ async function extractSkill(trajectories, model) {
6053
+ if (trajectories.length === 0) return null;
6054
+ const config2 = await loadConfig();
6055
+ const skillModel = model ?? config2.skillModel;
6056
+ const Anthropic2 = (await import("@anthropic-ai/sdk")).default;
6057
+ const client = new Anthropic2();
6058
+ const prompt = buildExtractionPrompt(trajectories);
6059
+ const response = await client.messages.create({
6060
+ model: skillModel,
6061
+ max_tokens: 500,
6062
+ messages: [{ role: "user", content: prompt }]
6063
+ });
6064
+ const textBlock = response.content.find((b) => b.type === "text");
6065
+ const skillText = textBlock?.text;
6066
+ if (!skillText) return null;
6067
+ const agentId = trajectories[0].agentId;
6068
+ const projectName = trajectories[0].projectName;
6069
+ const skillId = await storeBehavior({
6070
+ agentId,
6071
+ content: skillText,
6072
+ domain: "skill",
6073
+ projectName
6074
+ });
6075
+ const dbClient = getClient();
6076
+ for (const t of trajectories) {
6077
+ await dbClient.execute({
6078
+ sql: "UPDATE trajectories SET skill_id = ? WHERE id = ?",
6079
+ args: [skillId, t.id]
5964
6080
  });
5965
6081
  }
6082
+ process.stderr.write(
6083
+ `[skill-learning] Skill extracted from ${trajectories.length} trajectories \u2192 behavior ${skillId}
6084
+ `
6085
+ );
6086
+ return skillId;
6087
+ }
6088
+ async function captureAndLearn(opts) {
5966
6089
  try {
5967
- await writeCheckpoint({
5968
- taskId,
5969
- step: `status_transition:${input.status}`,
5970
- contextSummary: input.result ? `Transitioned to ${input.status}. Result: ${input.result.slice(0, 500)}` : `Transitioned to ${input.status}.`
6090
+ const config2 = await loadConfig();
6091
+ if (!config2.skillLearning) return;
6092
+ const { trajectoryId, similarCount, similar } = await captureTrajectory({
6093
+ ...opts,
6094
+ skillThreshold: config2.skillThreshold
5971
6095
  });
5972
- } catch {
6096
+ if (!trajectoryId) return;
6097
+ if (similarCount >= config2.skillThreshold) {
6098
+ const unprocessed = similar.filter((t) => !t.skillId);
6099
+ if (unprocessed.length >= config2.skillThreshold) {
6100
+ extractSkill(unprocessed, config2.skillModel).catch((err) => {
6101
+ process.stderr.write(
6102
+ `[skill-learning] Extraction failed: ${err instanceof Error ? err.message : String(err)}
6103
+ `
6104
+ );
6105
+ });
6106
+ }
6107
+ }
6108
+ } catch (err) {
6109
+ process.stderr.write(
6110
+ `[skill-learning] captureAndLearn failed: ${err instanceof Error ? err.message : String(err)}
6111
+ `
6112
+ );
5973
6113
  }
5974
- return { row, taskFile, now, taskId };
5975
6114
  }
5976
- async function deleteTaskCore(taskId, _baseDir) {
6115
+ async function sweepTrajectories(threshold, model) {
6116
+ const config2 = await loadConfig();
6117
+ if (!config2.skillLearning) return { clustersProcessed: 0, skillsExtracted: 0 };
6118
+ const t = threshold ?? config2.skillThreshold;
5977
6119
  const client = getClient();
5978
- const row = await resolveTask(client, taskId);
5979
- const id = String(row.id);
5980
- const taskFile = String(row.task_file);
5981
- const assignedTo = String(row.assigned_to);
5982
- const assignedBy = String(row.assigned_by);
5983
- await client.execute({ sql: "DELETE FROM tasks WHERE id = ?", args: [id] });
5984
- const taskSlug = taskFile.split("/").pop()?.replace(".md", "") ?? "";
5985
- return { taskFile, assignedTo, assignedBy, taskSlug };
5986
- }
5987
- async function ensureArchitectureDoc(baseDir, projectName) {
5988
- const archPath = path13.join(baseDir, "exe", "ARCHITECTURE.md");
5989
- try {
5990
- if (existsSync12(archPath)) return;
5991
- const template = [
5992
- `# ${projectName} \u2014 System Architecture`,
5993
- "",
5994
- "> Employees: read this before every task. Update it when you change system structure.",
5995
- `> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
5996
- "",
5997
- "## Overview",
5998
- "",
5999
- "<!-- Describe what this system does, its main components, and how they connect. -->",
6000
- "",
6001
- "## Key Components",
6002
- "",
6003
- "<!-- List the major modules, services, or subsystems. -->",
6004
- "",
6005
- "## Data Flow",
6006
- "",
6007
- "<!-- How does data move through the system? What writes where? -->",
6008
- "",
6009
- "## Invariants",
6010
- "",
6011
- "<!-- Rules that must never be violated. What breaks if these are wrong? -->",
6012
- "",
6013
- "## Dependencies",
6014
- "",
6015
- "<!-- What depends on what? If I change X, what else is affected? -->",
6016
- ""
6017
- ].join("\n");
6018
- await writeFile4(archPath, template, "utf-8");
6019
- } catch {
6120
+ const result = await client.execute({
6121
+ sql: `SELECT signature_hash, COUNT(*) as cnt
6122
+ FROM trajectories
6123
+ WHERE skill_id IS NULL
6124
+ GROUP BY signature_hash
6125
+ HAVING cnt >= ?
6126
+ ORDER BY cnt DESC
6127
+ LIMIT 10`,
6128
+ args: [t]
6129
+ });
6130
+ let clustersProcessed = 0;
6131
+ let skillsExtracted = 0;
6132
+ for (const row of result.rows) {
6133
+ const hash = String(row.signature_hash);
6134
+ const trajResult = await client.execute({
6135
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at
6136
+ FROM trajectories
6137
+ WHERE signature_hash = ? AND skill_id IS NULL
6138
+ ORDER BY created_at DESC
6139
+ LIMIT 10`,
6140
+ args: [hash]
6141
+ });
6142
+ const trajectories = trajResult.rows.map((r) => ({
6143
+ id: String(r.id),
6144
+ taskId: String(r.task_id),
6145
+ agentId: String(r.agent_id),
6146
+ projectName: String(r.project_name),
6147
+ taskTitle: String(r.task_title),
6148
+ signature: JSON.parse(String(r.signature)),
6149
+ signatureHash: String(r.signature_hash),
6150
+ toolCount: Number(r.tool_count),
6151
+ skillId: null,
6152
+ createdAt: String(r.created_at)
6153
+ }));
6154
+ if (trajectories.length >= t) {
6155
+ clustersProcessed++;
6156
+ const skillId = await extractSkill(trajectories, model ?? config2.skillModel);
6157
+ if (skillId) skillsExtracted++;
6158
+ }
6020
6159
  }
6160
+ return { clustersProcessed, skillsExtracted };
6021
6161
  }
6022
- async function ensureGitignoreExe(baseDir) {
6023
- const gitignorePath = path13.join(baseDir, ".gitignore");
6024
- try {
6025
- if (existsSync12(gitignorePath)) {
6026
- const content = readFileSync11(gitignorePath, "utf-8");
6027
- if (/^\/?exe\/?$/m.test(content)) return;
6028
- await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
6029
- } else {
6030
- await writeFile4(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
6162
+ function editDistance(a, b) {
6163
+ const m = a.length;
6164
+ const n = b.length;
6165
+ const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
6166
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
6167
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
6168
+ for (let i = 1; i <= m; i++) {
6169
+ for (let j = 1; j <= n; j++) {
6170
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
6171
+ dp[i][j] = Math.min(
6172
+ dp[i - 1][j] + 1,
6173
+ dp[i][j - 1] + 1,
6174
+ dp[i - 1][j - 1] + cost
6175
+ );
6031
6176
  }
6032
- } catch {
6033
6177
  }
6178
+ return dp[m][n];
6034
6179
  }
6035
- var DELEGATION_KEYWORDS, TASK_ALREADY_CLAIMED_PREFIX;
6036
- var init_tasks_crud = __esm({
6037
- "src/lib/tasks-crud.ts"() {
6180
+ var DEFAULT_SKILL_THRESHOLD;
6181
+ var init_skill_learning = __esm({
6182
+ "src/lib/skill-learning.ts"() {
6038
6183
  "use strict";
6039
6184
  init_database();
6040
- DELEGATION_KEYWORDS = /parallel|delegate|wave|tom\d*-exe/i;
6041
- TASK_ALREADY_CLAIMED_PREFIX = "TASK_ALREADY_CLAIMED";
6185
+ init_behaviors();
6186
+ init_config();
6187
+ DEFAULT_SKILL_THRESHOLD = 3;
6042
6188
  }
6043
6189
  });
6044
6190
 
6045
- // src/lib/tasks-review.ts
6046
- import path14 from "path";
6047
- import { existsSync as existsSync13, readdirSync as readdirSync3, unlinkSync as unlinkSync4 } from "fs";
6048
- async function countPendingReviews() {
6049
- const client = getClient();
6050
- const result = await client.execute({
6051
- sql: "SELECT COUNT(*) as cnt FROM tasks WHERE status = 'needs_review'",
6052
- args: []
6053
- });
6054
- return Number(result.rows[0]?.cnt) || 0;
6055
- }
6056
- async function countNewPendingReviewsSince(sinceIso) {
6057
- const client = getClient();
6058
- const result = await client.execute({
6059
- sql: `SELECT COUNT(*) as cnt FROM tasks
6060
- WHERE status = 'needs_review' AND updated_at > ?`,
6061
- args: [sinceIso]
6062
- });
6063
- return Number(result.rows[0]?.cnt) || 0;
6064
- }
6065
- async function listPendingReviews(limit) {
6066
- const client = getClient();
6067
- const result = await client.execute({
6068
- sql: `SELECT title, assigned_to, project_name FROM tasks
6069
- WHERE status = 'needs_review'
6070
- ORDER BY priority ASC, created_at DESC LIMIT ?`,
6071
- args: [limit]
6072
- });
6073
- return result.rows;
6074
- }
6075
- async function cleanupOrphanedReviews() {
6076
- const client = getClient();
6077
- const now = (/* @__PURE__ */ new Date()).toISOString();
6078
- const r1 = await client.execute({
6079
- sql: `UPDATE tasks SET status = 'done', updated_at = ?
6080
- WHERE status = 'needs_review'
6081
- AND assigned_by = 'system'
6082
- AND title LIKE 'Review:%'
6083
- AND parent_task_id IN (SELECT id FROM tasks WHERE status IN ('done', 'cancelled'))`,
6084
- args: [now]
6085
- });
6086
- const staleThreshold = new Date(Date.now() - 60 * 60 * 1e3).toISOString();
6087
- const r2 = await client.execute({
6088
- sql: `UPDATE tasks SET status = 'done', updated_at = ?
6089
- WHERE status = 'needs_review'
6090
- AND result IS NOT NULL
6091
- AND updated_at < ?`,
6092
- args: [now, staleThreshold]
6093
- });
6094
- const total = r1.rowsAffected + r2.rowsAffected;
6095
- if (total > 0) {
6096
- process.stderr.write(
6097
- `[cleanup] Closed ${total} orphaned review(s): ${r1.rowsAffected} cascade + ${r2.rowsAffected} stale
6098
- `
6099
- );
6100
- }
6101
- return total;
6102
- }
6103
- function getReviewChecklist(role, agent, taskSlug) {
6104
- const roleLower = role.toLowerCase();
6105
- if (roleLower.includes("engineer") || roleLower === "principal engineer") {
6106
- return {
6107
- lens: "Code Quality (Engineer)",
6108
- checklist: [
6109
- "1. Do all tests pass? Any new tests needed?",
6110
- "2. Is the code clean \u2014 no dead code, no TODOs left?",
6111
- "3. Does it follow existing patterns and conventions in the codebase?",
6112
- "4. Any regressions in the test suite?"
6113
- ]
6114
- };
6115
- }
6116
- if (roleLower === "cto" || roleLower.includes("architect")) {
6117
- return {
6118
- lens: "Architecture (CTO)",
6119
- checklist: [
6120
- "1. Does this fit the existing architecture? Consistent with ARCHITECTURE.md?",
6121
- "2. Is it backward compatible? Any breaking changes?",
6122
- "3. Does it introduce technical debt? Is that debt justified?",
6123
- "4. Security implications? Any new attack surface?",
6124
- "5. Does it scale? Performance considerations?",
6125
- "6. Coordination: does this affect other employees' work or other projects?"
6126
- ]
6127
- };
6128
- }
6129
- if (roleLower === "coo" || roleLower.includes("operations")) {
6130
- return {
6131
- lens: "Strategic (COO)",
6132
- checklist: [
6133
- "1. Does this serve the project mission?",
6134
- "2. Is this the right work at the right time?",
6135
- "3. Does the architectural assessment make sense for the business?",
6136
- "4. Any cross-project implications?"
6137
- ]
6138
- };
6139
- }
6140
- return {
6141
- lens: "General",
6142
- checklist: [
6143
- "1. Read the original task's acceptance criteria",
6144
- `2. Check git log for related commits: \`git log --oneline --author-date-order -10\``,
6145
- "3. Verify code changes match requirements",
6146
- "4. Check if tests were added/updated",
6147
- `5. Look for output files in exe/output/${agent}-${taskSlug}*`
6148
- ]
6149
- };
6191
+ // src/lib/tasks.ts
6192
+ var tasks_exports = {};
6193
+ __export(tasks_exports, {
6194
+ cleanupOrphanedReviews: () => cleanupOrphanedReviews,
6195
+ countNewPendingReviewsSince: () => countNewPendingReviewsSince,
6196
+ countPendingReviews: () => countPendingReviews,
6197
+ createTask: () => createTask,
6198
+ createTaskCore: () => createTaskCore,
6199
+ deleteTask: () => deleteTask,
6200
+ deleteTaskCore: () => deleteTaskCore,
6201
+ ensureArchitectureDoc: () => ensureArchitectureDoc,
6202
+ ensureGitignoreExe: () => ensureGitignoreExe,
6203
+ getReviewChecklist: () => getReviewChecklist,
6204
+ listPendingReviews: () => listPendingReviews,
6205
+ listTasks: () => listTasks,
6206
+ resolveTask: () => resolveTask,
6207
+ slugify: () => slugify,
6208
+ updateTask: () => updateTask,
6209
+ updateTaskStatus: () => updateTaskStatus,
6210
+ writeCheckpoint: () => writeCheckpoint
6211
+ });
6212
+ import path16 from "path";
6213
+ import { writeFileSync as writeFileSync4, mkdirSync as mkdirSync6, unlinkSync as unlinkSync4 } from "fs";
6214
+ async function createTask(input) {
6215
+ const result = await createTaskCore(input);
6216
+ if (!input.skipDispatch && result.status !== "blocked" && !process.env.VITEST) {
6217
+ dispatchTaskToEmployee({
6218
+ assignedTo: input.assignedTo,
6219
+ title: input.title,
6220
+ priority: input.priority,
6221
+ taskFile: result.taskFile,
6222
+ initialStatus: result.status,
6223
+ projectName: input.projectName
6224
+ });
6225
+ }
6226
+ return result;
6150
6227
  }
6151
- async function cleanupReviewFile(row, taskFile, _baseDir) {
6152
- if (String(row.assigned_by) !== "system" || !taskFile.includes("review-")) return;
6228
+ async function updateTask(input) {
6229
+ const { row, taskFile, now, taskId } = await updateTaskStatus(input);
6153
6230
  try {
6154
- const client = getClient();
6155
- const now = (/* @__PURE__ */ new Date()).toISOString();
6156
- const parentId = row.parent_task_id ? String(row.parent_task_id) : null;
6157
- if (parentId) {
6158
- const result = await client.execute({
6159
- sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ? AND status = 'needs_review'",
6160
- args: [now, parentId]
6231
+ const agent = String(row.assigned_to);
6232
+ const cacheDir = path16.join(EXE_AI_DIR, "session-cache");
6233
+ const cachePath = path16.join(cacheDir, `current-task-${agent}.json`);
6234
+ if (input.status === "in_progress") {
6235
+ mkdirSync6(cacheDir, { recursive: true });
6236
+ writeFileSync4(cachePath, JSON.stringify({ taskId, title: String(row.title) }));
6237
+ } else if (input.status === "done" || input.status === "blocked" || input.status === "cancelled") {
6238
+ try {
6239
+ unlinkSync4(cachePath);
6240
+ } catch {
6241
+ }
6242
+ }
6243
+ } catch {
6244
+ }
6245
+ if (input.status === "done") {
6246
+ await cleanupReviewFile(row, taskFile, input.baseDir);
6247
+ }
6248
+ if (input.status === "done" || input.status === "cancelled") {
6249
+ try {
6250
+ const client = getClient();
6251
+ const taskTitle = String(row.title);
6252
+ const escaped = taskTitle.replace(/%/g, "\\%").replace(/_/g, "\\_");
6253
+ await client.execute({
6254
+ sql: `UPDATE tasks SET status = 'cancelled', updated_at = ?
6255
+ WHERE title LIKE ? ESCAPE '\\' AND status IN ('open', 'in_progress')`,
6256
+ args: [now, `%left '${escaped}' as in\\_progress%`]
6161
6257
  });
6162
- if (result.rowsAffected > 0) {
6258
+ } catch {
6259
+ }
6260
+ try {
6261
+ const client = getClient();
6262
+ const cascaded = await client.execute({
6263
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
6264
+ WHERE parent_task_id = ? AND status = 'needs_review'`,
6265
+ args: [now, taskId]
6266
+ });
6267
+ if (cascaded.rowsAffected > 0) {
6163
6268
  process.stderr.write(
6164
- `[review-cleanup] Cascaded original task to done via parent_task_id: ${parentId}
6269
+ `[cascade] Closed ${cascaded.rowsAffected} orphaned review task(s) for parent ${taskId}
6165
6270
  `
6166
6271
  );
6167
6272
  }
6168
- } else {
6169
- const fileName = taskFile.split("/").pop() ?? "";
6170
- const reviewPrefix = fileName.replace(".md", "");
6171
- const parts = reviewPrefix.split("-");
6172
- if (parts.length >= 3 && parts[0] === "review") {
6173
- const agent = parts[1];
6174
- const slug = parts.slice(2).join("-");
6175
- const originalTaskFile = `exe/${agent}/${slug}.md`;
6176
- const result = await client.execute({
6177
- sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE task_file = ? AND status = 'needs_review'",
6178
- args: [now, originalTaskFile]
6179
- });
6180
- if (result.rowsAffected > 0) {
6181
- process.stderr.write(
6182
- `[review-cleanup] Cascaded original task to done (legacy path): ${originalTaskFile}
6183
- `
6184
- );
6273
+ } catch {
6274
+ }
6275
+ }
6276
+ const isTerminal = input.status === "done" || input.status === "needs_review";
6277
+ if (isTerminal) {
6278
+ const isExe = String(row.assigned_to) === "exe";
6279
+ if (!isExe) {
6280
+ notifyTaskDone();
6281
+ }
6282
+ await markTaskNotificationsRead(taskFile);
6283
+ if (input.status === "done") {
6284
+ try {
6285
+ await cascadeUnblock(taskId, input.baseDir, now);
6286
+ } catch {
6287
+ }
6288
+ orgBus.emit({
6289
+ type: "task_completed",
6290
+ taskId,
6291
+ employee: String(row.assigned_to),
6292
+ result: input.result ?? "",
6293
+ timestamp: now
6294
+ });
6295
+ if (row.parent_task_id) {
6296
+ try {
6297
+ await checkSubtaskCompletion(String(row.parent_task_id), String(row.project_name));
6298
+ } catch {
6185
6299
  }
6186
6300
  }
6187
6301
  }
6188
- } catch (err) {
6189
- process.stderr.write(
6190
- `[review-cleanup] Failed to cascade original task: ${err instanceof Error ? err.message : String(err)}
6302
+ }
6303
+ if (input.status === "done" && String(row.assigned_to) !== "exe" && !process.env.VITEST) {
6304
+ Promise.resolve().then(() => (init_skill_learning(), skill_learning_exports)).then(
6305
+ ({ captureAndLearn: captureAndLearn2 }) => captureAndLearn2({
6306
+ taskId,
6307
+ agentId: String(row.assigned_to),
6308
+ projectName: String(row.project_name),
6309
+ taskTitle: String(row.title)
6310
+ })
6311
+ ).catch((err) => {
6312
+ process.stderr.write(
6313
+ `[updateTask] skill learning failed: ${err instanceof Error ? err.message : String(err)}
6191
6314
  `
6192
- );
6315
+ );
6316
+ });
6193
6317
  }
6194
- try {
6195
- const cacheDir = path14.join(EXE_AI_DIR, "session-cache");
6196
- if (existsSync13(cacheDir)) {
6197
- for (const f of readdirSync3(cacheDir)) {
6198
- if (f.startsWith("review-notified-")) {
6199
- unlinkSync4(path14.join(cacheDir, f));
6200
- }
6201
- }
6318
+ let nextTask;
6319
+ if (isTerminal && String(row.assigned_to) !== "exe") {
6320
+ try {
6321
+ nextTask = await findNextTask(String(row.assigned_to));
6322
+ } catch {
6202
6323
  }
6203
- } catch {
6204
6324
  }
6325
+ return {
6326
+ id: String(row.id),
6327
+ title: String(row.title),
6328
+ assignedTo: String(row.assigned_to),
6329
+ assignedBy: String(row.assigned_by),
6330
+ projectName: String(row.project_name),
6331
+ priority: String(row.priority),
6332
+ status: input.status,
6333
+ taskFile,
6334
+ createdAt: String(row.created_at),
6335
+ updatedAt: now,
6336
+ budgetTokens: row.budget_tokens !== void 0 && row.budget_tokens !== null ? Number(row.budget_tokens) : null,
6337
+ budgetFallbackModel: row.budget_fallback_model !== void 0 && row.budget_fallback_model !== null ? String(row.budget_fallback_model) : null,
6338
+ tokensUsed: Number(row.tokens_used ?? 0),
6339
+ tokensWarnedAt: row.tokens_warned_at !== void 0 && row.tokens_warned_at !== null ? Number(row.tokens_warned_at) : null,
6340
+ nextTask
6341
+ };
6205
6342
  }
6206
- var init_tasks_review = __esm({
6207
- "src/lib/tasks-review.ts"() {
6343
+ async function deleteTask(taskId, baseDir) {
6344
+ const client = getClient();
6345
+ const { taskFile, assignedTo, assignedBy, taskSlug } = await deleteTaskCore(taskId, baseDir);
6346
+ const reviewer = assignedBy || "exe";
6347
+ const reviewSlug = `review-${assignedTo}-${taskSlug}`;
6348
+ const reviewFile = `exe/${reviewer}/${reviewSlug}.md`;
6349
+ await client.execute({
6350
+ sql: "DELETE FROM tasks WHERE task_file = ? OR task_file = ?",
6351
+ args: [reviewFile, `exe/exe/${reviewSlug}.md`]
6352
+ });
6353
+ await markAsReadByTaskFile(taskFile);
6354
+ await markAsReadByTaskFile(reviewFile);
6355
+ }
6356
+ var init_tasks = __esm({
6357
+ "src/lib/tasks.ts"() {
6208
6358
  "use strict";
6209
6359
  init_database();
6210
6360
  init_config();
6211
- init_employees();
6212
6361
  init_notifications();
6362
+ init_state_bus();
6213
6363
  init_tasks_crud();
6214
- init_tmux_routing();
6215
- init_session_key();
6364
+ init_tasks_review();
6365
+ init_tasks_crud();
6366
+ init_tasks_chain();
6367
+ init_tasks_review();
6368
+ init_tasks_notify();
6216
6369
  }
6217
6370
  });
6218
6371
 
6219
- // src/lib/tasks-chain.ts
6220
- import path15 from "path";
6221
- import { readFile as readFile4, writeFile as writeFile5 } from "fs/promises";
6222
- async function cascadeUnblock(taskId, baseDir, now) {
6223
- const client = getClient();
6224
- const unblocked = await client.execute({
6225
- sql: `UPDATE tasks SET status = 'open', blocked_by = NULL, updated_at = ?
6226
- WHERE blocked_by = ? AND status = 'blocked'`,
6227
- args: [now, taskId]
6228
- });
6229
- if (baseDir && unblocked.rowsAffected > 0) {
6230
- const unblockedRows = await client.execute({
6231
- sql: `SELECT task_file FROM tasks WHERE blocked_by IS NULL AND updated_at = ?`,
6232
- args: [now]
6233
- });
6234
- for (const ur of unblockedRows.rows) {
6235
- try {
6236
- const ubFile = path15.join(baseDir, String(ur.task_file));
6237
- let ubContent = await readFile4(ubFile, "utf-8");
6238
- ubContent = ubContent.replace(/\*\*Status:\*\* blocked/, "**Status:** open");
6239
- ubContent = ubContent.replace(/\n\*\*Blocked by:\*\*.*\n/, "\n");
6240
- await writeFile5(ubFile, ubContent, "utf-8");
6241
- } catch {
6242
- }
6372
+ // src/lib/capacity-monitor.ts
6373
+ var capacity_monitor_exports = {};
6374
+ __export(capacity_monitor_exports, {
6375
+ CTX_FLOOR_PERCENT: () => CTX_FLOOR_PERCENT,
6376
+ _resetLastRelaunchCache: () => _resetLastRelaunchCache,
6377
+ _resetPendingCapacityKills: () => _resetPendingCapacityKills,
6378
+ confirmCapacityKill: () => confirmCapacityKill,
6379
+ createOrRefreshResumeTask: () => createOrRefreshResumeTask,
6380
+ extractContextPercent: () => extractContextPercent,
6381
+ isAtCapacity: () => isAtCapacity,
6382
+ isWithinRelaunchCooldown: () => isWithinRelaunchCooldown,
6383
+ pollCapacityDead: () => pollCapacityDead
6384
+ });
6385
+ function resumeTaskTitle(agentId) {
6386
+ return `${RESUME_TITLE_PREFIX} ${agentId} hit context capacity \u2014 continue open tasks`;
6387
+ }
6388
+ function buildResumeContext(agentId, openTasks) {
6389
+ const taskList = openTasks.map(
6390
+ (r, i) => `${i + 1}. [${String(r.priority).toUpperCase()}] ${String(r.title)} (${String(r.task_file)})`
6391
+ ).join("\n");
6392
+ return [
6393
+ "## Context",
6394
+ "",
6395
+ `${agentId} hit context capacity and was auto-relaunched by the capacity monitor.`,
6396
+ "Call recall_my_memory first \u2014 search for 'CONTEXT CHECKPOINT'. Pick up where the previous session stopped.",
6397
+ "",
6398
+ `You have ${openTasks.length} open task(s). Work through them in priority order:`,
6399
+ "",
6400
+ taskList,
6401
+ "",
6402
+ "Read each task file and chain through them. Build and commit after each one."
6403
+ ].join("\n");
6404
+ }
6405
+ function filterPaneContent(paneOutput) {
6406
+ return paneOutput.split("\n").filter((line) => {
6407
+ if (CONTENT_LINE_PREFIX.test(line)) return false;
6408
+ for (const marker of CONTENT_LINE_MARKERS) {
6409
+ if (line.includes(marker)) return false;
6410
+ }
6411
+ for (const re of SOURCE_CODE_MARKERS) {
6412
+ if (re.test(line)) return false;
6243
6413
  }
6414
+ return true;
6415
+ }).join("\n");
6416
+ }
6417
+ function extractContextPercent(paneOutput) {
6418
+ const match = paneOutput.match(CC_CONTEXT_BAR_RE);
6419
+ if (!match) return null;
6420
+ const parsed = Number.parseInt(match[2], 10);
6421
+ return Number.isFinite(parsed) ? parsed : null;
6422
+ }
6423
+ function isAtCapacity(paneOutput) {
6424
+ const filtered = filterPaneContent(paneOutput);
6425
+ return CAPACITY_PATTERNS.some((p) => p.test(filtered));
6426
+ }
6427
+ function confirmCapacityKill(agentId, now = Date.now()) {
6428
+ const pendingSince = _pendingCapacityKill.get(agentId);
6429
+ if (pendingSince === void 0) {
6430
+ _pendingCapacityKill.set(agentId, now);
6431
+ return false;
6432
+ }
6433
+ if (now - pendingSince > CONFIRMATION_WINDOW_MS) {
6434
+ _pendingCapacityKill.set(agentId, now);
6435
+ return false;
6244
6436
  }
6437
+ _pendingCapacityKill.delete(agentId);
6438
+ return true;
6245
6439
  }
6246
- async function findNextTask(assignedTo) {
6440
+ function _resetPendingCapacityKills() {
6441
+ _pendingCapacityKill.clear();
6442
+ }
6443
+ function _resetLastRelaunchCache() {
6444
+ _lastRelaunch.clear();
6445
+ }
6446
+ async function lastResumeCreatedAtMs(agentId) {
6247
6447
  const client = getClient();
6248
- const nextResult = await client.execute({
6249
- sql: `SELECT title, task_file, priority FROM tasks
6250
- WHERE assigned_to = ? AND status = 'open'
6251
- ORDER BY priority ASC, created_at ASC
6252
- LIMIT 1`,
6253
- args: [assignedTo]
6448
+ const result = await client.execute({
6449
+ sql: `SELECT MAX(created_at) AS last_created_at
6450
+ FROM tasks
6451
+ WHERE assigned_to = ? AND title LIKE ?`,
6452
+ args: [agentId, `${RESUME_TITLE_PREFIX} %`]
6254
6453
  });
6255
- if (nextResult.rows.length === 1) {
6256
- const nr = nextResult.rows[0];
6257
- return {
6258
- title: String(nr.title),
6259
- priority: String(nr.priority),
6260
- taskFile: String(nr.task_file)
6261
- };
6262
- }
6263
- return void 0;
6454
+ const raw = result.rows[0]?.last_created_at;
6455
+ if (raw === null || raw === void 0) return null;
6456
+ const parsed = Date.parse(String(raw));
6457
+ return Number.isNaN(parsed) ? null : parsed;
6458
+ }
6459
+ async function isWithinRelaunchCooldown(agentId, now = Date.now()) {
6460
+ const cached = _lastRelaunch.get(agentId);
6461
+ if (cached !== void 0) return now - cached < RELAUNCH_COOLDOWN_MS;
6462
+ const persisted = await lastResumeCreatedAtMs(agentId);
6463
+ if (persisted === null) return false;
6464
+ if (now - persisted >= RELAUNCH_COOLDOWN_MS) return false;
6465
+ _lastRelaunch.set(agentId, persisted);
6466
+ return true;
6264
6467
  }
6265
- async function checkSubtaskCompletion(parentTaskId, projectName) {
6468
+ async function createOrRefreshResumeTask(agentId, projectDir, openTasks) {
6266
6469
  const client = getClient();
6267
- const remaining = await client.execute({
6268
- sql: `SELECT COUNT(*) as cnt FROM tasks
6269
- WHERE parent_task_id = ? AND status NOT IN ('done', 'cancelled')`,
6270
- args: [parentTaskId]
6470
+ const now = (/* @__PURE__ */ new Date()).toISOString();
6471
+ const context = buildResumeContext(agentId, openTasks);
6472
+ const existing = await client.execute({
6473
+ sql: `SELECT id FROM tasks
6474
+ WHERE assigned_to = ?
6475
+ AND title LIKE ?
6476
+ AND status IN (${RESUME_ACTIVE_STATUSES.map(() => "?").join(", ")})
6477
+ ORDER BY created_at DESC
6478
+ LIMIT 1`,
6479
+ args: [agentId, RESUME_TITLE_LIKE_PATTERN, ...RESUME_ACTIVE_STATUSES]
6271
6480
  });
6272
- const cnt = Number(remaining.rows[0]?.cnt ?? 1);
6273
- if (cnt === 0) {
6274
- const parentRow = await client.execute({
6275
- sql: `SELECT assigned_to, title, task_file, project_name FROM tasks WHERE id = ?`,
6276
- args: [parentTaskId]
6481
+ if (existing.rows.length > 0) {
6482
+ const taskId = String(existing.rows[0].id);
6483
+ await client.execute({
6484
+ sql: `UPDATE tasks SET context = ?, updated_at = ? WHERE id = ?`,
6485
+ args: [context, now, taskId]
6277
6486
  });
6278
- if (parentRow.rows.length === 1) {
6279
- const pr = parentRow.rows[0];
6280
- const parentProject = pr.project_name == null ? projectName : String(pr.project_name);
6281
- await writeNotification({
6282
- agentId: String(pr.assigned_to),
6283
- agentRole: "system",
6284
- event: "subtasks_complete",
6285
- project: parentProject,
6286
- summary: `All subtasks complete for "${String(pr.title)}" \u2014 ready for rollup review`,
6287
- taskFile: String(pr.task_file)
6487
+ return { created: false, taskId };
6488
+ }
6489
+ const { createTask: createTask2 } = await Promise.resolve().then(() => (init_tasks(), tasks_exports));
6490
+ const task = await createTask2({
6491
+ title: resumeTaskTitle(agentId),
6492
+ assignedTo: agentId,
6493
+ assignedBy: "system",
6494
+ projectName: projectDir.split("/").pop() ?? "unknown",
6495
+ priority: "p0",
6496
+ context,
6497
+ baseDir: projectDir
6498
+ });
6499
+ return { created: true, taskId: task.id };
6500
+ }
6501
+ async function pollCapacityDead() {
6502
+ const transport = getTransport();
6503
+ const relaunched = [];
6504
+ const registered = listSessions().filter(
6505
+ (s) => s.agentId !== "exe"
6506
+ );
6507
+ if (registered.length === 0) return [];
6508
+ let liveSessions;
6509
+ try {
6510
+ liveSessions = transport.listSessions();
6511
+ } catch {
6512
+ return [];
6513
+ }
6514
+ for (const entry of registered) {
6515
+ const { windowName, agentId, projectDir } = entry;
6516
+ if (!liveSessions.includes(windowName)) continue;
6517
+ if (await isWithinRelaunchCooldown(agentId)) continue;
6518
+ let pane;
6519
+ try {
6520
+ pane = transport.capturePane(windowName, 15);
6521
+ } catch {
6522
+ continue;
6523
+ }
6524
+ if (!isAtCapacity(pane)) continue;
6525
+ const ctxPct = extractContextPercent(pane);
6526
+ if (ctxPct !== null && ctxPct < CTX_FLOOR_PERCENT) {
6527
+ process.stderr.write(
6528
+ `[capacity-monitor] ctx-floor: ${agentId} at ${ctxPct}% in ${windowName} \u2014 below ${CTX_FLOOR_PERCENT}%. Skipping capacity kill (likely self-referential content or false positive).
6529
+ `
6530
+ );
6531
+ continue;
6532
+ }
6533
+ if (!confirmCapacityKill(agentId)) {
6534
+ process.stderr.write(
6535
+ `[capacity-monitor] ${agentId} matched capacity pattern once in ${windowName}. Awaiting confirmation on next tick.
6536
+ `
6537
+ );
6538
+ continue;
6539
+ }
6540
+ const verify = await verifyPaneAtCapacity(windowName);
6541
+ if (!verify.atCapacity) {
6542
+ process.stderr.write(
6543
+ `[capacity-monitor] verifyPaneAtCapacity rejected kill for ${agentId} in ${windowName} (reason: ${verify.reason}). Skipping.
6544
+ `
6545
+ );
6546
+ void recordSessionKill({
6547
+ sessionName: windowName,
6548
+ agentId,
6549
+ reason: "capacity_false_positive_blocked"
6550
+ });
6551
+ continue;
6552
+ }
6553
+ process.stderr.write(
6554
+ `[capacity-monitor] Detected ${agentId} at capacity in session ${windowName} (confirmed). Auto-relaunching.
6555
+ `
6556
+ );
6557
+ try {
6558
+ transport.kill(windowName);
6559
+ void recordSessionKill({
6560
+ sessionName: windowName,
6561
+ agentId,
6562
+ reason: "capacity"
6563
+ });
6564
+ const client = getClient();
6565
+ const openTasks = await client.execute({
6566
+ sql: `SELECT id, title, priority, task_file, status
6567
+ FROM tasks
6568
+ WHERE assigned_to = ? AND status IN ('open', 'in_progress')
6569
+ ORDER BY
6570
+ CASE priority WHEN 'p0' THEN 0 WHEN 'p1' THEN 1 WHEN 'p2' THEN 2 ELSE 3 END,
6571
+ created_at ASC
6572
+ LIMIT 10`,
6573
+ args: [agentId]
6288
6574
  });
6575
+ if (openTasks.rows.length === 0) {
6576
+ process.stderr.write(
6577
+ `[capacity-monitor] ${agentId} has no open tasks \u2014 skipping relaunch.
6578
+ `
6579
+ );
6580
+ continue;
6581
+ }
6582
+ const { created } = await createOrRefreshResumeTask(
6583
+ agentId,
6584
+ projectDir,
6585
+ openTasks.rows
6586
+ );
6587
+ if (created) {
6588
+ await writeNotification({
6589
+ agentId: "system",
6590
+ agentRole: "daemon",
6591
+ event: "capacity_relaunch",
6592
+ project: projectDir.split("/").pop() ?? "unknown",
6593
+ summary: `${agentId} hit context capacity. Auto-relaunched with ${openTasks.rows.length} open task(s).`
6594
+ });
6595
+ }
6596
+ _lastRelaunch.set(agentId, Date.now());
6597
+ if (created) relaunched.push(agentId);
6598
+ } catch (err) {
6599
+ process.stderr.write(
6600
+ `[capacity-monitor] Failed to relaunch ${agentId}: ${err instanceof Error ? err.message : String(err)}
6601
+ `
6602
+ );
6289
6603
  }
6290
6604
  }
6605
+ return relaunched;
6291
6606
  }
6292
- var init_tasks_chain = __esm({
6293
- "src/lib/tasks-chain.ts"() {
6607
+ 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;
6608
+ var init_capacity_monitor = __esm({
6609
+ "src/lib/capacity-monitor.ts"() {
6294
6610
  "use strict";
6295
- init_database();
6611
+ init_session_registry();
6612
+ init_transport();
6296
6613
  init_notifications();
6614
+ init_database();
6615
+ init_session_kill_telemetry();
6616
+ init_tmux_routing();
6617
+ CAPACITY_PATTERNS = [
6618
+ /conversation is too long/i,
6619
+ /maximum context length/i,
6620
+ /context window.*(?:limit|exceed|full)/i,
6621
+ /reached.*(?:token|context).*limit/i
6622
+ ];
6623
+ CONTENT_LINE_PREFIX = /^[\s>#\-*[]/;
6624
+ CONTENT_LINE_MARKERS = [
6625
+ "RESUME:",
6626
+ "intercom",
6627
+ "capacity-monitor",
6628
+ "CAPACITY_PATTERNS",
6629
+ "isAtCapacity",
6630
+ "CONTENT_LINE_MARKERS",
6631
+ "pollCapacityDead",
6632
+ "confirmCapacityKill",
6633
+ "session_kills",
6634
+ "capacity-monitor.test"
6635
+ ];
6636
+ SOURCE_CODE_MARKERS = [
6637
+ /["'`/].*(?:maximum context length|conversation is too long)/i,
6638
+ /(?:maximum context length|conversation is too long).*["'`/]/i
6639
+ ];
6640
+ RELAUNCH_COOLDOWN_MS = 5 * 60 * 1e3;
6641
+ _lastRelaunch = /* @__PURE__ */ new Map();
6642
+ RESUME_TITLE_PREFIX = "RESUME:";
6643
+ RESUME_TITLE_LIKE_PATTERN = `${RESUME_TITLE_PREFIX} % hit context capacity%`;
6644
+ RESUME_ACTIVE_STATUSES = ["open", "in_progress"];
6645
+ CONFIRMATION_WINDOW_MS = 3 * 60 * 1e3;
6646
+ _pendingCapacityKill = /* @__PURE__ */ new Map();
6647
+ CC_CONTEXT_BAR_RE = /([\u2588\u2591\u2592\u2593]{10})\s+(\d+)%/;
6648
+ CTX_FLOOR_PERCENT = 50;
6297
6649
  }
6298
6650
  });
6299
6651
 
6300
- // src/lib/project-name.ts
6301
- import { execSync as execSync6 } from "child_process";
6302
- import path16 from "path";
6303
- function getProjectName(cwd) {
6304
- const dir = cwd ?? process.cwd();
6305
- if (_cached2 && _cachedCwd === dir) return _cached2;
6652
+ // src/lib/tmux-routing.ts
6653
+ var tmux_routing_exports = {};
6654
+ __export(tmux_routing_exports, {
6655
+ acquireSpawnLock: () => acquireSpawnLock2,
6656
+ employeeSessionName: () => employeeSessionName,
6657
+ ensureEmployee: () => ensureEmployee,
6658
+ extractRootExe: () => extractRootExe,
6659
+ findFreeInstance: () => findFreeInstance,
6660
+ getDispatchedBy: () => getDispatchedBy,
6661
+ getMySession: () => getMySession,
6662
+ getParentExe: () => getParentExe,
6663
+ getSessionState: () => getSessionState,
6664
+ isEmployeeAlive: () => isEmployeeAlive,
6665
+ isExeSession: () => isExeSession,
6666
+ isSessionBusy: () => isSessionBusy,
6667
+ notifyParentExe: () => notifyParentExe,
6668
+ parseParentExe: () => parseParentExe,
6669
+ registerParentExe: () => registerParentExe,
6670
+ releaseSpawnLock: () => releaseSpawnLock2,
6671
+ resolveExeSession: () => resolveExeSession,
6672
+ sendIntercom: () => sendIntercom,
6673
+ spawnEmployee: () => spawnEmployee,
6674
+ verifyPaneAtCapacity: () => verifyPaneAtCapacity
6675
+ });
6676
+ import { execFileSync as execFileSync2, execSync as execSync6 } from "child_process";
6677
+ import { readFileSync as readFileSync11, writeFileSync as writeFileSync5, mkdirSync as mkdirSync7, existsSync as existsSync13, appendFileSync } from "fs";
6678
+ import path17 from "path";
6679
+ import os7 from "os";
6680
+ import { fileURLToPath as fileURLToPath2 } from "url";
6681
+ import { unlinkSync as unlinkSync5 } from "fs";
6682
+ function spawnLockPath(sessionName) {
6683
+ return path17.join(SPAWN_LOCK_DIR, `${sessionName}.lock`);
6684
+ }
6685
+ function isProcessAlive(pid) {
6306
6686
  try {
6307
- let repoRoot;
6687
+ process.kill(pid, 0);
6688
+ return true;
6689
+ } catch {
6690
+ return false;
6691
+ }
6692
+ }
6693
+ function acquireSpawnLock2(sessionName) {
6694
+ if (!existsSync13(SPAWN_LOCK_DIR)) {
6695
+ mkdirSync7(SPAWN_LOCK_DIR, { recursive: true });
6696
+ }
6697
+ const lockFile = spawnLockPath(sessionName);
6698
+ if (existsSync13(lockFile)) {
6308
6699
  try {
6309
- const gitCommonDir = execSync6("git rev-parse --path-format=absolute --git-common-dir", {
6310
- cwd: dir,
6311
- encoding: "utf8",
6312
- timeout: 2e3,
6313
- stdio: ["pipe", "pipe", "pipe"]
6314
- }).trim();
6315
- repoRoot = path16.dirname(gitCommonDir);
6700
+ const lock = JSON.parse(readFileSync11(lockFile, "utf8"));
6701
+ const age = Date.now() - lock.timestamp;
6702
+ if (isProcessAlive(lock.pid) && age < 6e4) {
6703
+ return false;
6704
+ }
6316
6705
  } catch {
6317
- repoRoot = execSync6("git rev-parse --show-toplevel", {
6318
- cwd: dir,
6319
- encoding: "utf8",
6320
- timeout: 2e3,
6321
- stdio: ["pipe", "pipe", "pipe"]
6322
- }).trim();
6323
6706
  }
6324
- _cached2 = path16.basename(repoRoot);
6325
- _cachedCwd = dir;
6326
- return _cached2;
6327
- } catch {
6328
- _cached2 = path16.basename(dir);
6329
- _cachedCwd = dir;
6330
- return _cached2;
6331
6707
  }
6708
+ writeFileSync5(lockFile, JSON.stringify({ pid: process.pid, timestamp: Date.now() }));
6709
+ return true;
6332
6710
  }
6333
- var _cached2, _cachedCwd;
6334
- var init_project_name = __esm({
6335
- "src/lib/project-name.ts"() {
6336
- "use strict";
6337
- _cached2 = null;
6338
- _cachedCwd = null;
6711
+ function releaseSpawnLock2(sessionName) {
6712
+ try {
6713
+ unlinkSync5(spawnLockPath(sessionName));
6714
+ } catch {
6339
6715
  }
6340
- });
6341
-
6342
- // src/lib/session-scope.ts
6343
- var session_scope_exports = {};
6344
- __export(session_scope_exports, {
6345
- assertSessionScope: () => assertSessionScope,
6346
- findSessionForProject: () => findSessionForProject,
6347
- getSessionProject: () => getSessionProject
6348
- });
6349
- function getSessionProject(sessionName) {
6350
- const sessions = listSessions();
6351
- const entry = sessions.find((s) => s.windowName === sessionName);
6352
- if (!entry) return null;
6353
- const parts = entry.projectDir.split("/").filter(Boolean);
6354
- return parts[parts.length - 1] ?? null;
6355
6716
  }
6356
- function findSessionForProject(projectName) {
6357
- const sessions = listSessions();
6358
- for (const s of sessions) {
6359
- const proj = s.projectDir.split("/").filter(Boolean).pop();
6360
- if (proj === projectName && s.agentId === "exe") return s;
6717
+ function resolveBehaviorsExporterScript() {
6718
+ try {
6719
+ const thisFile = fileURLToPath2(import.meta.url);
6720
+ const scriptPath = path17.join(
6721
+ path17.dirname(thisFile),
6722
+ "..",
6723
+ "bin",
6724
+ "exe-export-behaviors.js"
6725
+ );
6726
+ return existsSync13(scriptPath) ? scriptPath : null;
6727
+ } catch {
6728
+ return null;
6361
6729
  }
6362
- return null;
6363
6730
  }
6364
- function assertSessionScope(actionType, targetProject) {
6731
+ function exportBehaviorsSync(agentId, projectName, sessionKey) {
6732
+ const script = resolveBehaviorsExporterScript();
6733
+ if (!script) return null;
6365
6734
  try {
6366
- const currentProject = getProjectName();
6367
- const exeSession = resolveExeSession();
6368
- if (!exeSession) {
6369
- return { allowed: true, reason: "no_session" };
6370
- }
6371
- if (currentProject === targetProject) {
6372
- return {
6373
- allowed: true,
6374
- reason: "same_session",
6375
- currentProject,
6376
- targetProject
6377
- };
6378
- }
6735
+ const output = execFileSync2(
6736
+ process.execPath,
6737
+ [script, agentId, projectName, sessionKey],
6738
+ { encoding: "utf-8", timeout: BEHAVIORS_EXPORT_TIMEOUT_MS }
6739
+ ).trim();
6740
+ return output.length > 0 ? output : null;
6741
+ } catch (err) {
6379
6742
  process.stderr.write(
6380
- `[session-scope] Cross-project ${actionType}: session project="${currentProject}" \u2260 target project="${targetProject}"
6743
+ `[tmux-routing] behaviors export failed for ${agentId}: ${err instanceof Error ? err.message : String(err)}
6381
6744
  `
6382
6745
  );
6383
- return {
6384
- allowed: true,
6385
- // v1: warn-only, don't block
6386
- reason: "cross_session_granted",
6387
- currentProject,
6388
- targetProject,
6389
- targetSession: findSessionForProject(targetProject)?.windowName
6390
- };
6746
+ return null;
6747
+ }
6748
+ }
6749
+ function getMySession() {
6750
+ return getTransport().getMySession();
6751
+ }
6752
+ function employeeSessionName(employee, exeSession, instance) {
6753
+ if (!/^exe\d+$/.test(exeSession)) {
6754
+ const root = extractRootExe(exeSession);
6755
+ if (root) {
6756
+ process.stderr.write(
6757
+ `[tmux-routing] WARN: exeSession="${exeSession}" is not a root exe session, using "${root}" instead
6758
+ `
6759
+ );
6760
+ exeSession = root;
6761
+ } else {
6762
+ throw new Error(
6763
+ `Invalid exeSession "${exeSession}" \u2014 must be a root exe session (e.g., "exe1"), not an agent session`
6764
+ );
6765
+ }
6766
+ }
6767
+ const suffix = instance != null && instance > 0 ? String(instance) : "";
6768
+ const name = `${employee}${suffix}-${exeSession}`;
6769
+ if (!VALID_SESSION_NAME.test(name)) {
6770
+ throw new Error(
6771
+ `Invalid session name "${name}" \u2014 must match {agent}-exe{N} or {agent}{instance}-exe{N}`
6772
+ );
6773
+ }
6774
+ return name;
6775
+ }
6776
+ function parseParentExe(sessionName, agentId) {
6777
+ const escaped = agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6778
+ const regex = new RegExp(`^${escaped}\\d*-(.+)$`);
6779
+ const match = sessionName.match(regex);
6780
+ return match?.[1] ?? null;
6781
+ }
6782
+ function extractRootExe(name) {
6783
+ const match = name.match(/(exe\d+)$/);
6784
+ return match?.[1] ?? null;
6785
+ }
6786
+ function registerParentExe(sessionKey, parentExe, dispatchedBy) {
6787
+ if (!existsSync13(SESSION_CACHE)) {
6788
+ mkdirSync7(SESSION_CACHE, { recursive: true });
6789
+ }
6790
+ const rootExe = extractRootExe(parentExe) ?? parentExe;
6791
+ const filePath = path17.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`);
6792
+ writeFileSync5(filePath, JSON.stringify({
6793
+ parentExe: rootExe,
6794
+ dispatchedBy: dispatchedBy || rootExe,
6795
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString()
6796
+ }));
6797
+ }
6798
+ function getParentExe(sessionKey) {
6799
+ try {
6800
+ const data = JSON.parse(readFileSync11(path17.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
6801
+ return data.parentExe || null;
6391
6802
  } catch {
6392
- return { allowed: true, reason: "no_session" };
6803
+ return null;
6393
6804
  }
6394
6805
  }
6395
- var init_session_scope = __esm({
6396
- "src/lib/session-scope.ts"() {
6397
- "use strict";
6398
- init_session_registry();
6399
- init_project_name();
6400
- init_tmux_routing();
6806
+ function getDispatchedBy(sessionKey) {
6807
+ try {
6808
+ const data = JSON.parse(readFileSync11(
6809
+ path17.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`),
6810
+ "utf8"
6811
+ ));
6812
+ return data.dispatchedBy ?? data.parentExe ?? null;
6813
+ } catch {
6814
+ return null;
6401
6815
  }
6402
- });
6403
-
6404
- // src/lib/tasks-notify.ts
6405
- async function dispatchTaskToEmployee(input) {
6406
- if (input.assignedTo === "exe") return { dispatched: "skipped" };
6407
- let crossProject = false;
6408
- if (input.projectName) {
6409
- try {
6410
- const { assertSessionScope: assertSessionScope2 } = (init_session_scope(), __toCommonJS(session_scope_exports));
6411
- const check = assertSessionScope2("dispatch_task", input.projectName);
6412
- if (check.reason === "cross_session_granted") {
6413
- crossProject = true;
6414
- }
6415
- } catch {
6816
+ }
6817
+ function resolveExeSession() {
6818
+ const mySession = getMySession();
6819
+ if (!mySession) return null;
6820
+ try {
6821
+ const key = getSessionKey();
6822
+ const parentExe = getParentExe(key);
6823
+ if (parentExe) {
6824
+ return extractRootExe(parentExe) ?? parentExe;
6416
6825
  }
6826
+ } catch {
6827
+ }
6828
+ return extractRootExe(mySession) ?? mySession;
6829
+ }
6830
+ function isEmployeeAlive(sessionName) {
6831
+ return getTransport().isAlive(sessionName);
6832
+ }
6833
+ function findFreeInstance(employeeName, exeSession, maxInstances = 10, isAlive = isEmployeeAlive) {
6834
+ const base = employeeSessionName(employeeName, exeSession);
6835
+ if (!isAlive(base) && acquireSpawnLock2(base)) return 0;
6836
+ for (let i = 2; i <= maxInstances; i++) {
6837
+ const candidate = employeeSessionName(employeeName, exeSession, i);
6838
+ if (!isAlive(candidate) && acquireSpawnLock2(candidate)) return i;
6839
+ }
6840
+ return null;
6841
+ }
6842
+ async function verifyPaneAtCapacity(sessionName) {
6843
+ const transport = getTransport();
6844
+ if (!transport.isAlive(sessionName)) {
6845
+ return { atCapacity: false, reason: `session ${sessionName} is not alive` };
6417
6846
  }
6847
+ let pane;
6418
6848
  try {
6419
- const transport = getTransport();
6420
- const exeSession = resolveExeSession();
6421
- if (!exeSession) return { dispatched: "session_missing" };
6422
- const sessionName = employeeSessionName(input.assignedTo, exeSession);
6423
- if (transport.isAlive(sessionName)) {
6424
- const result = sendIntercom(sessionName);
6425
- const dispatched = result === "acknowledged" || result === "debounced" || result === "queued" ? "verified" : result === "delivered" ? "sent_unverified" : "session_dead";
6426
- return { dispatched, session: sessionName, crossProject };
6427
- } else {
6428
- const projectDir = input.projectDir ?? process.cwd();
6429
- const result = ensureEmployee(input.assignedTo, exeSession, projectDir, {
6430
- autoInstance: isMultiInstance(input.assignedTo)
6431
- });
6432
- if (result.status === "failed") {
6433
- process.stderr.write(
6434
- `[dispatch] Failed to spawn ${input.assignedTo}: ${result.error}
6435
- `
6436
- );
6437
- return { dispatched: "session_missing" };
6438
- }
6439
- return { dispatched: "spawned", session: result.sessionName, crossProject };
6440
- }
6849
+ pane = transport.capturePane(sessionName, VERIFY_PANE_LINES);
6850
+ } catch (err) {
6851
+ return {
6852
+ atCapacity: false,
6853
+ reason: `capture-pane failed: ${err instanceof Error ? err.message : String(err)}`
6854
+ };
6855
+ }
6856
+ const { isAtCapacity: isAtCapacity2 } = await Promise.resolve().then(() => (init_capacity_monitor(), capacity_monitor_exports));
6857
+ if (!isAtCapacity2(pane)) {
6858
+ return {
6859
+ atCapacity: false,
6860
+ reason: `last ${VERIFY_PANE_LINES} lines show normal work, no capacity banner`
6861
+ };
6862
+ }
6863
+ return {
6864
+ atCapacity: true,
6865
+ reason: "capacity banner matched in recent pane output"
6866
+ };
6867
+ }
6868
+ function readDebounceState() {
6869
+ try {
6870
+ if (!existsSync13(DEBOUNCE_FILE)) return {};
6871
+ return JSON.parse(readFileSync11(DEBOUNCE_FILE, "utf8"));
6441
6872
  } catch {
6442
- return { dispatched: "session_missing" };
6873
+ return {};
6443
6874
  }
6444
6875
  }
6445
- function notifyTaskDone() {
6876
+ function writeDebounceState(state) {
6446
6877
  try {
6447
- const key = getSessionKey();
6448
- if (key && !process.env.VITEST) notifyParentExe(key);
6878
+ if (!existsSync13(SESSION_CACHE)) mkdirSync7(SESSION_CACHE, { recursive: true });
6879
+ writeFileSync5(DEBOUNCE_FILE, JSON.stringify(state));
6449
6880
  } catch {
6450
6881
  }
6451
6882
  }
6452
- async function markTaskNotificationsRead(taskFile) {
6883
+ function isDebounced(targetSession) {
6884
+ const state = readDebounceState();
6885
+ const lastSent = state[targetSession] ?? 0;
6886
+ return Date.now() - lastSent < INTERCOM_DEBOUNCE_MS;
6887
+ }
6888
+ function recordDebounce(targetSession) {
6889
+ const state = readDebounceState();
6890
+ state[targetSession] = Date.now();
6891
+ const cutoff = Date.now() - DEBOUNCE_CLEANUP_AGE_MS;
6892
+ for (const key of Object.keys(state)) {
6893
+ if ((state[key] ?? 0) < cutoff) delete state[key];
6894
+ }
6895
+ writeDebounceState(state);
6896
+ }
6897
+ function logIntercom(msg) {
6898
+ const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${msg}
6899
+ `;
6900
+ process.stderr.write(`[intercom] ${msg}
6901
+ `);
6453
6902
  try {
6454
- await markAsReadByTaskFile(taskFile);
6903
+ appendFileSync(INTERCOM_LOG2, line);
6455
6904
  } catch {
6456
6905
  }
6457
6906
  }
6458
- var init_tasks_notify = __esm({
6459
- "src/lib/tasks-notify.ts"() {
6460
- "use strict";
6461
- init_tmux_routing();
6462
- init_session_key();
6463
- init_notifications();
6464
- init_transport();
6465
- init_employees();
6907
+ function getSessionState(sessionName) {
6908
+ const transport = getTransport();
6909
+ if (!transport.isAlive(sessionName)) return "offline";
6910
+ try {
6911
+ const pane = transport.capturePane(sessionName, 5);
6912
+ if (!pane.includes("\u276F") && !pane.includes("Claude Code") && !BUSY_PATTERN.test(pane) && !/Running…/.test(pane)) {
6913
+ if (/\$\s*$/.test(pane) || /% $/.test(pane.trimEnd())) {
6914
+ return "no_claude";
6915
+ }
6916
+ }
6917
+ if (/Running…/.test(pane)) return "tool";
6918
+ if (BUSY_PATTERN.test(pane)) return "thinking";
6919
+ return "idle";
6920
+ } catch {
6921
+ return "offline";
6466
6922
  }
6467
- });
6468
-
6469
- // src/lib/behaviors.ts
6470
- import crypto6 from "crypto";
6471
- async function storeBehavior(opts) {
6472
- const client = getClient();
6473
- const id = crypto6.randomUUID();
6474
- const now = (/* @__PURE__ */ new Date()).toISOString();
6475
- await client.execute({
6476
- sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, priority, content, active, created_at, updated_at)
6477
- VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)`,
6478
- args: [id, opts.agentId, opts.projectName ?? null, opts.domain ?? null, opts.priority ?? "p1", opts.content, now, now]
6479
- });
6480
- return id;
6481
6923
  }
6482
- var init_behaviors = __esm({
6483
- "src/lib/behaviors.ts"() {
6484
- "use strict";
6485
- init_database();
6924
+ function isSessionBusy(sessionName) {
6925
+ const state = getSessionState(sessionName);
6926
+ return state === "thinking" || state === "tool";
6927
+ }
6928
+ function isExeSession(sessionName) {
6929
+ return /^exe\d*$/.test(sessionName);
6930
+ }
6931
+ function sendIntercom(targetSession) {
6932
+ const transport = getTransport();
6933
+ if (isExeSession(targetSession)) {
6934
+ logIntercom(`SKIP_EXE \u2192 ${targetSession} (exe sessions use prompt-submit hook)`);
6935
+ return "skipped_exe";
6486
6936
  }
6487
- });
6488
-
6489
- // src/lib/skill-learning.ts
6490
- var skill_learning_exports = {};
6491
- __export(skill_learning_exports, {
6492
- captureAndLearn: () => captureAndLearn,
6493
- captureTrajectory: () => captureTrajectory,
6494
- editDistance: () => editDistance,
6495
- extractSkill: () => extractSkill,
6496
- extractTrajectory: () => extractTrajectory,
6497
- findSimilarTrajectories: () => findSimilarTrajectories,
6498
- hashSignature: () => hashSignature,
6499
- storeTrajectory: () => storeTrajectory,
6500
- sweepTrajectories: () => sweepTrajectories
6501
- });
6502
- import crypto7 from "crypto";
6503
- async function extractTrajectory(taskId, agentId) {
6504
- const client = getClient();
6505
- const result = await client.execute({
6506
- sql: `SELECT tool_name, raw_text
6507
- FROM memories
6508
- WHERE task_id = ? AND agent_id = ?
6509
- ORDER BY timestamp ASC`,
6510
- args: [taskId, agentId]
6511
- });
6512
- if (result.rows.length === 0) return [];
6513
- const rawTools = result.rows.map((r) => {
6514
- const toolName = String(r.tool_name);
6515
- if (toolName === "Bash") {
6516
- const text = String(r.raw_text);
6517
- const cmdMatch = text.match(/(?:command|Command).*?[:\s]+"?(\w+)/);
6518
- return cmdMatch ? `Bash:${cmdMatch[1]}` : "Bash";
6937
+ if (isDebounced(targetSession)) {
6938
+ logIntercom(`DEBOUNCE \u2192 ${targetSession} (cross-process file debounce)`);
6939
+ return "debounced";
6940
+ }
6941
+ try {
6942
+ const sessions = transport.listSessions();
6943
+ if (!sessions.includes(targetSession)) {
6944
+ logIntercom(`SKIP \u2192 ${targetSession} (session not found)`);
6945
+ return "failed";
6519
6946
  }
6520
- return toolName;
6521
- });
6522
- const signature = [];
6523
- for (const tool of rawTools) {
6524
- if (signature.length === 0 || signature[signature.length - 1] !== tool) {
6525
- signature.push(tool);
6947
+ const sessionState = getSessionState(targetSession);
6948
+ if (sessionState === "no_claude") {
6949
+ queueIntercom(targetSession, "claude not running in session");
6950
+ recordDebounce(targetSession);
6951
+ logIntercom(`QUEUED \u2192 ${targetSession} (no claude process \u2014 raw shell detected)`);
6952
+ return "queued";
6953
+ }
6954
+ if (sessionState === "thinking" || sessionState === "tool") {
6955
+ queueIntercom(targetSession, "session busy at send time");
6956
+ recordDebounce(targetSession);
6957
+ logIntercom(`QUEUED \u2192 ${targetSession} (session busy, will retry from queue)`);
6958
+ return "queued";
6959
+ }
6960
+ if (transport.isPaneInCopyMode(targetSession)) {
6961
+ logIntercom(`COPY_MODE \u2192 ${targetSession} (exiting copy mode first)`);
6962
+ transport.sendKeys(targetSession, "q");
6526
6963
  }
6964
+ transport.sendKeys(targetSession, "/exe-intercom");
6965
+ recordDebounce(targetSession);
6966
+ logIntercom(`DELIVERED \u2192 ${targetSession} (fire-and-forget)`);
6967
+ return "delivered";
6968
+ } catch {
6969
+ logIntercom(`FAIL \u2192 ${targetSession}`);
6970
+ return "failed";
6527
6971
  }
6528
- return signature;
6529
6972
  }
6530
- function hashSignature(signature) {
6531
- return crypto7.createHash("sha256").update(signature.join("|")).digest("hex").slice(0, 16);
6532
- }
6533
- async function storeTrajectory(opts) {
6534
- const client = getClient();
6535
- const id = crypto7.randomUUID();
6536
- const now = (/* @__PURE__ */ new Date()).toISOString();
6537
- const signatureHash = hashSignature(opts.signature);
6538
- await client.execute({
6539
- sql: `INSERT INTO trajectories (id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at)
6540
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
6541
- args: [
6542
- id,
6543
- opts.taskId,
6544
- opts.agentId,
6545
- opts.projectName,
6546
- opts.taskTitle,
6547
- JSON.stringify(opts.signature),
6548
- signatureHash,
6549
- opts.signature.length,
6550
- now
6551
- ]
6552
- });
6553
- return id;
6973
+ function notifyParentExe(sessionKey) {
6974
+ const target = getDispatchedBy(sessionKey);
6975
+ if (!target) {
6976
+ process.stderr.write(`[intercom] notifyParentExe: no dispatcher found for key ${sessionKey}
6977
+ `);
6978
+ return false;
6979
+ }
6980
+ process.stderr.write(`[intercom] notifyParentExe \u2192 ${target}
6981
+ `);
6982
+ const result = sendIntercom(target);
6983
+ if (result === "failed") {
6984
+ const rootExe = resolveExeSession();
6985
+ if (rootExe && rootExe !== target) {
6986
+ process.stderr.write(`[intercom] notifyParentExe: dispatcher ${target} dead, falling back to root exe ${rootExe}
6987
+ `);
6988
+ const fallback = sendIntercom(rootExe);
6989
+ return fallback !== "failed";
6990
+ }
6991
+ return false;
6992
+ }
6993
+ return true;
6554
6994
  }
6555
- async function findSimilarTrajectories(signature, threshold = DEFAULT_SKILL_THRESHOLD) {
6556
- const client = getClient();
6557
- const hash = hashSignature(signature);
6558
- const result = await client.execute({
6559
- sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
6560
- FROM trajectories
6561
- WHERE signature_hash = ?
6562
- ORDER BY created_at DESC
6563
- LIMIT 20`,
6564
- args: [hash]
6565
- });
6566
- const mapRow = (r) => ({
6567
- id: String(r.id),
6568
- taskId: String(r.task_id),
6569
- agentId: String(r.agent_id),
6570
- projectName: String(r.project_name),
6571
- taskTitle: String(r.task_title),
6572
- signature: JSON.parse(String(r.signature)),
6573
- signatureHash: String(r.signature_hash),
6574
- toolCount: Number(r.tool_count),
6575
- skillId: r.skill_id ? String(r.skill_id) : null,
6576
- createdAt: String(r.created_at)
6577
- });
6578
- const matches = result.rows.map(mapRow);
6579
- if (matches.length >= threshold) return matches;
6580
- const nearResult = await client.execute({
6581
- sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
6582
- FROM trajectories
6583
- WHERE tool_count BETWEEN ? AND ?
6584
- AND signature_hash != ?
6585
- ORDER BY created_at DESC
6586
- LIMIT 50`,
6587
- args: [
6588
- Math.max(1, signature.length - 3),
6589
- signature.length + 3,
6590
- hash
6591
- ]
6592
- });
6593
- for (const r of nearResult.rows) {
6594
- const candidateSig = JSON.parse(String(r.signature));
6595
- if (editDistance(signature, candidateSig) <= 2) {
6596
- matches.push(mapRow(r));
6995
+ function ensureEmployee(employeeName, exeSession, projectDir, opts) {
6996
+ if (employeeName === "exe") {
6997
+ return { status: "failed", sessionName: "", error: "exe is the COO, not a dispatchable employee" };
6998
+ }
6999
+ try {
7000
+ assertEmployeeLimitSync();
7001
+ } catch (err) {
7002
+ if (err instanceof PlanLimitError) {
7003
+ return { status: "failed", sessionName: "", error: err.message };
6597
7004
  }
6598
7005
  }
6599
- return matches;
6600
- }
6601
- async function captureTrajectory(opts) {
6602
- const signature = await extractTrajectory(opts.taskId, opts.agentId);
6603
- if (signature.length < 3) {
6604
- return { trajectoryId: "", similarCount: 0, similar: [] };
6605
- }
6606
- const trajectoryId = await storeTrajectory({
6607
- taskId: opts.taskId,
6608
- agentId: opts.agentId,
6609
- projectName: opts.projectName,
6610
- taskTitle: opts.taskTitle,
6611
- signature
6612
- });
6613
- const similar = await findSimilarTrajectories(
6614
- signature,
6615
- opts.skillThreshold ?? DEFAULT_SKILL_THRESHOLD
6616
- );
6617
- return { trajectoryId, similarCount: similar.length, similar };
6618
- }
6619
- function buildExtractionPrompt(trajectories) {
6620
- const items = trajectories.map((t, i) => {
6621
- const sig = t.signature.join(" \u2192 ");
6622
- return `Task ${i + 1}: "${t.taskTitle}" (${t.agentId}, ${t.projectName}) \u2014 ${t.toolCount} tool calls
6623
- Signature: ${sig}`;
6624
- }).join("\n\n");
6625
- return `You are analyzing ${trajectories.length} completed tasks that followed similar procedures:
6626
-
6627
- ${items}
6628
-
6629
- Extract the reusable procedure. Format your response EXACTLY like this:
6630
-
6631
- SKILL: {name \u2014 short, descriptive}
6632
- TRIGGER: {when to use this \u2014 one sentence}
6633
- STEPS:
6634
- 1. ...
6635
- 2. ...
6636
- PITFALLS: {common mistakes to avoid}
6637
-
6638
- Be specific and actionable. Include tool names, file patterns, and concrete commands where applicable.`;
6639
- }
6640
- async function extractSkill(trajectories, model) {
6641
- if (trajectories.length === 0) return null;
6642
- const config2 = await loadConfig();
6643
- const skillModel = model ?? config2.skillModel;
6644
- const Anthropic2 = (await import("@anthropic-ai/sdk")).default;
6645
- const client = new Anthropic2();
6646
- const prompt = buildExtractionPrompt(trajectories);
6647
- const response = await client.messages.create({
6648
- model: skillModel,
6649
- max_tokens: 500,
6650
- messages: [{ role: "user", content: prompt }]
6651
- });
6652
- const textBlock = response.content.find((b) => b.type === "text");
6653
- const skillText = textBlock?.text;
6654
- if (!skillText) return null;
6655
- const agentId = trajectories[0].agentId;
6656
- const projectName = trajectories[0].projectName;
6657
- const skillId = await storeBehavior({
6658
- agentId,
6659
- content: skillText,
6660
- domain: "skill",
6661
- projectName
6662
- });
6663
- const dbClient = getClient();
6664
- for (const t of trajectories) {
6665
- await dbClient.execute({
6666
- sql: "UPDATE trajectories SET skill_id = ? WHERE id = ?",
6667
- args: [skillId, t.id]
6668
- });
7006
+ if (/-exe\d*$/.test(employeeName)) {
7007
+ const bare = employeeName.replace(/-exe\d*$/, "").replace(/\d+$/, "");
7008
+ return {
7009
+ status: "failed",
7010
+ sessionName: "",
7011
+ error: `Error: pass employee name ('${bare}'), not session name ('${employeeName}')`
7012
+ };
6669
7013
  }
6670
- process.stderr.write(
6671
- `[skill-learning] Skill extracted from ${trajectories.length} trajectories \u2192 behavior ${skillId}
7014
+ if (!/^exe\d+$/.test(exeSession)) {
7015
+ const root = extractRootExe(exeSession);
7016
+ if (root) {
7017
+ process.stderr.write(
7018
+ `[ensureEmployee] WARN: caller passed exeSession="${exeSession}" (not a root exe). Auto-correcting to "${root}".
6672
7019
  `
6673
- );
6674
- return skillId;
7020
+ );
7021
+ exeSession = root;
7022
+ } else {
7023
+ return {
7024
+ status: "failed",
7025
+ sessionName: "",
7026
+ error: `Invalid exeSession "${exeSession}" \u2014 must be a root exe session (e.g., "exe1")`
7027
+ };
7028
+ }
7029
+ }
7030
+ let effectiveInstance = opts?.instance;
7031
+ if (effectiveInstance === void 0 && opts?.autoInstance) {
7032
+ const free = findFreeInstance(
7033
+ employeeName,
7034
+ exeSession,
7035
+ opts.maxAutoInstances ?? 10
7036
+ );
7037
+ if (free === null) {
7038
+ return {
7039
+ status: "failed",
7040
+ sessionName: employeeSessionName(employeeName, exeSession),
7041
+ error: `All ${opts.maxAutoInstances ?? 10} instances of ${employeeName} are alive \u2014 cap reached`
7042
+ };
7043
+ }
7044
+ effectiveInstance = free === 0 ? void 0 : free;
7045
+ }
7046
+ const sessionName = employeeSessionName(employeeName, exeSession, effectiveInstance);
7047
+ if (isEmployeeAlive(sessionName)) {
7048
+ const result2 = sendIntercom(sessionName);
7049
+ if (result2 === "acknowledged" || result2 === "skipped_exe" || result2 === "debounced" || result2 === "queued") {
7050
+ return { status: "intercom_sent", sessionName };
7051
+ }
7052
+ if (result2 === "delivered") {
7053
+ return { status: "intercom_unprocessed", sessionName };
7054
+ }
7055
+ return { status: "failed", sessionName, error: "intercom delivery failed" };
7056
+ }
7057
+ const spawnOpts = { ...opts, instance: effectiveInstance };
7058
+ const result = spawnEmployee(employeeName, exeSession, projectDir, spawnOpts);
7059
+ if (result.error) {
7060
+ return { status: "failed", sessionName, error: result.error };
7061
+ }
7062
+ return { status: "spawned", sessionName };
6675
7063
  }
6676
- async function captureAndLearn(opts) {
7064
+ function spawnEmployee(employeeName, exeSession, projectDir, opts) {
7065
+ const transport = getTransport();
7066
+ const sessionName = employeeSessionName(employeeName, exeSession, opts?.instance);
7067
+ const instanceLabel = opts?.instance != null && opts.instance > 0 ? `${employeeName}${opts.instance}` : employeeName;
7068
+ const logDir = path17.join(os7.homedir(), ".exe-os", "session-logs");
7069
+ const logFile = path17.join(logDir, `${instanceLabel}-${Date.now()}.log`);
7070
+ if (!existsSync13(logDir)) {
7071
+ mkdirSync7(logDir, { recursive: true });
7072
+ }
7073
+ transport.kill(sessionName);
7074
+ let cleanupSuffix = "";
6677
7075
  try {
6678
- const config2 = await loadConfig();
6679
- if (!config2.skillLearning) return;
6680
- const { trajectoryId, similarCount, similar } = await captureTrajectory({
6681
- ...opts,
6682
- skillThreshold: config2.skillThreshold
6683
- });
6684
- if (!trajectoryId) return;
6685
- if (similarCount >= config2.skillThreshold) {
6686
- const unprocessed = similar.filter((t) => !t.skillId);
6687
- if (unprocessed.length >= config2.skillThreshold) {
6688
- extractSkill(unprocessed, config2.skillModel).catch((err) => {
6689
- process.stderr.write(
6690
- `[skill-learning] Extraction failed: ${err instanceof Error ? err.message : String(err)}
7076
+ const thisFile = fileURLToPath2(import.meta.url);
7077
+ const cleanupScript = path17.join(path17.dirname(thisFile), "..", "bin", "exe-session-cleanup.js");
7078
+ if (existsSync13(cleanupScript)) {
7079
+ cleanupSuffix = `; ${process.execPath} "${cleanupScript}" "${employeeName}" "${exeSession}"`;
7080
+ }
7081
+ } catch {
7082
+ }
7083
+ try {
7084
+ const claudeJsonPath = path17.join(os7.homedir(), ".claude.json");
7085
+ let claudeJson = {};
7086
+ try {
7087
+ claudeJson = JSON.parse(readFileSync11(claudeJsonPath, "utf8"));
7088
+ } catch {
7089
+ }
7090
+ if (!claudeJson.projects) claudeJson.projects = {};
7091
+ const projects = claudeJson.projects;
7092
+ const trustDir = opts?.cwd ?? projectDir;
7093
+ if (!projects[trustDir]) projects[trustDir] = {};
7094
+ projects[trustDir].hasTrustDialogAccepted = true;
7095
+ writeFileSync5(claudeJsonPath, JSON.stringify(claudeJson, null, 2) + "\n");
7096
+ } catch {
7097
+ }
7098
+ try {
7099
+ const settingsDir = path17.join(os7.homedir(), ".claude", "projects");
7100
+ const normalizedKey = (opts?.cwd ?? projectDir).replace(/\//g, "-").replace(/^-/, "");
7101
+ const projSettingsDir = path17.join(settingsDir, normalizedKey);
7102
+ const settingsPath = path17.join(projSettingsDir, "settings.json");
7103
+ let settings = {};
7104
+ try {
7105
+ settings = JSON.parse(readFileSync11(settingsPath, "utf8"));
7106
+ } catch {
7107
+ }
7108
+ const perms = settings.permissions ?? {};
7109
+ const allow = perms.allow ?? [];
7110
+ const toolNames = [
7111
+ "recall_my_memory",
7112
+ "store_memory",
7113
+ "create_task",
7114
+ "update_task",
7115
+ "list_tasks",
7116
+ "get_task",
7117
+ "ask_team_memory",
7118
+ "store_behavior",
7119
+ "get_identity",
7120
+ "send_message"
7121
+ ];
7122
+ const requiredTools = expandDualPrefixTools(toolNames);
7123
+ let changed = false;
7124
+ for (const tool of requiredTools) {
7125
+ if (!allow.includes(tool)) {
7126
+ allow.push(tool);
7127
+ changed = true;
7128
+ }
7129
+ }
7130
+ if (changed) {
7131
+ perms.allow = allow;
7132
+ settings.permissions = perms;
7133
+ mkdirSync7(projSettingsDir, { recursive: true });
7134
+ writeFileSync5(settingsPath, JSON.stringify(settings, null, 2) + "\n");
7135
+ }
7136
+ } catch {
7137
+ }
7138
+ const spawnCwd = opts?.cwd ?? projectDir;
7139
+ const useExeAgent = !!(opts?.model && opts?.provider);
7140
+ const ccProvider = useExeAgent ? DEFAULT_PROVIDER : detectActiveProvider();
7141
+ const useBinSymlink = ccProvider !== DEFAULT_PROVIDER;
7142
+ let identityFlag = "";
7143
+ let behaviorsFlag = "";
7144
+ let legacyFallbackWarned = false;
7145
+ if (!useExeAgent && !useBinSymlink) {
7146
+ const identityPath = path17.join(
7147
+ os7.homedir(),
7148
+ ".exe-os",
7149
+ "identity",
7150
+ `${employeeName}.md`
7151
+ );
7152
+ _resetCcAgentSupportCache();
7153
+ const hasAgentFlag = claudeSupportsAgentFlag();
7154
+ if (hasAgentFlag) {
7155
+ identityFlag = ` --agent ${employeeName}`;
7156
+ } else if (existsSync13(identityPath)) {
7157
+ identityFlag = ` --append-system-prompt-file ${identityPath}`;
7158
+ legacyFallbackWarned = true;
7159
+ }
7160
+ const behaviorsFile = exportBehaviorsSync(
7161
+ employeeName,
7162
+ path17.basename(spawnCwd),
7163
+ sessionName
7164
+ );
7165
+ if (behaviorsFile) {
7166
+ behaviorsFlag = ` --append-system-prompt-file ${behaviorsFile}`;
7167
+ }
7168
+ }
7169
+ if (legacyFallbackWarned) {
7170
+ process.stderr.write(
7171
+ `[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.
6691
7172
  `
6692
- );
6693
- });
7173
+ );
7174
+ }
7175
+ let sessionContextFlag = "";
7176
+ try {
7177
+ const ctxDir = path17.join(os7.homedir(), ".exe-os", "session-cache");
7178
+ mkdirSync7(ctxDir, { recursive: true });
7179
+ const ctxFile = path17.join(ctxDir, `session-context-${sessionName}.md`);
7180
+ const ctxContent = [
7181
+ `## Session Context`,
7182
+ `You are running in tmux session: ${sessionName}.`,
7183
+ `Your parent exe session is ${exeSession}.`,
7184
+ `Your employees (if any) use the -${exeSession} suffix (e.g., tom-${exeSession}).`
7185
+ ].join("\n");
7186
+ writeFileSync5(ctxFile, ctxContent);
7187
+ sessionContextFlag = ` --append-system-prompt-file ${ctxFile}`;
7188
+ } catch {
7189
+ }
7190
+ let envPrefix = `EXE_SESSION=${exeSession} EXE_SESSION_NAME=${sessionName}`;
7191
+ if (ccProvider !== DEFAULT_PROVIDER) {
7192
+ const cfg = PROVIDER_TABLE[ccProvider];
7193
+ if (cfg?.apiKeyEnv) {
7194
+ const keyVal = process.env[cfg.apiKeyEnv];
7195
+ if (keyVal) {
7196
+ envPrefix = `${envPrefix} ${cfg.apiKeyEnv}=${keyVal}`;
6694
7197
  }
6695
7198
  }
6696
- } catch (err) {
7199
+ }
7200
+ let spawnCommand;
7201
+ if (useExeAgent) {
7202
+ spawnCommand = `${envPrefix} exe-agent --employee ${employeeName} --model ${opts.model} --provider ${opts.provider}${cleanupSuffix}`;
7203
+ } else if (useBinSymlink) {
7204
+ const binName = `${employeeName}-${ccProvider}`;
6697
7205
  process.stderr.write(
6698
- `[skill-learning] captureAndLearn failed: ${err instanceof Error ? err.message : String(err)}
7206
+ `[tmux-routing] provider cascade: ${ccProvider} \u2192 spawning ${binName}
6699
7207
  `
6700
7208
  );
7209
+ spawnCommand = `${envPrefix} ${binName}${cleanupSuffix}`;
7210
+ } else {
7211
+ spawnCommand = `${envPrefix} claude --dangerously-skip-permissions${identityFlag}${behaviorsFlag}${sessionContextFlag}${cleanupSuffix}`;
6701
7212
  }
6702
- }
6703
- async function sweepTrajectories(threshold, model) {
6704
- const config2 = await loadConfig();
6705
- if (!config2.skillLearning) return { clustersProcessed: 0, skillsExtracted: 0 };
6706
- const t = threshold ?? config2.skillThreshold;
6707
- const client = getClient();
6708
- const result = await client.execute({
6709
- sql: `SELECT signature_hash, COUNT(*) as cnt
6710
- FROM trajectories
6711
- WHERE skill_id IS NULL
6712
- GROUP BY signature_hash
6713
- HAVING cnt >= ?
6714
- ORDER BY cnt DESC
6715
- LIMIT 10`,
6716
- args: [t]
7213
+ const spawnResult = transport.spawn(sessionName, {
7214
+ cwd: spawnCwd,
7215
+ command: spawnCommand
6717
7216
  });
6718
- let clustersProcessed = 0;
6719
- let skillsExtracted = 0;
6720
- for (const row of result.rows) {
6721
- const hash = String(row.signature_hash);
6722
- const trajResult = await client.execute({
6723
- sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at
6724
- FROM trajectories
6725
- WHERE signature_hash = ? AND skill_id IS NULL
6726
- ORDER BY created_at DESC
6727
- LIMIT 10`,
6728
- args: [hash]
6729
- });
6730
- const trajectories = trajResult.rows.map((r) => ({
6731
- id: String(r.id),
6732
- taskId: String(r.task_id),
6733
- agentId: String(r.agent_id),
6734
- projectName: String(r.project_name),
6735
- taskTitle: String(r.task_title),
6736
- signature: JSON.parse(String(r.signature)),
6737
- signatureHash: String(r.signature_hash),
6738
- toolCount: Number(r.tool_count),
6739
- skillId: null,
6740
- createdAt: String(r.created_at)
7217
+ if (spawnResult.error) {
7218
+ releaseSpawnLock2(sessionName);
7219
+ return { sessionName, error: `tmux new-session failed: ${spawnResult.error}` };
7220
+ }
7221
+ transport.pipeLog(sessionName, logFile);
7222
+ try {
7223
+ const mySession = getMySession();
7224
+ const dispatchInfo = path17.join(SESSION_CACHE, `dispatch-info-${sessionName}.json`);
7225
+ writeFileSync5(dispatchInfo, JSON.stringify({
7226
+ dispatchedBy: mySession,
7227
+ rootExe: exeSession,
7228
+ provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
7229
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
6741
7230
  }));
6742
- if (trajectories.length >= t) {
6743
- clustersProcessed++;
6744
- const skillId = await extractSkill(trajectories, model ?? config2.skillModel);
6745
- if (skillId) skillsExtracted++;
7231
+ } catch {
7232
+ }
7233
+ let booted = false;
7234
+ for (let i = 0; i < 30; i++) {
7235
+ try {
7236
+ execSync6("sleep 0.5");
7237
+ } catch {
7238
+ }
7239
+ try {
7240
+ const pane = transport.capturePane(sessionName);
7241
+ if (useExeAgent) {
7242
+ if (pane.includes("[exe-agent]") || pane.includes("online")) {
7243
+ booted = true;
7244
+ break;
7245
+ }
7246
+ } else {
7247
+ if (pane.includes("Claude Code") || pane.includes("\u276F")) {
7248
+ booted = true;
7249
+ break;
7250
+ }
7251
+ }
7252
+ } catch {
6746
7253
  }
6747
7254
  }
6748
- return { clustersProcessed, skillsExtracted };
6749
- }
6750
- function editDistance(a, b) {
6751
- const m = a.length;
6752
- const n = b.length;
6753
- const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
6754
- for (let i = 0; i <= m; i++) dp[i][0] = i;
6755
- for (let j = 0; j <= n; j++) dp[0][j] = j;
6756
- for (let i = 1; i <= m; i++) {
6757
- for (let j = 1; j <= n; j++) {
6758
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
6759
- dp[i][j] = Math.min(
6760
- dp[i - 1][j] + 1,
6761
- dp[i][j - 1] + 1,
6762
- dp[i - 1][j - 1] + cost
6763
- );
7255
+ if (!booted) {
7256
+ releaseSpawnLock2(sessionName);
7257
+ return { sessionName, error: `${useExeAgent ? "exe-agent" : "claude"} did not boot within 15s` };
7258
+ }
7259
+ if (!useExeAgent) {
7260
+ try {
7261
+ transport.sendKeys(sessionName, `/exe-call ${employeeName}`);
7262
+ } catch {
6764
7263
  }
6765
7264
  }
6766
- return dp[m][n];
7265
+ registerSession({
7266
+ windowName: sessionName,
7267
+ agentId: employeeName,
7268
+ projectDir: spawnCwd,
7269
+ parentExe: exeSession,
7270
+ pid: 0,
7271
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString()
7272
+ });
7273
+ releaseSpawnLock2(sessionName);
7274
+ return { sessionName };
6767
7275
  }
6768
- var DEFAULT_SKILL_THRESHOLD;
6769
- var init_skill_learning = __esm({
6770
- "src/lib/skill-learning.ts"() {
7276
+ 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;
7277
+ var init_tmux_routing = __esm({
7278
+ "src/lib/tmux-routing.ts"() {
6771
7279
  "use strict";
6772
- init_database();
6773
- init_behaviors();
6774
- init_config();
6775
- DEFAULT_SKILL_THRESHOLD = 3;
7280
+ init_session_registry();
7281
+ init_session_key();
7282
+ init_transport();
7283
+ init_cc_agent_support();
7284
+ init_mcp_prefix();
7285
+ init_provider_table();
7286
+ init_intercom_queue();
7287
+ init_plan_limits();
7288
+ SPAWN_LOCK_DIR = path17.join(os7.homedir(), ".exe-os", "spawn-locks");
7289
+ SESSION_CACHE = path17.join(os7.homedir(), ".exe-os", "session-cache");
7290
+ BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
7291
+ VALID_SESSION_NAME = /^[a-z]+-exe\d+$|^[a-z]+\d+-exe\d+$/;
7292
+ VERIFY_PANE_LINES = 200;
7293
+ INTERCOM_DEBOUNCE_MS = 3e4;
7294
+ INTERCOM_LOG2 = path17.join(os7.homedir(), ".exe-os", "intercom.log");
7295
+ DEBOUNCE_FILE = path17.join(SESSION_CACHE, "intercom-debounce.json");
7296
+ DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
7297
+ BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
6776
7298
  }
6777
7299
  });
6778
7300
 
6779
- // src/lib/tasks.ts
6780
- var tasks_exports = {};
6781
- __export(tasks_exports, {
6782
- cleanupOrphanedReviews: () => cleanupOrphanedReviews,
6783
- countNewPendingReviewsSince: () => countNewPendingReviewsSince,
6784
- countPendingReviews: () => countPendingReviews,
6785
- createTask: () => createTask,
6786
- createTaskCore: () => createTaskCore,
6787
- deleteTask: () => deleteTask,
6788
- deleteTaskCore: () => deleteTaskCore,
6789
- ensureArchitectureDoc: () => ensureArchitectureDoc,
6790
- ensureGitignoreExe: () => ensureGitignoreExe,
6791
- getReviewChecklist: () => getReviewChecklist,
6792
- listPendingReviews: () => listPendingReviews,
6793
- listTasks: () => listTasks,
6794
- resolveTask: () => resolveTask,
6795
- slugify: () => slugify,
6796
- updateTask: () => updateTask,
6797
- updateTaskStatus: () => updateTaskStatus,
6798
- writeCheckpoint: () => writeCheckpoint
7301
+ // src/lib/messaging.ts
7302
+ var messaging_exports = {};
7303
+ __export(messaging_exports, {
7304
+ deliverLocalMessage: () => deliverLocalMessage,
7305
+ getFailedMessages: () => getFailedMessages,
7306
+ getMessageStatus: () => getMessageStatus,
7307
+ getPendingMessages: () => getPendingMessages,
7308
+ getReadMessages: () => getReadMessages,
7309
+ getUnacknowledgedMessages: () => getUnacknowledgedMessages,
7310
+ markAcknowledged: () => markAcknowledged,
7311
+ markFailed: () => markFailed,
7312
+ markProcessed: () => markProcessed,
7313
+ markRead: () => markRead,
7314
+ retryPendingMessages: () => retryPendingMessages,
7315
+ sendMessage: () => sendMessage,
7316
+ setWsClientSend: () => setWsClientSend
6799
7317
  });
6800
- import path17 from "path";
6801
- import { writeFileSync as writeFileSync5, mkdirSync as mkdirSync7, unlinkSync as unlinkSync5 } from "fs";
6802
- async function createTask(input) {
6803
- const result = await createTaskCore(input);
6804
- if (!input.skipDispatch && result.status !== "blocked" && !process.env.VITEST) {
6805
- dispatchTaskToEmployee({
6806
- assignedTo: input.assignedTo,
6807
- title: input.title,
6808
- priority: input.priority,
6809
- taskFile: result.taskFile,
6810
- initialStatus: result.status,
6811
- projectName: input.projectName
7318
+ import crypto8 from "crypto";
7319
+ function generateUlid() {
7320
+ const timestamp = Date.now().toString(36).padStart(10, "0");
7321
+ const random = crypto8.randomBytes(10).toString("hex").slice(0, 16);
7322
+ return (timestamp + random).toUpperCase();
7323
+ }
7324
+ function rowToMessage(row) {
7325
+ return {
7326
+ id: row.id,
7327
+ fromAgent: row.from_agent,
7328
+ fromDevice: row.from_device,
7329
+ targetAgent: row.target_agent,
7330
+ targetProject: row.target_project ?? null,
7331
+ targetDevice: row.target_device,
7332
+ content: row.content,
7333
+ priority: row.priority ?? "normal",
7334
+ status: row.status ?? "pending",
7335
+ serverSeq: row.server_seq != null ? Number(row.server_seq) : null,
7336
+ retryCount: Number(row.retry_count ?? 0),
7337
+ createdAt: row.created_at,
7338
+ deliveredAt: row.delivered_at ?? null,
7339
+ processedAt: row.processed_at ?? null,
7340
+ failedAt: row.failed_at ?? null,
7341
+ failureReason: row.failure_reason ?? null
7342
+ };
7343
+ }
7344
+ async function sendMessage(input) {
7345
+ const client = getClient();
7346
+ const id = generateUlid();
7347
+ const now = (/* @__PURE__ */ new Date()).toISOString();
7348
+ const targetDevice = input.targetDevice ?? "local";
7349
+ await client.execute({
7350
+ sql: `INSERT INTO messages (id, from_agent, from_device, target_agent, target_project, target_device, content, priority, status, created_at)
7351
+ VALUES (?, ?, 'local', ?, ?, ?, ?, ?, 'pending', ?)`,
7352
+ args: [
7353
+ id,
7354
+ input.fromAgent,
7355
+ input.targetAgent,
7356
+ input.targetProject ?? null,
7357
+ targetDevice,
7358
+ input.content,
7359
+ input.priority ?? "normal",
7360
+ now
7361
+ ]
7362
+ });
7363
+ try {
7364
+ if (targetDevice !== "local") {
7365
+ await deliverCrossMachineMessage(id, targetDevice);
7366
+ } else {
7367
+ await deliverLocalMessage(id);
7368
+ }
7369
+ } catch {
7370
+ }
7371
+ const result = await client.execute({
7372
+ sql: "SELECT * FROM messages WHERE id = ?",
7373
+ args: [id]
7374
+ });
7375
+ return rowToMessage(result.rows[0]);
7376
+ }
7377
+ function setWsClientSend(fn) {
7378
+ _wsClientSend = fn;
7379
+ }
7380
+ async function deliverCrossMachineMessage(messageId, targetDevice) {
7381
+ const client = getClient();
7382
+ const result = await client.execute({
7383
+ sql: "SELECT * FROM messages WHERE id = ?",
7384
+ args: [messageId]
7385
+ });
7386
+ if (result.rows.length === 0) return false;
7387
+ const msg = rowToMessage(result.rows[0]);
7388
+ if (msg.status !== "pending") return false;
7389
+ if (!_wsClientSend) {
7390
+ return false;
7391
+ }
7392
+ const payload = JSON.stringify({
7393
+ id: msg.id,
7394
+ fromAgent: msg.fromAgent,
7395
+ targetAgent: msg.targetAgent,
7396
+ targetProject: msg.targetProject,
7397
+ content: msg.content,
7398
+ priority: msg.priority,
7399
+ createdAt: msg.createdAt
7400
+ });
7401
+ const sent = _wsClientSend(targetDevice, payload);
7402
+ if (sent) {
7403
+ await client.execute({
7404
+ sql: "UPDATE messages SET status = 'synced' WHERE id = ?",
7405
+ args: [messageId]
6812
7406
  });
7407
+ return true;
6813
7408
  }
6814
- return result;
7409
+ return false;
6815
7410
  }
6816
- async function updateTask(input) {
6817
- const { row, taskFile, now, taskId } = await updateTaskStatus(input);
7411
+ async function deliverLocalMessage(messageId) {
7412
+ const client = getClient();
7413
+ const result = await client.execute({
7414
+ sql: "SELECT * FROM messages WHERE id = ?",
7415
+ args: [messageId]
7416
+ });
7417
+ if (result.rows.length === 0) return false;
7418
+ const msg = rowToMessage(result.rows[0]);
7419
+ if (msg.status !== "pending") return false;
7420
+ const targetAgent = msg.targetAgent;
7421
+ const now = (/* @__PURE__ */ new Date()).toISOString();
6818
7422
  try {
6819
- const agent = String(row.assigned_to);
6820
- const cacheDir = path17.join(EXE_AI_DIR, "session-cache");
6821
- const cachePath = path17.join(cacheDir, `current-task-${agent}.json`);
6822
- if (input.status === "in_progress") {
6823
- mkdirSync7(cacheDir, { recursive: true });
6824
- writeFileSync5(cachePath, JSON.stringify({ taskId, title: String(row.title) }));
6825
- } else if (input.status === "done" || input.status === "blocked" || input.status === "cancelled") {
6826
- try {
6827
- unlinkSync5(cachePath);
6828
- } catch {
6829
- }
7423
+ const exeSession = resolveExeSession();
7424
+ if (!exeSession) {
7425
+ throw new Error("No exe session found");
7426
+ }
7427
+ const ensureResult = ensureEmployee(targetAgent, exeSession, process.cwd());
7428
+ if (ensureResult.status === "failed") {
7429
+ throw new Error(ensureResult.error ?? "ensureEmployee failed");
6830
7430
  }
7431
+ await client.execute({
7432
+ sql: "UPDATE messages SET status = 'delivered', delivered_at = ? WHERE id = ?",
7433
+ args: [now, messageId]
7434
+ });
7435
+ return true;
6831
7436
  } catch {
6832
- }
6833
- if (input.status === "done") {
6834
- await cleanupReviewFile(row, taskFile, input.baseDir);
6835
- }
6836
- if (input.status === "done" || input.status === "cancelled") {
6837
- try {
6838
- const client = getClient();
6839
- const taskTitle = String(row.title);
6840
- const escaped = taskTitle.replace(/%/g, "\\%").replace(/_/g, "\\_");
7437
+ const newRetryCount = msg.retryCount + 1;
7438
+ if (newRetryCount >= MAX_RETRIES2) {
7439
+ await markFailed(messageId, "session unavailable after 10 retries");
7440
+ } else {
6841
7441
  await client.execute({
6842
- sql: `UPDATE tasks SET status = 'cancelled', updated_at = ?
6843
- WHERE title LIKE ? ESCAPE '\\' AND status IN ('open', 'in_progress')`,
6844
- args: [now, `%left '${escaped}' as in\\_progress%`]
6845
- });
6846
- } catch {
6847
- }
6848
- try {
6849
- const client = getClient();
6850
- const cascaded = await client.execute({
6851
- sql: `UPDATE tasks SET status = 'done', updated_at = ?
6852
- WHERE parent_task_id = ? AND status = 'needs_review'`,
6853
- args: [now, taskId]
7442
+ sql: "UPDATE messages SET retry_count = ? WHERE id = ?",
7443
+ args: [newRetryCount, messageId]
6854
7444
  });
6855
- if (cascaded.rowsAffected > 0) {
6856
- process.stderr.write(
6857
- `[cascade] Closed ${cascaded.rowsAffected} orphaned review task(s) for parent ${taskId}
6858
- `
6859
- );
6860
- }
6861
- } catch {
6862
- }
6863
- }
6864
- const isTerminal = input.status === "done" || input.status === "needs_review";
6865
- if (isTerminal) {
6866
- const isExe = String(row.assigned_to) === "exe";
6867
- if (!isExe) {
6868
- notifyTaskDone();
6869
- }
6870
- await markTaskNotificationsRead(taskFile);
6871
- if (input.status === "done") {
6872
- try {
6873
- await cascadeUnblock(taskId, input.baseDir, now);
6874
- } catch {
6875
- }
6876
- if (row.parent_task_id) {
6877
- try {
6878
- await checkSubtaskCompletion(String(row.parent_task_id), String(row.project_name));
6879
- } catch {
6880
- }
6881
- }
6882
- }
6883
- }
6884
- if (input.status === "done" && String(row.assigned_to) !== "exe" && !process.env.VITEST) {
6885
- Promise.resolve().then(() => (init_skill_learning(), skill_learning_exports)).then(
6886
- ({ captureAndLearn: captureAndLearn2 }) => captureAndLearn2({
6887
- taskId,
6888
- agentId: String(row.assigned_to),
6889
- projectName: String(row.project_name),
6890
- taskTitle: String(row.title)
6891
- })
6892
- ).catch((err) => {
6893
- process.stderr.write(
6894
- `[updateTask] skill learning failed: ${err instanceof Error ? err.message : String(err)}
6895
- `
6896
- );
6897
- });
6898
- }
6899
- let nextTask;
6900
- if (isTerminal && String(row.assigned_to) !== "exe") {
6901
- try {
6902
- nextTask = await findNextTask(String(row.assigned_to));
6903
- } catch {
6904
7445
  }
7446
+ return false;
6905
7447
  }
6906
- return {
6907
- id: String(row.id),
6908
- title: String(row.title),
6909
- assignedTo: String(row.assigned_to),
6910
- assignedBy: String(row.assigned_by),
6911
- projectName: String(row.project_name),
6912
- priority: String(row.priority),
6913
- status: input.status,
6914
- taskFile,
6915
- createdAt: String(row.created_at),
6916
- updatedAt: now,
6917
- budgetTokens: row.budget_tokens !== void 0 && row.budget_tokens !== null ? Number(row.budget_tokens) : null,
6918
- budgetFallbackModel: row.budget_fallback_model !== void 0 && row.budget_fallback_model !== null ? String(row.budget_fallback_model) : null,
6919
- tokensUsed: Number(row.tokens_used ?? 0),
6920
- tokensWarnedAt: row.tokens_warned_at !== void 0 && row.tokens_warned_at !== null ? Number(row.tokens_warned_at) : null,
6921
- nextTask
6922
- };
6923
7448
  }
6924
- async function deleteTask(taskId, baseDir) {
7449
+ async function getPendingMessages(targetAgent) {
7450
+ const client = getClient();
7451
+ const result = await client.execute({
7452
+ sql: `SELECT * FROM messages
7453
+ WHERE target_agent = ? AND status IN ('pending', 'delivered')
7454
+ ORDER BY id`,
7455
+ args: [targetAgent]
7456
+ });
7457
+ return result.rows.map((row) => rowToMessage(row));
7458
+ }
7459
+ async function markRead(messageId) {
6925
7460
  const client = getClient();
6926
- const { taskFile, assignedTo, assignedBy, taskSlug } = await deleteTaskCore(taskId, baseDir);
6927
- const reviewer = assignedBy || "exe";
6928
- const reviewSlug = `review-${assignedTo}-${taskSlug}`;
6929
- const reviewFile = `exe/${reviewer}/${reviewSlug}.md`;
6930
7461
  await client.execute({
6931
- sql: "DELETE FROM tasks WHERE task_file = ? OR task_file = ?",
6932
- args: [reviewFile, `exe/exe/${reviewSlug}.md`]
7462
+ sql: "UPDATE messages SET status = 'read' WHERE id = ? AND status IN ('pending', 'delivered')",
7463
+ args: [messageId]
6933
7464
  });
6934
- await markAsReadByTaskFile(taskFile);
6935
- await markAsReadByTaskFile(reviewFile);
6936
7465
  }
6937
- var init_tasks = __esm({
6938
- "src/lib/tasks.ts"() {
7466
+ async function markAcknowledged(messageId) {
7467
+ const client = getClient();
7468
+ await client.execute({
7469
+ sql: "UPDATE messages SET status = 'acknowledged', processed_at = ? WHERE id = ? AND status = 'read'",
7470
+ args: [(/* @__PURE__ */ new Date()).toISOString(), messageId]
7471
+ });
7472
+ }
7473
+ async function markProcessed(messageId) {
7474
+ const client = getClient();
7475
+ await client.execute({
7476
+ sql: "UPDATE messages SET status = 'processed', processed_at = ? WHERE id = ?",
7477
+ args: [(/* @__PURE__ */ new Date()).toISOString(), messageId]
7478
+ });
7479
+ }
7480
+ async function getMessageStatus(messageId) {
7481
+ const client = getClient();
7482
+ const result = await client.execute({
7483
+ sql: "SELECT status FROM messages WHERE id = ?",
7484
+ args: [messageId]
7485
+ });
7486
+ return result.rows[0]?.status ?? null;
7487
+ }
7488
+ async function getUnacknowledgedMessages(targetAgent) {
7489
+ const client = getClient();
7490
+ const result = await client.execute({
7491
+ sql: `SELECT * FROM messages
7492
+ WHERE target_agent = ? AND status IN ('pending', 'delivered', 'read')
7493
+ ORDER BY id`,
7494
+ args: [targetAgent]
7495
+ });
7496
+ return result.rows.map((row) => rowToMessage(row));
7497
+ }
7498
+ async function getReadMessages(targetAgent) {
7499
+ const client = getClient();
7500
+ const result = await client.execute({
7501
+ sql: "SELECT * FROM messages WHERE target_agent = ? AND status = 'read' ORDER BY id",
7502
+ args: [targetAgent]
7503
+ });
7504
+ return result.rows.map((row) => rowToMessage(row));
7505
+ }
7506
+ async function markFailed(messageId, reason) {
7507
+ const client = getClient();
7508
+ await client.execute({
7509
+ sql: "UPDATE messages SET status = 'failed', failed_at = ?, failure_reason = ? WHERE id = ?",
7510
+ args: [(/* @__PURE__ */ new Date()).toISOString(), reason, messageId]
7511
+ });
7512
+ }
7513
+ async function getFailedMessages() {
7514
+ const client = getClient();
7515
+ const result = await client.execute({
7516
+ sql: "SELECT * FROM messages WHERE status = 'failed' ORDER BY created_at DESC",
7517
+ args: []
7518
+ });
7519
+ return result.rows.map((row) => rowToMessage(row));
7520
+ }
7521
+ async function retryPendingMessages() {
7522
+ const client = getClient();
7523
+ const result = await client.execute({
7524
+ sql: `SELECT * FROM messages
7525
+ WHERE status = 'pending' AND retry_count < ?
7526
+ ORDER BY id`,
7527
+ args: [MAX_RETRIES2]
7528
+ });
7529
+ let delivered = 0;
7530
+ for (const row of result.rows) {
7531
+ const msg = rowToMessage(row);
7532
+ try {
7533
+ const success = await deliverLocalMessage(msg.id);
7534
+ if (success) delivered++;
7535
+ } catch {
7536
+ }
7537
+ }
7538
+ return delivered;
7539
+ }
7540
+ var MAX_RETRIES2, _wsClientSend;
7541
+ var init_messaging = __esm({
7542
+ "src/lib/messaging.ts"() {
6939
7543
  "use strict";
6940
7544
  init_database();
6941
- init_config();
6942
- init_notifications();
6943
- init_tasks_crud();
6944
- init_tasks_review();
6945
- init_tasks_crud();
6946
- init_tasks_chain();
6947
- init_tasks_review();
6948
- init_tasks_notify();
7545
+ init_tmux_routing();
7546
+ MAX_RETRIES2 = 10;
7547
+ _wsClientSend = null;
6949
7548
  }
6950
7549
  });
6951
7550
 
6952
7551
  // src/automation/trigger-engine.ts
6953
7552
  import { readFileSync as readFileSync12, writeFileSync as writeFileSync6, existsSync as existsSync14, mkdirSync as mkdirSync8 } from "fs";
6954
- import { randomUUID as randomUUID7 } from "crypto";
7553
+ import { randomUUID as randomUUID8 } from "crypto";
6955
7554
  import path18 from "path";
6956
7555
  import os8 from "os";
6957
7556
  function substituteTemplate(template, record) {
@@ -7496,6 +8095,9 @@ function sendJson(res, status, data) {
7496
8095
  res.end(JSON.stringify(data));
7497
8096
  }
7498
8097
 
8098
+ // src/gateway/gateway.ts
8099
+ init_state_bus();
8100
+
7499
8101
  // src/gateway/router.ts
7500
8102
  function matchesPlatform(msgPlatform, matchPlatform) {
7501
8103
  if (!matchPlatform) return true;
@@ -7794,6 +8396,13 @@ var Gateway = class {
7794
8396
  console.log(
7795
8397
  `[gateway] ${msg.platform}/${msg.senderId} \u2192 ${route.employee} (${route.routeName})`
7796
8398
  );
8399
+ orgBus.emit({
8400
+ type: "gateway_message",
8401
+ platform: msg.platform,
8402
+ senderId: msg.senderId,
8403
+ botId: route.employee,
8404
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
8405
+ });
7797
8406
  const bot = this.botRegistry.get(route.employee);
7798
8407
  if (!bot) {
7799
8408
  console.error(`[gateway] No bot registered for target: ${route.employee}`);