@askexenow/exe-os 0.8.41 → 0.8.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/bin/backfill-conversations.js +805 -642
  2. package/dist/bin/backfill-responses.js +804 -641
  3. package/dist/bin/backfill-vectors.js +791 -634
  4. package/dist/bin/cleanup-stale-review-tasks.js +788 -631
  5. package/dist/bin/cli.js +1345 -660
  6. package/dist/bin/exe-agent.js +20 -1
  7. package/dist/bin/exe-assign.js +1503 -1343
  8. package/dist/bin/exe-boot.js +2518 -1798
  9. package/dist/bin/exe-call.js +39 -1
  10. package/dist/bin/exe-cloud.js +15 -1
  11. package/dist/bin/exe-dispatch.js +39 -2
  12. package/dist/bin/exe-doctor.js +790 -633
  13. package/dist/bin/exe-export-behaviors.js +792 -637
  14. package/dist/bin/exe-forget.js +145 -0
  15. package/dist/bin/exe-gateway.js +2500 -1877
  16. package/dist/bin/exe-heartbeat.js +147 -1
  17. package/dist/bin/exe-kill.js +795 -640
  18. package/dist/bin/exe-launch-agent.js +2168 -2008
  19. package/dist/bin/exe-link.js +28 -2
  20. package/dist/bin/exe-new-employee.js +25 -3
  21. package/dist/bin/exe-pending-messages.js +146 -1
  22. package/dist/bin/exe-pending-notifications.js +788 -631
  23. package/dist/bin/exe-pending-reviews.js +147 -1
  24. package/dist/bin/exe-rename.js +23 -0
  25. package/dist/bin/exe-review.js +490 -327
  26. package/dist/bin/exe-search.js +154 -3
  27. package/dist/bin/exe-session-cleanup.js +2466 -413
  28. package/dist/bin/exe-status.js +474 -317
  29. package/dist/bin/exe-team.js +474 -317
  30. package/dist/bin/git-sweep.js +2690 -150
  31. package/dist/bin/graph-backfill.js +794 -637
  32. package/dist/bin/graph-export.js +798 -641
  33. package/dist/bin/scan-tasks.js +2951 -44
  34. package/dist/bin/setup.js +62 -26
  35. package/dist/bin/shard-migrate.js +792 -637
  36. package/dist/bin/wiki-sync.js +794 -637
  37. package/dist/gateway/index.js +2504 -1895
  38. package/dist/hooks/bug-report-worker.js +2118 -576
  39. package/dist/hooks/commit-complete.js +2689 -149
  40. package/dist/hooks/error-recall.js +154 -3
  41. package/dist/hooks/ingest-worker.js +1439 -815
  42. package/dist/hooks/instructions-loaded.js +151 -0
  43. package/dist/hooks/notification.js +153 -2
  44. package/dist/hooks/post-compact.js +164 -0
  45. package/dist/hooks/pre-compact.js +3073 -101
  46. package/dist/hooks/pre-tool-use.js +151 -0
  47. package/dist/hooks/prompt-ingest-worker.js +1714 -1537
  48. package/dist/hooks/prompt-submit.js +2658 -1113
  49. package/dist/hooks/response-ingest-worker.js +170 -6
  50. package/dist/hooks/session-end.js +153 -2
  51. package/dist/hooks/session-start.js +154 -3
  52. package/dist/hooks/stop.js +151 -0
  53. package/dist/hooks/subagent-stop.js +151 -0
  54. package/dist/hooks/summary-worker.js +179 -7
  55. package/dist/index.js +278 -100
  56. package/dist/lib/cloud-sync.js +28 -2
  57. package/dist/lib/consolidation.js +69 -2
  58. package/dist/lib/database.js +19 -0
  59. package/dist/lib/device-registry.js +19 -0
  60. package/dist/lib/employee-templates.js +20 -1
  61. package/dist/lib/exe-daemon.js +236 -16
  62. package/dist/lib/hybrid-search.js +154 -3
  63. package/dist/lib/license.js +15 -1
  64. package/dist/lib/messaging.js +39 -2
  65. package/dist/lib/schedules.js +792 -637
  66. package/dist/lib/store.js +796 -636
  67. package/dist/lib/tasks.js +1614 -1091
  68. package/dist/lib/tmux-routing.js +149 -9
  69. package/dist/mcp/server.js +1825 -1138
  70. package/dist/mcp/tools/create-task.js +2280 -828
  71. package/dist/mcp/tools/list-tasks.js +2788 -159
  72. package/dist/mcp/tools/send-message.js +39 -2
  73. package/dist/mcp/tools/update-task.js +64 -0
  74. package/dist/runtime/index.js +235 -67
  75. package/dist/tui/App.js +1452 -644
  76. package/package.json +3 -2
@@ -1,7 +1,23 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1
3
  var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
2
5
  var __esm = (fn, res) => function __init() {
3
6
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
4
7
  };
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
5
21
 
6
22
  // src/lib/db-retry.ts
7
23
  var init_db_retry = __esm({
@@ -48,7 +64,89 @@ function resolveDataDir() {
48
64
  }
49
65
  return newDir;
50
66
  }
51
- var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG;
67
+ function migrateLegacyConfig(raw) {
68
+ if ("r2" in raw) {
69
+ process.stderr.write(
70
+ "[exe-os] Warning: config.json contains deprecated 'r2' field from v1.0. R2 sync has been replaced in v1.1. The 'r2' field will be ignored.\n"
71
+ );
72
+ delete raw.r2;
73
+ }
74
+ if ("syncIntervalMs" in raw) {
75
+ delete raw.syncIntervalMs;
76
+ }
77
+ return raw;
78
+ }
79
+ function migrateConfig(raw) {
80
+ const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
81
+ let currentVersion = fromVersion;
82
+ let migrated = false;
83
+ if (currentVersion > CURRENT_CONFIG_VERSION) {
84
+ return { config: raw, migrated: false, fromVersion };
85
+ }
86
+ for (const migration of CONFIG_MIGRATIONS) {
87
+ if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
88
+ raw = migration.migrate(raw);
89
+ currentVersion = migration.to;
90
+ migrated = true;
91
+ }
92
+ }
93
+ return { config: raw, migrated, fromVersion };
94
+ }
95
+ function normalizeScalingRoadmap(raw) {
96
+ const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
97
+ const userRoadmap = raw.scalingRoadmap ?? {};
98
+ const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
99
+ if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
100
+ userAuto.enabled = raw.rerankerEnabled;
101
+ }
102
+ raw.scalingRoadmap = {
103
+ ...userRoadmap,
104
+ rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
105
+ };
106
+ }
107
+ function normalizeSessionLifecycle(raw) {
108
+ const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
109
+ const userSL = raw.sessionLifecycle ?? {};
110
+ raw.sessionLifecycle = { ...defaultSL, ...userSL };
111
+ }
112
+ function normalizeAutoUpdate(raw) {
113
+ const defaultAU = DEFAULT_CONFIG.autoUpdate;
114
+ const userAU = raw.autoUpdate ?? {};
115
+ raw.autoUpdate = { ...defaultAU, ...userAU };
116
+ }
117
+ async function loadConfig() {
118
+ const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
119
+ await mkdir(dir, { recursive: true });
120
+ const configPath = path.join(dir, "config.json");
121
+ if (!existsSync(configPath)) {
122
+ return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
123
+ }
124
+ const raw = await readFile(configPath, "utf-8");
125
+ try {
126
+ let parsed = JSON.parse(raw);
127
+ parsed = migrateLegacyConfig(parsed);
128
+ const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
129
+ if (migrated) {
130
+ process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
131
+ `);
132
+ try {
133
+ await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
134
+ } catch {
135
+ }
136
+ }
137
+ normalizeScalingRoadmap(migratedCfg);
138
+ normalizeSessionLifecycle(migratedCfg);
139
+ normalizeAutoUpdate(migratedCfg);
140
+ const config = { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
141
+ if (config.dbPath.startsWith("~")) {
142
+ config.dbPath = config.dbPath.replace(/^~/, os.homedir());
143
+ }
144
+ return config;
145
+ } catch {
146
+ return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
147
+ }
148
+ }
149
+ var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
52
150
  var init_config = __esm({
53
151
  "src/lib/config.ts"() {
54
152
  "use strict";
@@ -121,6 +219,16 @@ var init_config = __esm({
121
219
  checkIntervalMs: 24 * 60 * 60 * 1e3
122
220
  }
123
221
  };
222
+ CONFIG_MIGRATIONS = [
223
+ {
224
+ from: 0,
225
+ to: 1,
226
+ migrate: (cfg) => {
227
+ cfg.config_version = 1;
228
+ return cfg;
229
+ }
230
+ }
231
+ ];
124
232
  }
125
233
  });
126
234
 
@@ -135,120 +243,314 @@ import {
135
243
  existsSync as existsSync2,
136
244
  rmdirSync
137
245
  } from "fs";
138
- var init_notifications = __esm({
139
- "src/lib/notifications.ts"() {
140
- "use strict";
141
- init_database();
142
- }
143
- });
144
-
145
- // src/lib/tasks-crud.ts
146
- import crypto2 from "crypto";
147
- import path3 from "path";
148
- import { execSync } from "child_process";
149
- import { mkdir as mkdir2, writeFile as writeFile2, appendFile } from "fs/promises";
150
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
151
- async function listTasks(input) {
152
- const client = getClient();
153
- const conditions = [];
154
- const args = [];
155
- if (input.assignedTo) {
156
- conditions.push("assigned_to = ?");
157
- args.push(input.assignedTo);
158
- }
159
- if (input.status) {
160
- conditions.push("status = ?");
161
- args.push(input.status);
162
- } else {
163
- conditions.push("status IN ('open', 'in_progress', 'blocked')");
164
- }
165
- if (input.projectName) {
166
- conditions.push("project_name = ?");
167
- args.push(input.projectName);
246
+ async function writeNotification(notification) {
247
+ try {
248
+ const client = getClient();
249
+ const id = crypto.randomUUID();
250
+ const now = (/* @__PURE__ */ new Date()).toISOString();
251
+ await client.execute({
252
+ sql: `INSERT INTO notifications (id, agent_id, agent_role, event, project, summary, task_file, read, created_at)
253
+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)`,
254
+ args: [
255
+ id,
256
+ notification.agentId,
257
+ notification.agentRole,
258
+ notification.event,
259
+ notification.project,
260
+ notification.summary,
261
+ notification.taskFile ?? null,
262
+ now
263
+ ]
264
+ });
265
+ } catch (err) {
266
+ process.stderr.write(`[notifications] WRITE FAILED: ${err instanceof Error ? err.message : String(err)}
267
+ `);
168
268
  }
169
- if (input.priority) {
170
- conditions.push("priority = ?");
171
- args.push(input.priority);
269
+ }
270
+ async function markAsReadByTaskFile(taskFile) {
271
+ try {
272
+ const client = getClient();
273
+ await client.execute({
274
+ sql: "UPDATE notifications SET read = 1 WHERE task_file = ? AND read = 0",
275
+ args: [taskFile]
276
+ });
277
+ } catch {
172
278
  }
173
- const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
174
- const result = await client.execute({
175
- 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`,
176
- args
177
- });
178
- return result.rows.map((r) => ({
179
- id: String(r.id),
180
- title: String(r.title),
181
- assignedTo: String(r.assigned_to),
182
- assignedBy: String(r.assigned_by),
183
- projectName: String(r.project_name),
184
- priority: String(r.priority),
185
- status: String(r.status),
186
- taskFile: String(r.task_file),
187
- createdAt: String(r.created_at),
188
- updatedAt: String(r.updated_at),
189
- checkpointCount: Number(r.checkpoint_count ?? 0),
190
- budgetTokens: r.budget_tokens !== null ? Number(r.budget_tokens) : null,
191
- budgetFallbackModel: r.budget_fallback_model !== null ? String(r.budget_fallback_model) : null,
192
- tokensUsed: Number(r.tokens_used ?? 0),
193
- tokensWarnedAt: r.tokens_warned_at !== null ? Number(r.tokens_warned_at) : null
194
- }));
195
279
  }
196
- var init_tasks_crud = __esm({
197
- "src/lib/tasks-crud.ts"() {
280
+ var init_notifications = __esm({
281
+ "src/lib/notifications.ts"() {
198
282
  "use strict";
199
283
  init_database();
200
284
  }
201
285
  });
202
286
 
203
- // src/lib/employees.ts
204
- import { readFile as readFile2, writeFile as writeFile3, mkdir as mkdir3 } from "fs/promises";
205
- import { existsSync as existsSync4, symlinkSync, readlinkSync, readFileSync as readFileSync4 } from "fs";
206
- import { execSync as execSync2 } from "child_process";
207
- import path4 from "path";
208
- var EMPLOYEES_PATH;
209
- var init_employees = __esm({
210
- "src/lib/employees.ts"() {
287
+ // src/lib/state-bus.ts
288
+ var StateBus, orgBus;
289
+ var init_state_bus = __esm({
290
+ "src/lib/state-bus.ts"() {
211
291
  "use strict";
212
- init_config();
213
- EMPLOYEES_PATH = path4.join(EXE_AI_DIR, "exe-employees.json");
292
+ StateBus = class {
293
+ handlers = /* @__PURE__ */ new Map();
294
+ globalHandlers = /* @__PURE__ */ new Set();
295
+ /** Emit an event to all subscribers */
296
+ emit(event) {
297
+ const typeHandlers = this.handlers.get(event.type);
298
+ if (typeHandlers) {
299
+ for (const handler of typeHandlers) {
300
+ try {
301
+ handler(event);
302
+ } catch {
303
+ }
304
+ }
305
+ }
306
+ for (const handler of this.globalHandlers) {
307
+ try {
308
+ handler(event);
309
+ } catch {
310
+ }
311
+ }
312
+ }
313
+ /** Subscribe to a specific event type */
314
+ on(type, handler) {
315
+ if (!this.handlers.has(type)) {
316
+ this.handlers.set(type, /* @__PURE__ */ new Set());
317
+ }
318
+ this.handlers.get(type).add(handler);
319
+ }
320
+ /** Subscribe to ALL events */
321
+ onAny(handler) {
322
+ this.globalHandlers.add(handler);
323
+ }
324
+ /** Unsubscribe from a specific event type */
325
+ off(type, handler) {
326
+ this.handlers.get(type)?.delete(handler);
327
+ }
328
+ /** Unsubscribe from ALL events */
329
+ offAny(handler) {
330
+ this.globalHandlers.delete(handler);
331
+ }
332
+ /** Remove all listeners */
333
+ clear() {
334
+ this.handlers.clear();
335
+ this.globalHandlers.clear();
336
+ }
337
+ };
338
+ orgBus = new StateBus();
214
339
  }
215
340
  });
216
341
 
217
342
  // src/lib/session-registry.ts
218
- import path5 from "path";
343
+ import { readFileSync as readFileSync3, writeFileSync, mkdirSync, existsSync as existsSync3 } from "fs";
344
+ import path3 from "path";
219
345
  import os3 from "os";
346
+ function registerSession(entry) {
347
+ const dir = path3.dirname(REGISTRY_PATH);
348
+ if (!existsSync3(dir)) {
349
+ mkdirSync(dir, { recursive: true });
350
+ }
351
+ const sessions = listSessions();
352
+ const idx = sessions.findIndex((s) => s.windowName === entry.windowName);
353
+ if (idx >= 0) {
354
+ sessions[idx] = entry;
355
+ } else {
356
+ sessions.push(entry);
357
+ }
358
+ writeFileSync(REGISTRY_PATH, JSON.stringify(sessions, null, 2));
359
+ }
360
+ function listSessions() {
361
+ try {
362
+ const raw = readFileSync3(REGISTRY_PATH, "utf8");
363
+ return JSON.parse(raw);
364
+ } catch {
365
+ return [];
366
+ }
367
+ }
220
368
  var REGISTRY_PATH;
221
369
  var init_session_registry = __esm({
222
370
  "src/lib/session-registry.ts"() {
223
371
  "use strict";
224
- REGISTRY_PATH = path5.join(os3.homedir(), ".exe-os", "session-registry.json");
372
+ REGISTRY_PATH = path3.join(os3.homedir(), ".exe-os", "session-registry.json");
225
373
  }
226
374
  });
227
375
 
228
376
  // src/lib/session-key.ts
229
- import { execSync as execSync3 } from "child_process";
377
+ import { execSync } from "child_process";
378
+ function getSessionKey() {
379
+ if (_cached) return _cached;
380
+ let pid = process.ppid;
381
+ for (let i = 0; i < 10; i++) {
382
+ try {
383
+ const info = execSync(`ps -p ${pid} -o ppid=,comm=`, {
384
+ encoding: "utf8",
385
+ timeout: 2e3
386
+ }).trim();
387
+ const match = info.match(/^\s*(\d+)\s+(.+)$/);
388
+ if (!match) break;
389
+ const [, ppid, cmd] = match;
390
+ if (cmd === "claude" || cmd.endsWith("/claude")) {
391
+ _cached = String(pid);
392
+ return _cached;
393
+ }
394
+ pid = parseInt(ppid, 10);
395
+ if (pid <= 1) break;
396
+ } catch {
397
+ break;
398
+ }
399
+ }
400
+ _cached = process.env.CLAUDE_CODE_SSE_PORT ?? String(process.ppid);
401
+ return _cached;
402
+ }
403
+ var _cached;
230
404
  var init_session_key = __esm({
231
405
  "src/lib/session-key.ts"() {
232
406
  "use strict";
407
+ _cached = null;
408
+ }
409
+ });
410
+
411
+ // src/lib/tmux-transport.ts
412
+ var tmux_transport_exports = {};
413
+ __export(tmux_transport_exports, {
414
+ TmuxTransport: () => TmuxTransport
415
+ });
416
+ import { execFileSync } from "child_process";
417
+ var QUIET, TmuxTransport;
418
+ var init_tmux_transport = __esm({
419
+ "src/lib/tmux-transport.ts"() {
420
+ "use strict";
421
+ QUIET = {
422
+ encoding: "utf8",
423
+ stdio: ["pipe", "pipe", "pipe"]
424
+ };
425
+ TmuxTransport = class {
426
+ getMySession() {
427
+ try {
428
+ return execFileSync("tmux", ["display-message", "-p", "#{session_name}"], QUIET).trim() || null;
429
+ } catch {
430
+ return null;
431
+ }
432
+ }
433
+ listSessions() {
434
+ try {
435
+ return execFileSync("tmux", ["list-sessions", "-F", "#{session_name}"], QUIET).trim().split("\n").filter(Boolean);
436
+ } catch {
437
+ return [];
438
+ }
439
+ }
440
+ isAlive(target) {
441
+ try {
442
+ const sessions = this.listSessions();
443
+ if (!sessions.includes(target)) return false;
444
+ const paneStatus = execFileSync(
445
+ "tmux",
446
+ ["list-panes", "-t", target, "-F", "#{pane_dead}"],
447
+ QUIET
448
+ ).trim();
449
+ return paneStatus !== "1";
450
+ } catch {
451
+ return false;
452
+ }
453
+ }
454
+ sendKeys(target, keys) {
455
+ execFileSync("tmux", ["send-keys", "-t", target, keys, "Enter"], QUIET);
456
+ }
457
+ capturePane(target, lines) {
458
+ const args = ["capture-pane", "-t", target, "-p"];
459
+ if (lines) args.push("-S", `-${lines}`);
460
+ return execFileSync("tmux", args, { ...QUIET, timeout: 3e3 });
461
+ }
462
+ isPaneInCopyMode(target) {
463
+ try {
464
+ const result = execFileSync(
465
+ "tmux",
466
+ ["display-message", "-p", "-t", target, "#{pane_in_mode}"],
467
+ { ...QUIET, timeout: 3e3 }
468
+ ).trim();
469
+ return result === "1";
470
+ } catch {
471
+ return false;
472
+ }
473
+ }
474
+ spawn(name, config) {
475
+ try {
476
+ const args = ["new-session", "-d", "-s", name];
477
+ if (config.cwd) args.push("-c", config.cwd);
478
+ args.push(config.command);
479
+ execFileSync("tmux", args);
480
+ return { sessionName: name };
481
+ } catch (e) {
482
+ return { sessionName: name, error: `spawn failed: ${e}` };
483
+ }
484
+ }
485
+ kill(target) {
486
+ try {
487
+ execFileSync("tmux", ["kill-session", "-t", target], QUIET);
488
+ } catch {
489
+ }
490
+ }
491
+ pipeLog(target, logFile) {
492
+ try {
493
+ const safePath = logFile.replace(/'/g, "'\\''");
494
+ execFileSync("tmux", ["pipe-pane", "-t", target, `cat >> '${safePath}'`], QUIET);
495
+ } catch {
496
+ }
497
+ }
498
+ };
233
499
  }
234
500
  });
235
501
 
236
502
  // src/lib/transport.ts
503
+ function getTransport() {
504
+ if (!_transport) {
505
+ const { TmuxTransport: TmuxTransport2 } = (init_tmux_transport(), __toCommonJS(tmux_transport_exports));
506
+ _transport = new TmuxTransport2();
507
+ }
508
+ return _transport;
509
+ }
510
+ var _transport;
237
511
  var init_transport = __esm({
238
512
  "src/lib/transport.ts"() {
239
513
  "use strict";
514
+ _transport = null;
240
515
  }
241
516
  });
242
517
 
243
518
  // src/lib/cc-agent-support.ts
244
- import { execSync as execSync4 } from "child_process";
519
+ import { execSync as execSync2 } from "child_process";
520
+ function _resetCcAgentSupportCache() {
521
+ _cachedSupport = null;
522
+ }
523
+ function claudeSupportsAgentFlag() {
524
+ if (_cachedSupport !== null) return _cachedSupport;
525
+ try {
526
+ const helpOutput = execSync2("claude --help 2>&1", {
527
+ encoding: "utf-8",
528
+ timeout: 5e3
529
+ });
530
+ _cachedSupport = /(^|\s)--agent(\b|=)/.test(helpOutput);
531
+ } catch {
532
+ _cachedSupport = false;
533
+ }
534
+ return _cachedSupport;
535
+ }
536
+ var _cachedSupport;
245
537
  var init_cc_agent_support = __esm({
246
538
  "src/lib/cc-agent-support.ts"() {
247
539
  "use strict";
540
+ _cachedSupport = null;
248
541
  }
249
542
  });
250
543
 
251
544
  // src/lib/mcp-prefix.ts
545
+ function expandDualPrefixTools(shortNames) {
546
+ const out = [];
547
+ for (const name of shortNames) {
548
+ for (const prefix of MCP_TOOL_PREFIXES) {
549
+ out.push(prefix + name);
550
+ }
551
+ }
552
+ return out;
553
+ }
252
554
  var MCP_PRIMARY_KEY, MCP_LEGACY_KEY, MCP_TOOL_PREFIXES;
253
555
  var init_mcp_prefix = __esm({
254
556
  "src/lib/mcp-prefix.ts"() {
@@ -263,46 +565,194 @@ var init_mcp_prefix = __esm({
263
565
  });
264
566
 
265
567
  // src/lib/provider-table.ts
568
+ function detectActiveProvider(env = process.env) {
569
+ const baseUrl = env.ANTHROPIC_BASE_URL;
570
+ if (!baseUrl) return DEFAULT_PROVIDER;
571
+ for (const [name, cfg] of Object.entries(PROVIDER_TABLE)) {
572
+ if (cfg.baseUrl === baseUrl) return name;
573
+ }
574
+ return DEFAULT_PROVIDER;
575
+ }
576
+ var PROVIDER_TABLE, DEFAULT_PROVIDER;
266
577
  var init_provider_table = __esm({
267
578
  "src/lib/provider-table.ts"() {
268
579
  "use strict";
580
+ PROVIDER_TABLE = {
581
+ opencode: {
582
+ baseUrl: "https://opencode.ai/zen/go",
583
+ apiKeyEnv: "OPENCODE_API_KEY",
584
+ defaultModel: "minimax-m2.7"
585
+ }
586
+ };
587
+ DEFAULT_PROVIDER = "default";
269
588
  }
270
589
  });
271
590
 
272
591
  // src/lib/intercom-queue.ts
273
- import { readFileSync as readFileSync5, writeFileSync, renameSync as renameSync2, existsSync as existsSync5, mkdirSync } from "fs";
274
- import path6 from "path";
592
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync2, renameSync as renameSync2, existsSync as existsSync4, mkdirSync as mkdirSync2 } from "fs";
593
+ import path4 from "path";
275
594
  import os4 from "os";
595
+ function ensureDir() {
596
+ const dir = path4.dirname(QUEUE_PATH);
597
+ if (!existsSync4(dir)) mkdirSync2(dir, { recursive: true });
598
+ }
599
+ function readQueue() {
600
+ try {
601
+ if (!existsSync4(QUEUE_PATH)) return [];
602
+ return JSON.parse(readFileSync4(QUEUE_PATH, "utf8"));
603
+ } catch {
604
+ return [];
605
+ }
606
+ }
607
+ function writeQueue(queue) {
608
+ ensureDir();
609
+ const tmp = `${QUEUE_PATH}.tmp`;
610
+ writeFileSync2(tmp, JSON.stringify(queue, null, 2));
611
+ renameSync2(tmp, QUEUE_PATH);
612
+ }
613
+ function queueIntercom(targetSession, reason) {
614
+ const queue = readQueue();
615
+ const existing = queue.find((q) => q.targetSession === targetSession);
616
+ if (existing) {
617
+ existing.attempts++;
618
+ existing.queuedAt = (/* @__PURE__ */ new Date()).toISOString();
619
+ existing.reason = reason;
620
+ } else {
621
+ queue.push({
622
+ targetSession,
623
+ queuedAt: (/* @__PURE__ */ new Date()).toISOString(),
624
+ attempts: 0,
625
+ reason
626
+ });
627
+ }
628
+ writeQueue(queue);
629
+ }
276
630
  var QUEUE_PATH, TTL_MS, INTERCOM_LOG;
277
631
  var init_intercom_queue = __esm({
278
632
  "src/lib/intercom-queue.ts"() {
279
633
  "use strict";
280
- QUEUE_PATH = path6.join(os4.homedir(), ".exe-os", "intercom-queue.json");
634
+ QUEUE_PATH = path4.join(os4.homedir(), ".exe-os", "intercom-queue.json");
281
635
  TTL_MS = 60 * 60 * 1e3;
282
- INTERCOM_LOG = path6.join(os4.homedir(), ".exe-os", "intercom.log");
636
+ INTERCOM_LOG = path4.join(os4.homedir(), ".exe-os", "intercom.log");
637
+ }
638
+ });
639
+
640
+ // src/lib/employees.ts
641
+ import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
642
+ import { existsSync as existsSync5, symlinkSync, readlinkSync, readFileSync as readFileSync5 } from "fs";
643
+ import { execSync as execSync3 } from "child_process";
644
+ import path5 from "path";
645
+ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
646
+ if (!existsSync5(employeesPath)) return [];
647
+ try {
648
+ return JSON.parse(readFileSync5(employeesPath, "utf-8"));
649
+ } catch {
650
+ return [];
651
+ }
652
+ }
653
+ function getEmployee(employees, name) {
654
+ return employees.find((e) => e.name.toLowerCase() === name.toLowerCase());
655
+ }
656
+ function isMultiInstance(agentName, employees) {
657
+ const roster = employees ?? loadEmployeesSync();
658
+ const emp = getEmployee(roster, agentName);
659
+ if (!emp) return false;
660
+ return MULTI_INSTANCE_ROLES.has(emp.role.toLowerCase());
661
+ }
662
+ var EMPLOYEES_PATH, MULTI_INSTANCE_ROLES;
663
+ var init_employees = __esm({
664
+ "src/lib/employees.ts"() {
665
+ "use strict";
666
+ init_config();
667
+ EMPLOYEES_PATH = path5.join(EXE_AI_DIR, "exe-employees.json");
668
+ MULTI_INSTANCE_ROLES = /* @__PURE__ */ new Set(["principal engineer", "content production specialist", "staff code reviewer"]);
283
669
  }
284
670
  });
285
671
 
286
672
  // src/lib/license.ts
287
- import { readFileSync as readFileSync6, writeFileSync as writeFileSync2, existsSync as existsSync6, mkdirSync as mkdirSync2 } from "fs";
673
+ import { readFileSync as readFileSync6, writeFileSync as writeFileSync3, existsSync as existsSync6, mkdirSync as mkdirSync3 } from "fs";
288
674
  import { randomUUID } from "crypto";
289
- import path7 from "path";
675
+ import path6 from "path";
290
676
  import { jwtVerify, importSPKI } from "jose";
291
- var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH;
677
+ var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH, PLAN_LIMITS;
292
678
  var init_license = __esm({
293
679
  "src/lib/license.ts"() {
294
680
  "use strict";
295
681
  init_config();
296
- LICENSE_PATH = path7.join(EXE_AI_DIR, "license.key");
297
- CACHE_PATH = path7.join(EXE_AI_DIR, "license-cache.json");
298
- DEVICE_ID_PATH = path7.join(EXE_AI_DIR, "device-id");
682
+ LICENSE_PATH = path6.join(EXE_AI_DIR, "license.key");
683
+ CACHE_PATH = path6.join(EXE_AI_DIR, "license-cache.json");
684
+ DEVICE_ID_PATH = path6.join(EXE_AI_DIR, "device-id");
685
+ PLAN_LIMITS = {
686
+ free: { devices: 1, employees: 1, memories: 5e3 },
687
+ pro: { devices: 2, employees: 5, memories: 1e5 },
688
+ team: { devices: 10, employees: 20, memories: 1e6 },
689
+ agency: { devices: 50, employees: 100, memories: 1e7 },
690
+ enterprise: { devices: -1, employees: -1, memories: -1 }
691
+ };
299
692
  }
300
693
  });
301
694
 
302
695
  // src/lib/plan-limits.ts
303
696
  import { readFileSync as readFileSync7, existsSync as existsSync7 } from "fs";
304
- import path8 from "path";
305
- var CACHE_PATH2;
697
+ import path7 from "path";
698
+ function getLicenseSync() {
699
+ try {
700
+ if (!existsSync7(CACHE_PATH2)) return freeLicense();
701
+ const raw = JSON.parse(readFileSync7(CACHE_PATH2, "utf8"));
702
+ if (!raw.token || typeof raw.token !== "string") return freeLicense();
703
+ const parts = raw.token.split(".");
704
+ if (parts.length !== 3) return freeLicense();
705
+ const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
706
+ const plan = payload.plan ?? "free";
707
+ const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
708
+ return {
709
+ valid: true,
710
+ plan,
711
+ email: payload.sub ?? "",
712
+ expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
713
+ deviceLimit: limits.devices,
714
+ employeeLimit: limits.employees,
715
+ memoryLimit: limits.memories
716
+ };
717
+ } catch {
718
+ return freeLicense();
719
+ }
720
+ }
721
+ function freeLicense() {
722
+ const limits = PLAN_LIMITS.free;
723
+ return {
724
+ valid: true,
725
+ plan: "free",
726
+ email: "",
727
+ expiresAt: null,
728
+ deviceLimit: limits.devices,
729
+ employeeLimit: limits.employees,
730
+ memoryLimit: limits.memories
731
+ };
732
+ }
733
+ function assertEmployeeLimitSync(rosterPath) {
734
+ const license = getLicenseSync();
735
+ if (license.employeeLimit < 0) return;
736
+ const filePath = rosterPath ?? EMPLOYEES_PATH;
737
+ let count = 0;
738
+ try {
739
+ if (existsSync7(filePath)) {
740
+ const raw = readFileSync7(filePath, "utf8");
741
+ const employees = JSON.parse(raw);
742
+ count = Array.isArray(employees) ? employees.length : 0;
743
+ }
744
+ } catch {
745
+ throw new PlanLimitError(
746
+ `Cannot verify employee count: roster unreadable at ${filePath}. Refusing to proceed. Check file permissions or upgrade plan.`
747
+ );
748
+ }
749
+ if (count >= license.employeeLimit) {
750
+ throw new PlanLimitError(
751
+ `Employee limit reached: ${count}/${license.employeeLimit} employees on the ${license.plan} plan. Upgrade at https://askexe.com to add more.`
752
+ );
753
+ }
754
+ }
755
+ var PlanLimitError, CACHE_PATH2;
306
756
  var init_plan_limits = __esm({
307
757
  "src/lib/plan-limits.ts"() {
308
758
  "use strict";
@@ -310,133 +760,2312 @@ var init_plan_limits = __esm({
310
760
  init_employees();
311
761
  init_license();
312
762
  init_config();
313
- CACHE_PATH2 = path8.join(EXE_AI_DIR, "license-cache.json");
763
+ PlanLimitError = class extends Error {
764
+ constructor(message) {
765
+ super(message);
766
+ this.name = "PlanLimitError";
767
+ }
768
+ };
769
+ CACHE_PATH2 = path7.join(EXE_AI_DIR, "license-cache.json");
314
770
  }
315
771
  });
316
772
 
317
- // src/lib/tmux-routing.ts
318
- import path9 from "path";
319
- import os5 from "os";
320
- import { fileURLToPath } from "url";
321
- var SPAWN_LOCK_DIR, SESSION_CACHE, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS;
322
- var init_tmux_routing = __esm({
323
- "src/lib/tmux-routing.ts"() {
324
- "use strict";
325
- init_session_registry();
326
- init_session_key();
327
- init_transport();
328
- init_cc_agent_support();
329
- init_mcp_prefix();
330
- init_provider_table();
331
- init_intercom_queue();
332
- init_plan_limits();
333
- SPAWN_LOCK_DIR = path9.join(os5.homedir(), ".exe-os", "spawn-locks");
334
- SESSION_CACHE = path9.join(os5.homedir(), ".exe-os", "session-cache");
335
- INTERCOM_LOG2 = path9.join(os5.homedir(), ".exe-os", "intercom.log");
336
- DEBOUNCE_FILE = path9.join(SESSION_CACHE, "intercom-debounce.json");
337
- DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
773
+ // src/lib/session-kill-telemetry.ts
774
+ import crypto2 from "crypto";
775
+ async function recordSessionKill(input) {
776
+ try {
777
+ const client = getClient();
778
+ await client.execute({
779
+ sql: `INSERT INTO session_kills
780
+ (id, session_name, agent_id, killed_at, reason,
781
+ ticks_idle, estimated_tokens_saved)
782
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
783
+ args: [
784
+ crypto2.randomUUID(),
785
+ input.sessionName,
786
+ input.agentId,
787
+ (/* @__PURE__ */ new Date()).toISOString(),
788
+ input.reason,
789
+ input.ticksIdle ?? null,
790
+ input.estimatedTokensSaved ?? null
791
+ ]
792
+ });
793
+ } catch (err) {
794
+ process.stderr.write(
795
+ `[session-kill-telemetry] write failed: ${err instanceof Error ? err.message : String(err)}
796
+ `
797
+ );
338
798
  }
339
- });
340
-
341
- // src/lib/tasks-review.ts
342
- import path10 from "path";
343
- import { existsSync as existsSync8, readdirSync as readdirSync2, unlinkSync as unlinkSync2 } from "fs";
344
- var init_tasks_review = __esm({
345
- "src/lib/tasks-review.ts"() {
799
+ }
800
+ var init_session_kill_telemetry = __esm({
801
+ "src/lib/session-kill-telemetry.ts"() {
346
802
  "use strict";
347
803
  init_database();
348
- init_config();
349
- init_employees();
350
- init_notifications();
351
- init_tasks_crud();
352
- init_tmux_routing();
353
- init_session_key();
354
804
  }
355
805
  });
356
806
 
357
- // src/lib/tasks-chain.ts
358
- import path11 from "path";
359
- import { readFile as readFile3, writeFile as writeFile4 } from "fs/promises";
360
- var init_tasks_chain = __esm({
361
- "src/lib/tasks-chain.ts"() {
362
- "use strict";
363
- init_database();
364
- init_notifications();
365
- }
807
+ // src/lib/capacity-monitor.ts
808
+ var capacity_monitor_exports = {};
809
+ __export(capacity_monitor_exports, {
810
+ CTX_FLOOR_PERCENT: () => CTX_FLOOR_PERCENT,
811
+ _resetLastRelaunchCache: () => _resetLastRelaunchCache,
812
+ _resetPendingCapacityKills: () => _resetPendingCapacityKills,
813
+ confirmCapacityKill: () => confirmCapacityKill,
814
+ createOrRefreshResumeTask: () => createOrRefreshResumeTask,
815
+ extractContextPercent: () => extractContextPercent,
816
+ isAtCapacity: () => isAtCapacity,
817
+ isWithinRelaunchCooldown: () => isWithinRelaunchCooldown,
818
+ pollCapacityDead: () => pollCapacityDead
366
819
  });
367
-
368
- // src/lib/tasks-notify.ts
369
- var init_tasks_notify = __esm({
370
- "src/lib/tasks-notify.ts"() {
820
+ function resumeTaskTitle(agentId) {
821
+ return `${RESUME_TITLE_PREFIX} ${agentId} hit context capacity \u2014 continue open tasks`;
822
+ }
823
+ function buildResumeContext(agentId, openTasks) {
824
+ const taskList = openTasks.map(
825
+ (r, i) => `${i + 1}. [${String(r.priority).toUpperCase()}] ${String(r.title)} (${String(r.task_file)})`
826
+ ).join("\n");
827
+ return [
828
+ "## Context",
829
+ "",
830
+ `${agentId} hit context capacity and was auto-relaunched by the capacity monitor.`,
831
+ "Call recall_my_memory first \u2014 search for 'CONTEXT CHECKPOINT'. Pick up where the previous session stopped.",
832
+ "",
833
+ `You have ${openTasks.length} open task(s). Work through them in priority order:`,
834
+ "",
835
+ taskList,
836
+ "",
837
+ "Read each task file and chain through them. Build and commit after each one."
838
+ ].join("\n");
839
+ }
840
+ function filterPaneContent(paneOutput) {
841
+ return paneOutput.split("\n").filter((line) => {
842
+ if (CONTENT_LINE_PREFIX.test(line)) return false;
843
+ for (const marker of CONTENT_LINE_MARKERS) {
844
+ if (line.includes(marker)) return false;
845
+ }
846
+ for (const re of SOURCE_CODE_MARKERS) {
847
+ if (re.test(line)) return false;
848
+ }
849
+ return true;
850
+ }).join("\n");
851
+ }
852
+ function extractContextPercent(paneOutput) {
853
+ const match = paneOutput.match(CC_CONTEXT_BAR_RE);
854
+ if (!match) return null;
855
+ const parsed = Number.parseInt(match[2], 10);
856
+ return Number.isFinite(parsed) ? parsed : null;
857
+ }
858
+ function isAtCapacity(paneOutput) {
859
+ const filtered = filterPaneContent(paneOutput);
860
+ return CAPACITY_PATTERNS.some((p) => p.test(filtered));
861
+ }
862
+ function confirmCapacityKill(agentId, now = Date.now()) {
863
+ const pendingSince = _pendingCapacityKill.get(agentId);
864
+ if (pendingSince === void 0) {
865
+ _pendingCapacityKill.set(agentId, now);
866
+ return false;
867
+ }
868
+ if (now - pendingSince > CONFIRMATION_WINDOW_MS) {
869
+ _pendingCapacityKill.set(agentId, now);
870
+ return false;
871
+ }
872
+ _pendingCapacityKill.delete(agentId);
873
+ return true;
874
+ }
875
+ function _resetPendingCapacityKills() {
876
+ _pendingCapacityKill.clear();
877
+ }
878
+ function _resetLastRelaunchCache() {
879
+ _lastRelaunch.clear();
880
+ }
881
+ async function lastResumeCreatedAtMs(agentId) {
882
+ const client = getClient();
883
+ const result = await client.execute({
884
+ sql: `SELECT MAX(created_at) AS last_created_at
885
+ FROM tasks
886
+ WHERE assigned_to = ? AND title LIKE ?`,
887
+ args: [agentId, `${RESUME_TITLE_PREFIX} %`]
888
+ });
889
+ const raw = result.rows[0]?.last_created_at;
890
+ if (raw === null || raw === void 0) return null;
891
+ const parsed = Date.parse(String(raw));
892
+ return Number.isNaN(parsed) ? null : parsed;
893
+ }
894
+ async function isWithinRelaunchCooldown(agentId, now = Date.now()) {
895
+ const cached = _lastRelaunch.get(agentId);
896
+ if (cached !== void 0) return now - cached < RELAUNCH_COOLDOWN_MS;
897
+ const persisted = await lastResumeCreatedAtMs(agentId);
898
+ if (persisted === null) return false;
899
+ if (now - persisted >= RELAUNCH_COOLDOWN_MS) return false;
900
+ _lastRelaunch.set(agentId, persisted);
901
+ return true;
902
+ }
903
+ async function createOrRefreshResumeTask(agentId, projectDir, openTasks) {
904
+ const client = getClient();
905
+ const now = (/* @__PURE__ */ new Date()).toISOString();
906
+ const context = buildResumeContext(agentId, openTasks);
907
+ const existing = await client.execute({
908
+ sql: `SELECT id FROM tasks
909
+ WHERE assigned_to = ?
910
+ AND title LIKE ?
911
+ AND status IN (${RESUME_ACTIVE_STATUSES.map(() => "?").join(", ")})
912
+ ORDER BY created_at DESC
913
+ LIMIT 1`,
914
+ args: [agentId, RESUME_TITLE_LIKE_PATTERN, ...RESUME_ACTIVE_STATUSES]
915
+ });
916
+ if (existing.rows.length > 0) {
917
+ const taskId = String(existing.rows[0].id);
918
+ await client.execute({
919
+ sql: `UPDATE tasks SET context = ?, updated_at = ? WHERE id = ?`,
920
+ args: [context, now, taskId]
921
+ });
922
+ return { created: false, taskId };
923
+ }
924
+ const { createTask: createTask2 } = await Promise.resolve().then(() => (init_tasks(), tasks_exports));
925
+ const task = await createTask2({
926
+ title: resumeTaskTitle(agentId),
927
+ assignedTo: agentId,
928
+ assignedBy: "system",
929
+ projectName: projectDir.split("/").pop() ?? "unknown",
930
+ priority: "p0",
931
+ context,
932
+ baseDir: projectDir
933
+ });
934
+ return { created: true, taskId: task.id };
935
+ }
936
+ async function pollCapacityDead() {
937
+ const transport = getTransport();
938
+ const relaunched = [];
939
+ const registered = listSessions().filter(
940
+ (s) => s.agentId !== "exe"
941
+ );
942
+ if (registered.length === 0) return [];
943
+ let liveSessions;
944
+ try {
945
+ liveSessions = transport.listSessions();
946
+ } catch {
947
+ return [];
948
+ }
949
+ for (const entry of registered) {
950
+ const { windowName, agentId, projectDir } = entry;
951
+ if (!liveSessions.includes(windowName)) continue;
952
+ if (await isWithinRelaunchCooldown(agentId)) continue;
953
+ let pane;
954
+ try {
955
+ pane = transport.capturePane(windowName, 15);
956
+ } catch {
957
+ continue;
958
+ }
959
+ if (!isAtCapacity(pane)) continue;
960
+ const ctxPct = extractContextPercent(pane);
961
+ if (ctxPct !== null && ctxPct < CTX_FLOOR_PERCENT) {
962
+ process.stderr.write(
963
+ `[capacity-monitor] ctx-floor: ${agentId} at ${ctxPct}% in ${windowName} \u2014 below ${CTX_FLOOR_PERCENT}%. Skipping capacity kill (likely self-referential content or false positive).
964
+ `
965
+ );
966
+ continue;
967
+ }
968
+ if (!confirmCapacityKill(agentId)) {
969
+ process.stderr.write(
970
+ `[capacity-monitor] ${agentId} matched capacity pattern once in ${windowName}. Awaiting confirmation on next tick.
971
+ `
972
+ );
973
+ continue;
974
+ }
975
+ const verify = await verifyPaneAtCapacity(windowName);
976
+ if (!verify.atCapacity) {
977
+ process.stderr.write(
978
+ `[capacity-monitor] verifyPaneAtCapacity rejected kill for ${agentId} in ${windowName} (reason: ${verify.reason}). Skipping.
979
+ `
980
+ );
981
+ void recordSessionKill({
982
+ sessionName: windowName,
983
+ agentId,
984
+ reason: "capacity_false_positive_blocked"
985
+ });
986
+ continue;
987
+ }
988
+ process.stderr.write(
989
+ `[capacity-monitor] Detected ${agentId} at capacity in session ${windowName} (confirmed). Auto-relaunching.
990
+ `
991
+ );
992
+ try {
993
+ transport.kill(windowName);
994
+ void recordSessionKill({
995
+ sessionName: windowName,
996
+ agentId,
997
+ reason: "capacity"
998
+ });
999
+ const client = getClient();
1000
+ const openTasks = await client.execute({
1001
+ sql: `SELECT id, title, priority, task_file, status
1002
+ FROM tasks
1003
+ WHERE assigned_to = ? AND status IN ('open', 'in_progress')
1004
+ ORDER BY
1005
+ CASE priority WHEN 'p0' THEN 0 WHEN 'p1' THEN 1 WHEN 'p2' THEN 2 ELSE 3 END,
1006
+ created_at ASC
1007
+ LIMIT 10`,
1008
+ args: [agentId]
1009
+ });
1010
+ if (openTasks.rows.length === 0) {
1011
+ process.stderr.write(
1012
+ `[capacity-monitor] ${agentId} has no open tasks \u2014 skipping relaunch.
1013
+ `
1014
+ );
1015
+ continue;
1016
+ }
1017
+ const { created } = await createOrRefreshResumeTask(
1018
+ agentId,
1019
+ projectDir,
1020
+ openTasks.rows
1021
+ );
1022
+ if (created) {
1023
+ await writeNotification({
1024
+ agentId: "system",
1025
+ agentRole: "daemon",
1026
+ event: "capacity_relaunch",
1027
+ project: projectDir.split("/").pop() ?? "unknown",
1028
+ summary: `${agentId} hit context capacity. Auto-relaunched with ${openTasks.rows.length} open task(s).`
1029
+ });
1030
+ }
1031
+ _lastRelaunch.set(agentId, Date.now());
1032
+ if (created) relaunched.push(agentId);
1033
+ } catch (err) {
1034
+ process.stderr.write(
1035
+ `[capacity-monitor] Failed to relaunch ${agentId}: ${err instanceof Error ? err.message : String(err)}
1036
+ `
1037
+ );
1038
+ }
1039
+ }
1040
+ return relaunched;
1041
+ }
1042
+ 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;
1043
+ var init_capacity_monitor = __esm({
1044
+ "src/lib/capacity-monitor.ts"() {
1045
+ "use strict";
1046
+ init_session_registry();
1047
+ init_transport();
1048
+ init_notifications();
1049
+ init_database();
1050
+ init_session_kill_telemetry();
1051
+ init_tmux_routing();
1052
+ CAPACITY_PATTERNS = [
1053
+ /conversation is too long/i,
1054
+ /maximum context length/i,
1055
+ /context window.*(?:limit|exceed|full)/i,
1056
+ /reached.*(?:token|context).*limit/i
1057
+ ];
1058
+ CONTENT_LINE_PREFIX = /^[\s>#\-*[]/;
1059
+ CONTENT_LINE_MARKERS = [
1060
+ "RESUME:",
1061
+ "intercom",
1062
+ "capacity-monitor",
1063
+ "CAPACITY_PATTERNS",
1064
+ "isAtCapacity",
1065
+ "CONTENT_LINE_MARKERS",
1066
+ "pollCapacityDead",
1067
+ "confirmCapacityKill",
1068
+ "session_kills",
1069
+ "capacity-monitor.test"
1070
+ ];
1071
+ SOURCE_CODE_MARKERS = [
1072
+ /["'`/].*(?:maximum context length|conversation is too long)/i,
1073
+ /(?:maximum context length|conversation is too long).*["'`/]/i
1074
+ ];
1075
+ RELAUNCH_COOLDOWN_MS = 5 * 60 * 1e3;
1076
+ _lastRelaunch = /* @__PURE__ */ new Map();
1077
+ RESUME_TITLE_PREFIX = "RESUME:";
1078
+ RESUME_TITLE_LIKE_PATTERN = `${RESUME_TITLE_PREFIX} % hit context capacity%`;
1079
+ RESUME_ACTIVE_STATUSES = ["open", "in_progress"];
1080
+ CONFIRMATION_WINDOW_MS = 3 * 60 * 1e3;
1081
+ _pendingCapacityKill = /* @__PURE__ */ new Map();
1082
+ CC_CONTEXT_BAR_RE = /([\u2588\u2591\u2592\u2593]{10})\s+(\d+)%/;
1083
+ CTX_FLOOR_PERCENT = 50;
1084
+ }
1085
+ });
1086
+
1087
+ // src/lib/tmux-routing.ts
1088
+ var tmux_routing_exports = {};
1089
+ __export(tmux_routing_exports, {
1090
+ acquireSpawnLock: () => acquireSpawnLock,
1091
+ employeeSessionName: () => employeeSessionName,
1092
+ ensureEmployee: () => ensureEmployee,
1093
+ extractRootExe: () => extractRootExe,
1094
+ findFreeInstance: () => findFreeInstance,
1095
+ getDispatchedBy: () => getDispatchedBy,
1096
+ getMySession: () => getMySession,
1097
+ getParentExe: () => getParentExe,
1098
+ getSessionState: () => getSessionState,
1099
+ isEmployeeAlive: () => isEmployeeAlive,
1100
+ isExeSession: () => isExeSession,
1101
+ isSessionBusy: () => isSessionBusy,
1102
+ notifyParentExe: () => notifyParentExe,
1103
+ parseParentExe: () => parseParentExe,
1104
+ registerParentExe: () => registerParentExe,
1105
+ releaseSpawnLock: () => releaseSpawnLock,
1106
+ resolveExeSession: () => resolveExeSession,
1107
+ sendIntercom: () => sendIntercom,
1108
+ spawnEmployee: () => spawnEmployee,
1109
+ verifyPaneAtCapacity: () => verifyPaneAtCapacity
1110
+ });
1111
+ import { execFileSync as execFileSync2, execSync as execSync4 } from "child_process";
1112
+ import { readFileSync as readFileSync8, writeFileSync as writeFileSync4, mkdirSync as mkdirSync4, existsSync as existsSync8, appendFileSync } from "fs";
1113
+ import path8 from "path";
1114
+ import os5 from "os";
1115
+ import { fileURLToPath } from "url";
1116
+ import { unlinkSync as unlinkSync2 } from "fs";
1117
+ function spawnLockPath(sessionName) {
1118
+ return path8.join(SPAWN_LOCK_DIR, `${sessionName}.lock`);
1119
+ }
1120
+ function isProcessAlive(pid) {
1121
+ try {
1122
+ process.kill(pid, 0);
1123
+ return true;
1124
+ } catch {
1125
+ return false;
1126
+ }
1127
+ }
1128
+ function acquireSpawnLock(sessionName) {
1129
+ if (!existsSync8(SPAWN_LOCK_DIR)) {
1130
+ mkdirSync4(SPAWN_LOCK_DIR, { recursive: true });
1131
+ }
1132
+ const lockFile = spawnLockPath(sessionName);
1133
+ if (existsSync8(lockFile)) {
1134
+ try {
1135
+ const lock = JSON.parse(readFileSync8(lockFile, "utf8"));
1136
+ const age = Date.now() - lock.timestamp;
1137
+ if (isProcessAlive(lock.pid) && age < 6e4) {
1138
+ return false;
1139
+ }
1140
+ } catch {
1141
+ }
1142
+ }
1143
+ writeFileSync4(lockFile, JSON.stringify({ pid: process.pid, timestamp: Date.now() }));
1144
+ return true;
1145
+ }
1146
+ function releaseSpawnLock(sessionName) {
1147
+ try {
1148
+ unlinkSync2(spawnLockPath(sessionName));
1149
+ } catch {
1150
+ }
1151
+ }
1152
+ function resolveBehaviorsExporterScript() {
1153
+ try {
1154
+ const thisFile = fileURLToPath(import.meta.url);
1155
+ const scriptPath = path8.join(
1156
+ path8.dirname(thisFile),
1157
+ "..",
1158
+ "bin",
1159
+ "exe-export-behaviors.js"
1160
+ );
1161
+ return existsSync8(scriptPath) ? scriptPath : null;
1162
+ } catch {
1163
+ return null;
1164
+ }
1165
+ }
1166
+ function exportBehaviorsSync(agentId, projectName, sessionKey) {
1167
+ const script = resolveBehaviorsExporterScript();
1168
+ if (!script) return null;
1169
+ try {
1170
+ const output = execFileSync2(
1171
+ process.execPath,
1172
+ [script, agentId, projectName, sessionKey],
1173
+ { encoding: "utf-8", timeout: BEHAVIORS_EXPORT_TIMEOUT_MS }
1174
+ ).trim();
1175
+ return output.length > 0 ? output : null;
1176
+ } catch (err) {
1177
+ process.stderr.write(
1178
+ `[tmux-routing] behaviors export failed for ${agentId}: ${err instanceof Error ? err.message : String(err)}
1179
+ `
1180
+ );
1181
+ return null;
1182
+ }
1183
+ }
1184
+ function getMySession() {
1185
+ return getTransport().getMySession();
1186
+ }
1187
+ function employeeSessionName(employee, exeSession, instance) {
1188
+ if (!/^exe\d+$/.test(exeSession)) {
1189
+ const root = extractRootExe(exeSession);
1190
+ if (root) {
1191
+ process.stderr.write(
1192
+ `[tmux-routing] WARN: exeSession="${exeSession}" is not a root exe session, using "${root}" instead
1193
+ `
1194
+ );
1195
+ exeSession = root;
1196
+ } else {
1197
+ throw new Error(
1198
+ `Invalid exeSession "${exeSession}" \u2014 must be a root exe session (e.g., "exe1"), not an agent session`
1199
+ );
1200
+ }
1201
+ }
1202
+ const suffix = instance != null && instance > 0 ? String(instance) : "";
1203
+ const name = `${employee}${suffix}-${exeSession}`;
1204
+ if (!VALID_SESSION_NAME.test(name)) {
1205
+ throw new Error(
1206
+ `Invalid session name "${name}" \u2014 must match {agent}-exe{N} or {agent}{instance}-exe{N}`
1207
+ );
1208
+ }
1209
+ return name;
1210
+ }
1211
+ function parseParentExe(sessionName, agentId) {
1212
+ const escaped = agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1213
+ const regex = new RegExp(`^${escaped}\\d*-(.+)$`);
1214
+ const match = sessionName.match(regex);
1215
+ return match?.[1] ?? null;
1216
+ }
1217
+ function extractRootExe(name) {
1218
+ const match = name.match(/(exe\d+)$/);
1219
+ return match?.[1] ?? null;
1220
+ }
1221
+ function registerParentExe(sessionKey, parentExe, dispatchedBy) {
1222
+ if (!existsSync8(SESSION_CACHE)) {
1223
+ mkdirSync4(SESSION_CACHE, { recursive: true });
1224
+ }
1225
+ const rootExe = extractRootExe(parentExe) ?? parentExe;
1226
+ const filePath = path8.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`);
1227
+ writeFileSync4(filePath, JSON.stringify({
1228
+ parentExe: rootExe,
1229
+ dispatchedBy: dispatchedBy || rootExe,
1230
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString()
1231
+ }));
1232
+ }
1233
+ function getParentExe(sessionKey) {
1234
+ try {
1235
+ const data = JSON.parse(readFileSync8(path8.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
1236
+ return data.parentExe || null;
1237
+ } catch {
1238
+ return null;
1239
+ }
1240
+ }
1241
+ function getDispatchedBy(sessionKey) {
1242
+ try {
1243
+ const data = JSON.parse(readFileSync8(
1244
+ path8.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`),
1245
+ "utf8"
1246
+ ));
1247
+ return data.dispatchedBy ?? data.parentExe ?? null;
1248
+ } catch {
1249
+ return null;
1250
+ }
1251
+ }
1252
+ function resolveExeSession() {
1253
+ const mySession = getMySession();
1254
+ if (!mySession) return null;
1255
+ try {
1256
+ const key = getSessionKey();
1257
+ const parentExe = getParentExe(key);
1258
+ if (parentExe) {
1259
+ return extractRootExe(parentExe) ?? parentExe;
1260
+ }
1261
+ } catch {
1262
+ }
1263
+ return extractRootExe(mySession) ?? mySession;
1264
+ }
1265
+ function isEmployeeAlive(sessionName) {
1266
+ return getTransport().isAlive(sessionName);
1267
+ }
1268
+ function findFreeInstance(employeeName, exeSession, maxInstances = 10, isAlive = isEmployeeAlive) {
1269
+ const base = employeeSessionName(employeeName, exeSession);
1270
+ if (!isAlive(base) && acquireSpawnLock(base)) return 0;
1271
+ for (let i = 2; i <= maxInstances; i++) {
1272
+ const candidate = employeeSessionName(employeeName, exeSession, i);
1273
+ if (!isAlive(candidate) && acquireSpawnLock(candidate)) return i;
1274
+ }
1275
+ return null;
1276
+ }
1277
+ async function verifyPaneAtCapacity(sessionName) {
1278
+ const transport = getTransport();
1279
+ if (!transport.isAlive(sessionName)) {
1280
+ return { atCapacity: false, reason: `session ${sessionName} is not alive` };
1281
+ }
1282
+ let pane;
1283
+ try {
1284
+ pane = transport.capturePane(sessionName, VERIFY_PANE_LINES);
1285
+ } catch (err) {
1286
+ return {
1287
+ atCapacity: false,
1288
+ reason: `capture-pane failed: ${err instanceof Error ? err.message : String(err)}`
1289
+ };
1290
+ }
1291
+ const { isAtCapacity: isAtCapacity2 } = await Promise.resolve().then(() => (init_capacity_monitor(), capacity_monitor_exports));
1292
+ if (!isAtCapacity2(pane)) {
1293
+ return {
1294
+ atCapacity: false,
1295
+ reason: `last ${VERIFY_PANE_LINES} lines show normal work, no capacity banner`
1296
+ };
1297
+ }
1298
+ return {
1299
+ atCapacity: true,
1300
+ reason: "capacity banner matched in recent pane output"
1301
+ };
1302
+ }
1303
+ function readDebounceState() {
1304
+ try {
1305
+ if (!existsSync8(DEBOUNCE_FILE)) return {};
1306
+ return JSON.parse(readFileSync8(DEBOUNCE_FILE, "utf8"));
1307
+ } catch {
1308
+ return {};
1309
+ }
1310
+ }
1311
+ function writeDebounceState(state) {
1312
+ try {
1313
+ if (!existsSync8(SESSION_CACHE)) mkdirSync4(SESSION_CACHE, { recursive: true });
1314
+ writeFileSync4(DEBOUNCE_FILE, JSON.stringify(state));
1315
+ } catch {
1316
+ }
1317
+ }
1318
+ function isDebounced(targetSession) {
1319
+ const state = readDebounceState();
1320
+ const lastSent = state[targetSession] ?? 0;
1321
+ return Date.now() - lastSent < INTERCOM_DEBOUNCE_MS;
1322
+ }
1323
+ function recordDebounce(targetSession) {
1324
+ const state = readDebounceState();
1325
+ state[targetSession] = Date.now();
1326
+ const cutoff = Date.now() - DEBOUNCE_CLEANUP_AGE_MS;
1327
+ for (const key of Object.keys(state)) {
1328
+ if ((state[key] ?? 0) < cutoff) delete state[key];
1329
+ }
1330
+ writeDebounceState(state);
1331
+ }
1332
+ function logIntercom(msg) {
1333
+ const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${msg}
1334
+ `;
1335
+ process.stderr.write(`[intercom] ${msg}
1336
+ `);
1337
+ try {
1338
+ appendFileSync(INTERCOM_LOG2, line);
1339
+ } catch {
1340
+ }
1341
+ }
1342
+ function getSessionState(sessionName) {
1343
+ const transport = getTransport();
1344
+ if (!transport.isAlive(sessionName)) return "offline";
1345
+ try {
1346
+ const pane = transport.capturePane(sessionName, 5);
1347
+ if (!pane.includes("\u276F") && !pane.includes("Claude Code") && !BUSY_PATTERN.test(pane) && !/Running…/.test(pane)) {
1348
+ if (/\$\s*$/.test(pane) || /% $/.test(pane.trimEnd())) {
1349
+ return "no_claude";
1350
+ }
1351
+ }
1352
+ if (/Running…/.test(pane)) return "tool";
1353
+ if (BUSY_PATTERN.test(pane)) return "thinking";
1354
+ return "idle";
1355
+ } catch {
1356
+ return "offline";
1357
+ }
1358
+ }
1359
+ function isSessionBusy(sessionName) {
1360
+ const state = getSessionState(sessionName);
1361
+ return state === "thinking" || state === "tool";
1362
+ }
1363
+ function isExeSession(sessionName) {
1364
+ return /^exe\d*$/.test(sessionName);
1365
+ }
1366
+ function sendIntercom(targetSession) {
1367
+ const transport = getTransport();
1368
+ if (isExeSession(targetSession)) {
1369
+ logIntercom(`SKIP_EXE \u2192 ${targetSession} (exe sessions use prompt-submit hook)`);
1370
+ return "skipped_exe";
1371
+ }
1372
+ if (isDebounced(targetSession)) {
1373
+ logIntercom(`DEBOUNCE \u2192 ${targetSession} (cross-process file debounce)`);
1374
+ return "debounced";
1375
+ }
1376
+ try {
1377
+ const sessions = transport.listSessions();
1378
+ if (!sessions.includes(targetSession)) {
1379
+ logIntercom(`SKIP \u2192 ${targetSession} (session not found)`);
1380
+ return "failed";
1381
+ }
1382
+ const sessionState = getSessionState(targetSession);
1383
+ if (sessionState === "no_claude") {
1384
+ queueIntercom(targetSession, "claude not running in session");
1385
+ recordDebounce(targetSession);
1386
+ logIntercom(`QUEUED \u2192 ${targetSession} (no claude process \u2014 raw shell detected)`);
1387
+ return "queued";
1388
+ }
1389
+ if (sessionState === "thinking" || sessionState === "tool") {
1390
+ queueIntercom(targetSession, "session busy at send time");
1391
+ recordDebounce(targetSession);
1392
+ logIntercom(`QUEUED \u2192 ${targetSession} (session busy, will retry from queue)`);
1393
+ return "queued";
1394
+ }
1395
+ if (transport.isPaneInCopyMode(targetSession)) {
1396
+ logIntercom(`COPY_MODE \u2192 ${targetSession} (exiting copy mode first)`);
1397
+ transport.sendKeys(targetSession, "q");
1398
+ }
1399
+ transport.sendKeys(targetSession, "/exe-intercom");
1400
+ recordDebounce(targetSession);
1401
+ logIntercom(`DELIVERED \u2192 ${targetSession} (fire-and-forget)`);
1402
+ return "delivered";
1403
+ } catch {
1404
+ logIntercom(`FAIL \u2192 ${targetSession}`);
1405
+ return "failed";
1406
+ }
1407
+ }
1408
+ function notifyParentExe(sessionKey) {
1409
+ const target = getDispatchedBy(sessionKey);
1410
+ if (!target) {
1411
+ process.stderr.write(`[intercom] notifyParentExe: no dispatcher found for key ${sessionKey}
1412
+ `);
1413
+ return false;
1414
+ }
1415
+ process.stderr.write(`[intercom] notifyParentExe \u2192 ${target}
1416
+ `);
1417
+ const result = sendIntercom(target);
1418
+ if (result === "failed") {
1419
+ const rootExe = resolveExeSession();
1420
+ if (rootExe && rootExe !== target) {
1421
+ process.stderr.write(`[intercom] notifyParentExe: dispatcher ${target} dead, falling back to root exe ${rootExe}
1422
+ `);
1423
+ const fallback = sendIntercom(rootExe);
1424
+ return fallback !== "failed";
1425
+ }
1426
+ return false;
1427
+ }
1428
+ return true;
1429
+ }
1430
+ function ensureEmployee(employeeName, exeSession, projectDir, opts) {
1431
+ if (employeeName === "exe") {
1432
+ return { status: "failed", sessionName: "", error: "exe is the COO, not a dispatchable employee" };
1433
+ }
1434
+ try {
1435
+ assertEmployeeLimitSync();
1436
+ } catch (err) {
1437
+ if (err instanceof PlanLimitError) {
1438
+ return { status: "failed", sessionName: "", error: err.message };
1439
+ }
1440
+ }
1441
+ if (/-exe\d*$/.test(employeeName)) {
1442
+ const bare = employeeName.replace(/-exe\d*$/, "").replace(/\d+$/, "");
1443
+ return {
1444
+ status: "failed",
1445
+ sessionName: "",
1446
+ error: `Error: pass employee name ('${bare}'), not session name ('${employeeName}')`
1447
+ };
1448
+ }
1449
+ if (!/^exe\d+$/.test(exeSession)) {
1450
+ const root = extractRootExe(exeSession);
1451
+ if (root) {
1452
+ process.stderr.write(
1453
+ `[ensureEmployee] WARN: caller passed exeSession="${exeSession}" (not a root exe). Auto-correcting to "${root}".
1454
+ `
1455
+ );
1456
+ exeSession = root;
1457
+ } else {
1458
+ return {
1459
+ status: "failed",
1460
+ sessionName: "",
1461
+ error: `Invalid exeSession "${exeSession}" \u2014 must be a root exe session (e.g., "exe1")`
1462
+ };
1463
+ }
1464
+ }
1465
+ let effectiveInstance = opts?.instance;
1466
+ if (effectiveInstance === void 0 && opts?.autoInstance) {
1467
+ const free = findFreeInstance(
1468
+ employeeName,
1469
+ exeSession,
1470
+ opts.maxAutoInstances ?? 10
1471
+ );
1472
+ if (free === null) {
1473
+ return {
1474
+ status: "failed",
1475
+ sessionName: employeeSessionName(employeeName, exeSession),
1476
+ error: `All ${opts.maxAutoInstances ?? 10} instances of ${employeeName} are alive \u2014 cap reached`
1477
+ };
1478
+ }
1479
+ effectiveInstance = free === 0 ? void 0 : free;
1480
+ }
1481
+ const sessionName = employeeSessionName(employeeName, exeSession, effectiveInstance);
1482
+ if (isEmployeeAlive(sessionName)) {
1483
+ const result2 = sendIntercom(sessionName);
1484
+ if (result2 === "acknowledged" || result2 === "skipped_exe" || result2 === "debounced" || result2 === "queued") {
1485
+ return { status: "intercom_sent", sessionName };
1486
+ }
1487
+ if (result2 === "delivered") {
1488
+ return { status: "intercom_unprocessed", sessionName };
1489
+ }
1490
+ return { status: "failed", sessionName, error: "intercom delivery failed" };
1491
+ }
1492
+ const spawnOpts = { ...opts, instance: effectiveInstance };
1493
+ const result = spawnEmployee(employeeName, exeSession, projectDir, spawnOpts);
1494
+ if (result.error) {
1495
+ return { status: "failed", sessionName, error: result.error };
1496
+ }
1497
+ return { status: "spawned", sessionName };
1498
+ }
1499
+ function spawnEmployee(employeeName, exeSession, projectDir, opts) {
1500
+ const transport = getTransport();
1501
+ const sessionName = employeeSessionName(employeeName, exeSession, opts?.instance);
1502
+ const instanceLabel = opts?.instance != null && opts.instance > 0 ? `${employeeName}${opts.instance}` : employeeName;
1503
+ const logDir = path8.join(os5.homedir(), ".exe-os", "session-logs");
1504
+ const logFile = path8.join(logDir, `${instanceLabel}-${Date.now()}.log`);
1505
+ if (!existsSync8(logDir)) {
1506
+ mkdirSync4(logDir, { recursive: true });
1507
+ }
1508
+ transport.kill(sessionName);
1509
+ let cleanupSuffix = "";
1510
+ try {
1511
+ const thisFile = fileURLToPath(import.meta.url);
1512
+ const cleanupScript = path8.join(path8.dirname(thisFile), "..", "bin", "exe-session-cleanup.js");
1513
+ if (existsSync8(cleanupScript)) {
1514
+ cleanupSuffix = `; ${process.execPath} "${cleanupScript}" "${employeeName}" "${exeSession}"`;
1515
+ }
1516
+ } catch {
1517
+ }
1518
+ try {
1519
+ const claudeJsonPath = path8.join(os5.homedir(), ".claude.json");
1520
+ let claudeJson = {};
1521
+ try {
1522
+ claudeJson = JSON.parse(readFileSync8(claudeJsonPath, "utf8"));
1523
+ } catch {
1524
+ }
1525
+ if (!claudeJson.projects) claudeJson.projects = {};
1526
+ const projects = claudeJson.projects;
1527
+ const trustDir = opts?.cwd ?? projectDir;
1528
+ if (!projects[trustDir]) projects[trustDir] = {};
1529
+ projects[trustDir].hasTrustDialogAccepted = true;
1530
+ writeFileSync4(claudeJsonPath, JSON.stringify(claudeJson, null, 2) + "\n");
1531
+ } catch {
1532
+ }
1533
+ try {
1534
+ const settingsDir = path8.join(os5.homedir(), ".claude", "projects");
1535
+ const normalizedKey = (opts?.cwd ?? projectDir).replace(/\//g, "-").replace(/^-/, "");
1536
+ const projSettingsDir = path8.join(settingsDir, normalizedKey);
1537
+ const settingsPath = path8.join(projSettingsDir, "settings.json");
1538
+ let settings = {};
1539
+ try {
1540
+ settings = JSON.parse(readFileSync8(settingsPath, "utf8"));
1541
+ } catch {
1542
+ }
1543
+ const perms = settings.permissions ?? {};
1544
+ const allow = perms.allow ?? [];
1545
+ const toolNames = [
1546
+ "recall_my_memory",
1547
+ "store_memory",
1548
+ "create_task",
1549
+ "update_task",
1550
+ "list_tasks",
1551
+ "get_task",
1552
+ "ask_team_memory",
1553
+ "store_behavior",
1554
+ "get_identity",
1555
+ "send_message"
1556
+ ];
1557
+ const requiredTools = expandDualPrefixTools(toolNames);
1558
+ let changed = false;
1559
+ for (const tool of requiredTools) {
1560
+ if (!allow.includes(tool)) {
1561
+ allow.push(tool);
1562
+ changed = true;
1563
+ }
1564
+ }
1565
+ if (changed) {
1566
+ perms.allow = allow;
1567
+ settings.permissions = perms;
1568
+ mkdirSync4(projSettingsDir, { recursive: true });
1569
+ writeFileSync4(settingsPath, JSON.stringify(settings, null, 2) + "\n");
1570
+ }
1571
+ } catch {
1572
+ }
1573
+ const spawnCwd = opts?.cwd ?? projectDir;
1574
+ const useExeAgent = !!(opts?.model && opts?.provider);
1575
+ const ccProvider = useExeAgent ? DEFAULT_PROVIDER : detectActiveProvider();
1576
+ const useBinSymlink = ccProvider !== DEFAULT_PROVIDER;
1577
+ let identityFlag = "";
1578
+ let behaviorsFlag = "";
1579
+ let legacyFallbackWarned = false;
1580
+ if (!useExeAgent && !useBinSymlink) {
1581
+ const identityPath = path8.join(
1582
+ os5.homedir(),
1583
+ ".exe-os",
1584
+ "identity",
1585
+ `${employeeName}.md`
1586
+ );
1587
+ _resetCcAgentSupportCache();
1588
+ const hasAgentFlag = claudeSupportsAgentFlag();
1589
+ if (hasAgentFlag) {
1590
+ identityFlag = ` --agent ${employeeName}`;
1591
+ } else if (existsSync8(identityPath)) {
1592
+ identityFlag = ` --append-system-prompt-file ${identityPath}`;
1593
+ legacyFallbackWarned = true;
1594
+ }
1595
+ const behaviorsFile = exportBehaviorsSync(
1596
+ employeeName,
1597
+ path8.basename(spawnCwd),
1598
+ sessionName
1599
+ );
1600
+ if (behaviorsFile) {
1601
+ behaviorsFlag = ` --append-system-prompt-file ${behaviorsFile}`;
1602
+ }
1603
+ }
1604
+ if (legacyFallbackWarned) {
1605
+ process.stderr.write(
1606
+ `[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.
1607
+ `
1608
+ );
1609
+ }
1610
+ let sessionContextFlag = "";
1611
+ try {
1612
+ const ctxDir = path8.join(os5.homedir(), ".exe-os", "session-cache");
1613
+ mkdirSync4(ctxDir, { recursive: true });
1614
+ const ctxFile = path8.join(ctxDir, `session-context-${sessionName}.md`);
1615
+ const ctxContent = [
1616
+ `## Session Context`,
1617
+ `You are running in tmux session: ${sessionName}.`,
1618
+ `Your parent exe session is ${exeSession}.`,
1619
+ `Your employees (if any) use the -${exeSession} suffix (e.g., tom-${exeSession}).`
1620
+ ].join("\n");
1621
+ writeFileSync4(ctxFile, ctxContent);
1622
+ sessionContextFlag = ` --append-system-prompt-file ${ctxFile}`;
1623
+ } catch {
1624
+ }
1625
+ let envPrefix = `EXE_SESSION=${exeSession} EXE_SESSION_NAME=${sessionName}`;
1626
+ if (ccProvider !== DEFAULT_PROVIDER) {
1627
+ const cfg = PROVIDER_TABLE[ccProvider];
1628
+ if (cfg?.apiKeyEnv) {
1629
+ const keyVal = process.env[cfg.apiKeyEnv];
1630
+ if (keyVal) {
1631
+ envPrefix = `${envPrefix} ${cfg.apiKeyEnv}=${keyVal}`;
1632
+ }
1633
+ }
1634
+ }
1635
+ let spawnCommand;
1636
+ if (useExeAgent) {
1637
+ spawnCommand = `${envPrefix} exe-agent --employee ${employeeName} --model ${opts.model} --provider ${opts.provider}${cleanupSuffix}`;
1638
+ } else if (useBinSymlink) {
1639
+ const binName = `${employeeName}-${ccProvider}`;
1640
+ process.stderr.write(
1641
+ `[tmux-routing] provider cascade: ${ccProvider} \u2192 spawning ${binName}
1642
+ `
1643
+ );
1644
+ spawnCommand = `${envPrefix} ${binName}${cleanupSuffix}`;
1645
+ } else {
1646
+ spawnCommand = `${envPrefix} claude --dangerously-skip-permissions${identityFlag}${behaviorsFlag}${sessionContextFlag}${cleanupSuffix}`;
1647
+ }
1648
+ const spawnResult = transport.spawn(sessionName, {
1649
+ cwd: spawnCwd,
1650
+ command: spawnCommand
1651
+ });
1652
+ if (spawnResult.error) {
1653
+ releaseSpawnLock(sessionName);
1654
+ return { sessionName, error: `tmux new-session failed: ${spawnResult.error}` };
1655
+ }
1656
+ transport.pipeLog(sessionName, logFile);
1657
+ try {
1658
+ const mySession = getMySession();
1659
+ const dispatchInfo = path8.join(SESSION_CACHE, `dispatch-info-${sessionName}.json`);
1660
+ writeFileSync4(dispatchInfo, JSON.stringify({
1661
+ dispatchedBy: mySession,
1662
+ rootExe: exeSession,
1663
+ provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
1664
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1665
+ }));
1666
+ } catch {
1667
+ }
1668
+ let booted = false;
1669
+ for (let i = 0; i < 30; i++) {
1670
+ try {
1671
+ execSync4("sleep 0.5");
1672
+ } catch {
1673
+ }
1674
+ try {
1675
+ const pane = transport.capturePane(sessionName);
1676
+ if (useExeAgent) {
1677
+ if (pane.includes("[exe-agent]") || pane.includes("online")) {
1678
+ booted = true;
1679
+ break;
1680
+ }
1681
+ } else {
1682
+ if (pane.includes("Claude Code") || pane.includes("\u276F")) {
1683
+ booted = true;
1684
+ break;
1685
+ }
1686
+ }
1687
+ } catch {
1688
+ }
1689
+ }
1690
+ if (!booted) {
1691
+ releaseSpawnLock(sessionName);
1692
+ return { sessionName, error: `${useExeAgent ? "exe-agent" : "claude"} did not boot within 15s` };
1693
+ }
1694
+ if (!useExeAgent) {
1695
+ try {
1696
+ transport.sendKeys(sessionName, `/exe-call ${employeeName}`);
1697
+ } catch {
1698
+ }
1699
+ }
1700
+ registerSession({
1701
+ windowName: sessionName,
1702
+ agentId: employeeName,
1703
+ projectDir: spawnCwd,
1704
+ parentExe: exeSession,
1705
+ pid: 0,
1706
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString()
1707
+ });
1708
+ releaseSpawnLock(sessionName);
1709
+ return { sessionName };
1710
+ }
1711
+ 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;
1712
+ var init_tmux_routing = __esm({
1713
+ "src/lib/tmux-routing.ts"() {
1714
+ "use strict";
1715
+ init_session_registry();
1716
+ init_session_key();
1717
+ init_transport();
1718
+ init_cc_agent_support();
1719
+ init_mcp_prefix();
1720
+ init_provider_table();
1721
+ init_intercom_queue();
1722
+ init_plan_limits();
1723
+ SPAWN_LOCK_DIR = path8.join(os5.homedir(), ".exe-os", "spawn-locks");
1724
+ SESSION_CACHE = path8.join(os5.homedir(), ".exe-os", "session-cache");
1725
+ BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
1726
+ VALID_SESSION_NAME = /^[a-z]+-exe\d+$|^[a-z]+\d+-exe\d+$/;
1727
+ VERIFY_PANE_LINES = 200;
1728
+ INTERCOM_DEBOUNCE_MS = 3e4;
1729
+ INTERCOM_LOG2 = path8.join(os5.homedir(), ".exe-os", "intercom.log");
1730
+ DEBOUNCE_FILE = path8.join(SESSION_CACHE, "intercom-debounce.json");
1731
+ DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
1732
+ BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
1733
+ }
1734
+ });
1735
+
1736
+ // src/lib/tasks-crud.ts
1737
+ import crypto3 from "crypto";
1738
+ import path9 from "path";
1739
+ import { execSync as execSync5 } from "child_process";
1740
+ import { mkdir as mkdir3, writeFile as writeFile3, appendFile } from "fs/promises";
1741
+ import { existsSync as existsSync9, readFileSync as readFileSync9 } from "fs";
1742
+ async function writeCheckpoint(input) {
1743
+ const client = getClient();
1744
+ const row = await resolveTask(client, input.taskId);
1745
+ const taskId = String(row.id);
1746
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1747
+ const blockedByIds = [];
1748
+ if (row.blocked_by) {
1749
+ blockedByIds.push(String(row.blocked_by));
1750
+ }
1751
+ const checkpoint = {
1752
+ step: input.step,
1753
+ context_summary: input.contextSummary,
1754
+ files_touched: input.filesTouched ?? [],
1755
+ blocked_by_ids: blockedByIds,
1756
+ last_checkpoint_at: now
1757
+ };
1758
+ const result = await client.execute({
1759
+ sql: `UPDATE tasks SET checkpoint = ?, checkpoint_count = checkpoint_count + 1, updated_at = ? WHERE id = ?`,
1760
+ args: [JSON.stringify(checkpoint), now, taskId]
1761
+ });
1762
+ if (result.rowsAffected === 0) {
1763
+ throw new Error(`Checkpoint write failed: task ${taskId} not found`);
1764
+ }
1765
+ const countResult = await client.execute({
1766
+ sql: "SELECT checkpoint_count FROM tasks WHERE id = ?",
1767
+ args: [taskId]
1768
+ });
1769
+ const checkpointCount = Number(countResult.rows[0]?.checkpoint_count ?? 1);
1770
+ return { checkpointCount };
1771
+ }
1772
+ function extractParentFromContext(contextBody) {
1773
+ if (!contextBody) return null;
1774
+ const match = contextBody.match(
1775
+ /Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
1776
+ );
1777
+ return match ? match[1].toLowerCase() : null;
1778
+ }
1779
+ function slugify(title) {
1780
+ return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
1781
+ }
1782
+ async function resolveTask(client, identifier) {
1783
+ let result = await client.execute({
1784
+ sql: "SELECT * FROM tasks WHERE id = ?",
1785
+ args: [identifier]
1786
+ });
1787
+ if (result.rows.length === 1) return result.rows[0];
1788
+ result = await client.execute({
1789
+ sql: "SELECT * FROM tasks WHERE task_file LIKE ?",
1790
+ args: [`%${identifier}%`]
1791
+ });
1792
+ if (result.rows.length === 1) return result.rows[0];
1793
+ if (result.rows.length > 1) {
1794
+ const exact = result.rows.filter(
1795
+ (r) => String(r.task_file).endsWith(`/${identifier}.md`)
1796
+ );
1797
+ if (exact.length === 1) return exact[0];
1798
+ const candidates = exact.length > 1 ? exact : result.rows;
1799
+ const active = candidates.filter(
1800
+ (r) => !["done", "cancelled"].includes(String(r.status))
1801
+ );
1802
+ if (active.length === 1) return active[0];
1803
+ const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
1804
+ throw new Error(
1805
+ `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
1806
+ );
1807
+ }
1808
+ result = await client.execute({
1809
+ sql: "SELECT * FROM tasks WHERE title LIKE ?",
1810
+ args: [`%${identifier}%`]
1811
+ });
1812
+ if (result.rows.length === 1) return result.rows[0];
1813
+ if (result.rows.length > 1) {
1814
+ const active = result.rows.filter(
1815
+ (r) => !["done", "cancelled"].includes(String(r.status))
1816
+ );
1817
+ if (active.length === 1) return active[0];
1818
+ const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
1819
+ throw new Error(
1820
+ `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
1821
+ );
1822
+ }
1823
+ throw new Error(`Task not found: ${identifier}`);
1824
+ }
1825
+ async function createTaskCore(input) {
1826
+ const client = getClient();
1827
+ const id = crypto3.randomUUID();
1828
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1829
+ const slug = slugify(input.title);
1830
+ const taskFile = input.taskFile ?? `exe/${input.assignedTo}/${slug}.md`;
1831
+ let blockedById = null;
1832
+ const initialStatus = input.blockedBy ? "blocked" : "open";
1833
+ if (input.blockedBy) {
1834
+ const blocker = await resolveTask(client, input.blockedBy);
1835
+ blockedById = String(blocker.id);
1836
+ }
1837
+ let parentTaskId = null;
1838
+ let parentRef = input.parentTaskId;
1839
+ if (!parentRef) {
1840
+ const extracted = extractParentFromContext(input.context);
1841
+ if (extracted) {
1842
+ parentRef = extracted;
1843
+ process.stderr.write(
1844
+ "[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
1845
+ );
1846
+ }
1847
+ }
1848
+ if (parentRef) {
1849
+ try {
1850
+ const parent = await resolveTask(client, parentRef);
1851
+ parentTaskId = String(parent.id);
1852
+ } catch (err) {
1853
+ if (!input.parentTaskId) {
1854
+ throw new Error(
1855
+ `create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
1856
+ );
1857
+ }
1858
+ throw err;
1859
+ }
1860
+ }
1861
+ let warning;
1862
+ const dupCheck = await client.execute({
1863
+ sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
1864
+ args: [input.title, input.assignedTo]
1865
+ });
1866
+ if (dupCheck.rows.length > 0) {
1867
+ warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
1868
+ }
1869
+ if (input.baseDir) {
1870
+ try {
1871
+ await mkdir3(path9.join(input.baseDir, "exe", "output"), { recursive: true });
1872
+ await mkdir3(path9.join(input.baseDir, "exe", "research"), { recursive: true });
1873
+ await ensureArchitectureDoc(input.baseDir, input.projectName);
1874
+ await ensureGitignoreExe(input.baseDir);
1875
+ } catch {
1876
+ }
1877
+ }
1878
+ const complexity = input.complexity ?? "standard";
1879
+ let sessionScope = null;
1880
+ try {
1881
+ const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
1882
+ sessionScope = resolveExeSession2();
1883
+ } catch {
1884
+ }
1885
+ await client.execute({
1886
+ 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)
1887
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1888
+ args: [
1889
+ id,
1890
+ input.title,
1891
+ input.assignedTo,
1892
+ input.assignedBy,
1893
+ input.projectName,
1894
+ input.priority,
1895
+ initialStatus,
1896
+ taskFile,
1897
+ blockedById,
1898
+ parentTaskId,
1899
+ input.reviewer ?? null,
1900
+ input.context,
1901
+ complexity,
1902
+ input.budgetTokens ?? null,
1903
+ input.budgetFallbackModel ?? null,
1904
+ 0,
1905
+ null,
1906
+ sessionScope,
1907
+ now,
1908
+ now
1909
+ ]
1910
+ });
1911
+ return {
1912
+ id,
1913
+ title: input.title,
1914
+ assignedTo: input.assignedTo,
1915
+ assignedBy: input.assignedBy,
1916
+ projectName: input.projectName,
1917
+ priority: input.priority,
1918
+ status: initialStatus,
1919
+ taskFile,
1920
+ createdAt: now,
1921
+ updatedAt: now,
1922
+ warning,
1923
+ budgetTokens: input.budgetTokens ?? null,
1924
+ budgetFallbackModel: input.budgetFallbackModel ?? null,
1925
+ tokensUsed: 0,
1926
+ tokensWarnedAt: null
1927
+ };
1928
+ }
1929
+ async function listTasks(input) {
1930
+ const client = getClient();
1931
+ const conditions = [];
1932
+ const args = [];
1933
+ if (input.assignedTo) {
1934
+ conditions.push("assigned_to = ?");
1935
+ args.push(input.assignedTo);
1936
+ }
1937
+ if (input.status) {
1938
+ conditions.push("status = ?");
1939
+ args.push(input.status);
1940
+ } else {
1941
+ conditions.push("status IN ('open', 'in_progress', 'blocked')");
1942
+ }
1943
+ if (input.projectName) {
1944
+ conditions.push("project_name = ?");
1945
+ args.push(input.projectName);
1946
+ }
1947
+ if (input.priority) {
1948
+ conditions.push("priority = ?");
1949
+ args.push(input.priority);
1950
+ }
1951
+ try {
1952
+ const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
1953
+ const session = resolveExeSession2();
1954
+ if (session) {
1955
+ conditions.push("(session_scope IS NULL OR session_scope = ?)");
1956
+ args.push(session);
1957
+ }
1958
+ } catch {
1959
+ }
1960
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1961
+ const result = await client.execute({
1962
+ 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`,
1963
+ args
1964
+ });
1965
+ return result.rows.map((r) => ({
1966
+ id: String(r.id),
1967
+ title: String(r.title),
1968
+ assignedTo: String(r.assigned_to),
1969
+ assignedBy: String(r.assigned_by),
1970
+ projectName: String(r.project_name),
1971
+ priority: String(r.priority),
1972
+ status: String(r.status),
1973
+ taskFile: String(r.task_file),
1974
+ createdAt: String(r.created_at),
1975
+ updatedAt: String(r.updated_at),
1976
+ checkpointCount: Number(r.checkpoint_count ?? 0),
1977
+ budgetTokens: r.budget_tokens !== null ? Number(r.budget_tokens) : null,
1978
+ budgetFallbackModel: r.budget_fallback_model !== null ? String(r.budget_fallback_model) : null,
1979
+ tokensUsed: Number(r.tokens_used ?? 0),
1980
+ tokensWarnedAt: r.tokens_warned_at !== null ? Number(r.tokens_warned_at) : null
1981
+ }));
1982
+ }
1983
+ function checkStaleCompletion(taskContext, taskCreatedAt) {
1984
+ if (!taskContext) return null;
1985
+ if (!DELEGATION_KEYWORDS.test(taskContext)) return null;
1986
+ try {
1987
+ const since = new Date(taskCreatedAt).toISOString();
1988
+ const branch = execSync5(
1989
+ "git rev-parse --abbrev-ref HEAD 2>/dev/null",
1990
+ { encoding: "utf8", timeout: 3e3 }
1991
+ ).trim();
1992
+ const branchArg = branch && branch !== "HEAD" ? branch : "";
1993
+ const commitCount = execSync5(
1994
+ `git log --oneline --since="${since}" ${branchArg} 2>/dev/null | wc -l`,
1995
+ { encoding: "utf8", timeout: 5e3 }
1996
+ ).trim();
1997
+ const count = parseInt(commitCount, 10);
1998
+ if (count === 0) {
1999
+ return "WARNING: task closed with no new commits since creation. Verify work was actually produced.";
2000
+ }
2001
+ return null;
2002
+ } catch {
2003
+ return null;
2004
+ }
2005
+ }
2006
+ async function updateTaskStatus(input) {
2007
+ const client = getClient();
2008
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2009
+ const row = await resolveTask(client, input.taskId);
2010
+ const taskId = String(row.id);
2011
+ const taskFile = String(row.task_file);
2012
+ if (input.status === "done" && String(row.assigned_by) === "system" && taskFile.includes("review-")) {
2013
+ process.stderr.write(
2014
+ `[updateTask] Review task "${String(row.title)}" being marked done (assigned to ${String(row.assigned_to)})
2015
+ `
2016
+ );
2017
+ }
2018
+ if (input.status === "done") {
2019
+ const existingRow = await client.execute({
2020
+ sql: "SELECT context, created_at FROM tasks WHERE id = ?",
2021
+ args: [taskId]
2022
+ });
2023
+ if (existingRow.rows.length > 0) {
2024
+ const ctx = existingRow.rows[0];
2025
+ const warning = checkStaleCompletion(ctx.context, ctx.created_at);
2026
+ if (warning) {
2027
+ input.result = input.result ? `\u26A0\uFE0F ${warning}
2028
+
2029
+ ${input.result}` : `\u26A0\uFE0F ${warning}`;
2030
+ process.stderr.write(`[tasks] ${warning} (task: ${taskId})
2031
+ `);
2032
+ }
2033
+ }
2034
+ }
2035
+ if (input.status === "in_progress") {
2036
+ const tmuxSession = process.env.TMUX_PANE ?? process.env.MY_TMUX_SESSION ?? "unknown";
2037
+ const claim = await client.execute({
2038
+ sql: `UPDATE tasks
2039
+ SET status = 'in_progress', assigned_tmux = ?, updated_at = ?
2040
+ WHERE id = ? AND status = 'open'`,
2041
+ args: [tmuxSession, now, taskId]
2042
+ });
2043
+ if (claim.rowsAffected === 0) {
2044
+ const current = await client.execute({
2045
+ sql: "SELECT status, assigned_tmux FROM tasks WHERE id = ?",
2046
+ args: [taskId]
2047
+ });
2048
+ const cur = current.rows[0];
2049
+ const status = cur?.status ?? "unknown";
2050
+ const claimedBy = cur?.assigned_tmux ? ` (claimed by ${cur.assigned_tmux})` : "";
2051
+ throw new Error(`${TASK_ALREADY_CLAIMED_PREFIX}: task ${taskId} is ${status}${claimedBy}`);
2052
+ }
2053
+ try {
2054
+ await writeCheckpoint({
2055
+ taskId,
2056
+ step: "claimed",
2057
+ contextSummary: `Task claimed by session. Transitioning open \u2192 in_progress.`
2058
+ });
2059
+ } catch {
2060
+ }
2061
+ return { row, taskFile, now, taskId };
2062
+ }
2063
+ if (input.result) {
2064
+ await client.execute({
2065
+ sql: "UPDATE tasks SET status = ?, result = ?, updated_at = ? WHERE id = ?",
2066
+ args: [input.status, input.result, now, taskId]
2067
+ });
2068
+ } else {
2069
+ await client.execute({
2070
+ sql: "UPDATE tasks SET status = ?, updated_at = ? WHERE id = ?",
2071
+ args: [input.status, now, taskId]
2072
+ });
2073
+ }
2074
+ try {
2075
+ await writeCheckpoint({
2076
+ taskId,
2077
+ step: `status_transition:${input.status}`,
2078
+ contextSummary: input.result ? `Transitioned to ${input.status}. Result: ${input.result.slice(0, 500)}` : `Transitioned to ${input.status}.`
2079
+ });
2080
+ } catch {
2081
+ }
2082
+ return { row, taskFile, now, taskId };
2083
+ }
2084
+ async function deleteTaskCore(taskId, _baseDir) {
2085
+ const client = getClient();
2086
+ const row = await resolveTask(client, taskId);
2087
+ const id = String(row.id);
2088
+ const taskFile = String(row.task_file);
2089
+ const assignedTo = String(row.assigned_to);
2090
+ const assignedBy = String(row.assigned_by);
2091
+ await client.execute({ sql: "DELETE FROM tasks WHERE id = ?", args: [id] });
2092
+ const taskSlug = taskFile.split("/").pop()?.replace(".md", "") ?? "";
2093
+ return { taskFile, assignedTo, assignedBy, taskSlug };
2094
+ }
2095
+ async function ensureArchitectureDoc(baseDir, projectName) {
2096
+ const archPath = path9.join(baseDir, "exe", "ARCHITECTURE.md");
2097
+ try {
2098
+ if (existsSync9(archPath)) return;
2099
+ const template = [
2100
+ `# ${projectName} \u2014 System Architecture`,
2101
+ "",
2102
+ "> Employees: read this before every task. Update it when you change system structure.",
2103
+ `> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
2104
+ "",
2105
+ "## Overview",
2106
+ "",
2107
+ "<!-- Describe what this system does, its main components, and how they connect. -->",
2108
+ "",
2109
+ "## Key Components",
2110
+ "",
2111
+ "<!-- List the major modules, services, or subsystems. -->",
2112
+ "",
2113
+ "## Data Flow",
2114
+ "",
2115
+ "<!-- How does data move through the system? What writes where? -->",
2116
+ "",
2117
+ "## Invariants",
2118
+ "",
2119
+ "<!-- Rules that must never be violated. What breaks if these are wrong? -->",
2120
+ "",
2121
+ "## Dependencies",
2122
+ "",
2123
+ "<!-- What depends on what? If I change X, what else is affected? -->",
2124
+ ""
2125
+ ].join("\n");
2126
+ await writeFile3(archPath, template, "utf-8");
2127
+ } catch {
2128
+ }
2129
+ }
2130
+ async function ensureGitignoreExe(baseDir) {
2131
+ const gitignorePath = path9.join(baseDir, ".gitignore");
2132
+ try {
2133
+ if (existsSync9(gitignorePath)) {
2134
+ const content = readFileSync9(gitignorePath, "utf-8");
2135
+ if (/^\/?exe\/?$/m.test(content)) return;
2136
+ await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
2137
+ } else {
2138
+ await writeFile3(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
2139
+ }
2140
+ } catch {
2141
+ }
2142
+ }
2143
+ var DELEGATION_KEYWORDS, TASK_ALREADY_CLAIMED_PREFIX;
2144
+ var init_tasks_crud = __esm({
2145
+ "src/lib/tasks-crud.ts"() {
2146
+ "use strict";
2147
+ init_database();
2148
+ DELEGATION_KEYWORDS = /parallel|delegate|wave|tom\d*-exe/i;
2149
+ TASK_ALREADY_CLAIMED_PREFIX = "TASK_ALREADY_CLAIMED";
2150
+ }
2151
+ });
2152
+
2153
+ // src/lib/tasks-review.ts
2154
+ import path10 from "path";
2155
+ import { existsSync as existsSync10, readdirSync as readdirSync2, unlinkSync as unlinkSync3 } from "fs";
2156
+ async function countPendingReviews() {
2157
+ const client = getClient();
2158
+ const result = await client.execute({
2159
+ sql: "SELECT COUNT(*) as cnt FROM tasks WHERE status = 'needs_review'",
2160
+ args: []
2161
+ });
2162
+ return Number(result.rows[0]?.cnt) || 0;
2163
+ }
2164
+ async function countNewPendingReviewsSince(sinceIso) {
2165
+ const client = getClient();
2166
+ const result = await client.execute({
2167
+ sql: `SELECT COUNT(*) as cnt FROM tasks
2168
+ WHERE status = 'needs_review' AND updated_at > ?`,
2169
+ args: [sinceIso]
2170
+ });
2171
+ return Number(result.rows[0]?.cnt) || 0;
2172
+ }
2173
+ async function listPendingReviews(limit) {
2174
+ const client = getClient();
2175
+ const result = await client.execute({
2176
+ sql: `SELECT title, assigned_to, project_name FROM tasks
2177
+ WHERE status = 'needs_review'
2178
+ ORDER BY priority ASC, created_at DESC LIMIT ?`,
2179
+ args: [limit]
2180
+ });
2181
+ return result.rows;
2182
+ }
2183
+ async function cleanupOrphanedReviews() {
2184
+ const client = getClient();
2185
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2186
+ const r1 = await client.execute({
2187
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
2188
+ WHERE status = 'needs_review'
2189
+ AND assigned_by = 'system'
2190
+ AND title LIKE 'Review:%'
2191
+ AND parent_task_id IN (SELECT id FROM tasks WHERE status IN ('done', 'cancelled'))`,
2192
+ args: [now]
2193
+ });
2194
+ const staleThreshold = new Date(Date.now() - 60 * 60 * 1e3).toISOString();
2195
+ const r2 = await client.execute({
2196
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
2197
+ WHERE status = 'needs_review'
2198
+ AND result IS NOT NULL
2199
+ AND updated_at < ?`,
2200
+ args: [now, staleThreshold]
2201
+ });
2202
+ const total = r1.rowsAffected + r2.rowsAffected;
2203
+ if (total > 0) {
2204
+ process.stderr.write(
2205
+ `[cleanup] Closed ${total} orphaned review(s): ${r1.rowsAffected} cascade + ${r2.rowsAffected} stale
2206
+ `
2207
+ );
2208
+ }
2209
+ return total;
2210
+ }
2211
+ function getReviewChecklist(role, agent, taskSlug) {
2212
+ const roleLower = role.toLowerCase();
2213
+ if (roleLower.includes("engineer") || roleLower === "principal engineer") {
2214
+ return {
2215
+ lens: "Code Quality (Engineer)",
2216
+ checklist: [
2217
+ "1. Do all tests pass? Any new tests needed?",
2218
+ "2. Is the code clean \u2014 no dead code, no TODOs left?",
2219
+ "3. Does it follow existing patterns and conventions in the codebase?",
2220
+ "4. Any regressions in the test suite?"
2221
+ ]
2222
+ };
2223
+ }
2224
+ if (roleLower === "cto" || roleLower.includes("architect")) {
2225
+ return {
2226
+ lens: "Architecture (CTO)",
2227
+ checklist: [
2228
+ "1. Does this fit the existing architecture? Consistent with ARCHITECTURE.md?",
2229
+ "2. Is it backward compatible? Any breaking changes?",
2230
+ "3. Does it introduce technical debt? Is that debt justified?",
2231
+ "4. Security implications? Any new attack surface?",
2232
+ "5. Does it scale? Performance considerations?",
2233
+ "6. Coordination: does this affect other employees' work or other projects?"
2234
+ ]
2235
+ };
2236
+ }
2237
+ if (roleLower === "coo" || roleLower.includes("operations")) {
2238
+ return {
2239
+ lens: "Strategic (COO)",
2240
+ checklist: [
2241
+ "1. Does this serve the project mission?",
2242
+ "2. Is this the right work at the right time?",
2243
+ "3. Does the architectural assessment make sense for the business?",
2244
+ "4. Any cross-project implications?"
2245
+ ]
2246
+ };
2247
+ }
2248
+ return {
2249
+ lens: "General",
2250
+ checklist: [
2251
+ "1. Read the original task's acceptance criteria",
2252
+ `2. Check git log for related commits: \`git log --oneline --author-date-order -10\``,
2253
+ "3. Verify code changes match requirements",
2254
+ "4. Check if tests were added/updated",
2255
+ `5. Look for output files in exe/output/${agent}-${taskSlug}*`
2256
+ ]
2257
+ };
2258
+ }
2259
+ async function cleanupReviewFile(row, taskFile, _baseDir) {
2260
+ if (String(row.assigned_by) !== "system" || !taskFile.includes("review-")) return;
2261
+ try {
2262
+ const client = getClient();
2263
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2264
+ const parentId = row.parent_task_id ? String(row.parent_task_id) : null;
2265
+ if (parentId) {
2266
+ const result = await client.execute({
2267
+ sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ? AND status = 'needs_review'",
2268
+ args: [now, parentId]
2269
+ });
2270
+ if (result.rowsAffected > 0) {
2271
+ process.stderr.write(
2272
+ `[review-cleanup] Cascaded original task to done via parent_task_id: ${parentId}
2273
+ `
2274
+ );
2275
+ }
2276
+ } else {
2277
+ const fileName = taskFile.split("/").pop() ?? "";
2278
+ const reviewPrefix = fileName.replace(".md", "");
2279
+ const parts = reviewPrefix.split("-");
2280
+ if (parts.length >= 3 && parts[0] === "review") {
2281
+ const agent = parts[1];
2282
+ const slug = parts.slice(2).join("-");
2283
+ const originalTaskFile = `exe/${agent}/${slug}.md`;
2284
+ const result = await client.execute({
2285
+ sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE task_file = ? AND status = 'needs_review'",
2286
+ args: [now, originalTaskFile]
2287
+ });
2288
+ if (result.rowsAffected > 0) {
2289
+ process.stderr.write(
2290
+ `[review-cleanup] Cascaded original task to done (legacy path): ${originalTaskFile}
2291
+ `
2292
+ );
2293
+ }
2294
+ }
2295
+ }
2296
+ } catch (err) {
2297
+ process.stderr.write(
2298
+ `[review-cleanup] Failed to cascade original task: ${err instanceof Error ? err.message : String(err)}
2299
+ `
2300
+ );
2301
+ }
2302
+ try {
2303
+ const cacheDir = path10.join(EXE_AI_DIR, "session-cache");
2304
+ if (existsSync10(cacheDir)) {
2305
+ for (const f of readdirSync2(cacheDir)) {
2306
+ if (f.startsWith("review-notified-")) {
2307
+ unlinkSync3(path10.join(cacheDir, f));
2308
+ }
2309
+ }
2310
+ }
2311
+ } catch {
2312
+ }
2313
+ }
2314
+ var init_tasks_review = __esm({
2315
+ "src/lib/tasks-review.ts"() {
371
2316
  "use strict";
2317
+ init_database();
2318
+ init_config();
2319
+ init_employees();
2320
+ init_notifications();
2321
+ init_tasks_crud();
372
2322
  init_tmux_routing();
373
2323
  init_session_key();
374
- init_notifications();
375
- init_transport();
376
- init_employees();
2324
+ init_state_bus();
377
2325
  }
378
2326
  });
379
2327
 
380
- // src/lib/tasks.ts
381
- import path12 from "path";
382
- import { writeFileSync as writeFileSync3, mkdirSync as mkdirSync3, unlinkSync as unlinkSync3 } from "fs";
383
- var init_tasks = __esm({
384
- "src/lib/tasks.ts"() {
2328
+ // src/lib/tasks-chain.ts
2329
+ import path11 from "path";
2330
+ import { readFile as readFile3, writeFile as writeFile4 } from "fs/promises";
2331
+ async function cascadeUnblock(taskId, baseDir, now) {
2332
+ const client = getClient();
2333
+ const unblocked = await client.execute({
2334
+ sql: `UPDATE tasks SET status = 'open', blocked_by = NULL, updated_at = ?
2335
+ WHERE blocked_by = ? AND status = 'blocked'`,
2336
+ args: [now, taskId]
2337
+ });
2338
+ if (baseDir && unblocked.rowsAffected > 0) {
2339
+ const unblockedRows = await client.execute({
2340
+ sql: `SELECT task_file FROM tasks WHERE blocked_by IS NULL AND updated_at = ?`,
2341
+ args: [now]
2342
+ });
2343
+ for (const ur of unblockedRows.rows) {
2344
+ try {
2345
+ const ubFile = path11.join(baseDir, String(ur.task_file));
2346
+ let ubContent = await readFile3(ubFile, "utf-8");
2347
+ ubContent = ubContent.replace(/\*\*Status:\*\* blocked/, "**Status:** open");
2348
+ ubContent = ubContent.replace(/\n\*\*Blocked by:\*\*.*\n/, "\n");
2349
+ await writeFile4(ubFile, ubContent, "utf-8");
2350
+ } catch {
2351
+ }
2352
+ }
2353
+ }
2354
+ }
2355
+ async function findNextTask(assignedTo) {
2356
+ const client = getClient();
2357
+ const nextResult = await client.execute({
2358
+ sql: `SELECT title, task_file, priority FROM tasks
2359
+ WHERE assigned_to = ? AND status = 'open'
2360
+ ORDER BY priority ASC, created_at ASC
2361
+ LIMIT 1`,
2362
+ args: [assignedTo]
2363
+ });
2364
+ if (nextResult.rows.length === 1) {
2365
+ const nr = nextResult.rows[0];
2366
+ return {
2367
+ title: String(nr.title),
2368
+ priority: String(nr.priority),
2369
+ taskFile: String(nr.task_file)
2370
+ };
2371
+ }
2372
+ return void 0;
2373
+ }
2374
+ async function checkSubtaskCompletion(parentTaskId, projectName) {
2375
+ const client = getClient();
2376
+ const remaining = await client.execute({
2377
+ sql: `SELECT COUNT(*) as cnt FROM tasks
2378
+ WHERE parent_task_id = ? AND status NOT IN ('done', 'cancelled')`,
2379
+ args: [parentTaskId]
2380
+ });
2381
+ const cnt = Number(remaining.rows[0]?.cnt ?? 1);
2382
+ if (cnt === 0) {
2383
+ const parentRow = await client.execute({
2384
+ sql: `SELECT assigned_to, title, task_file, project_name FROM tasks WHERE id = ?`,
2385
+ args: [parentTaskId]
2386
+ });
2387
+ if (parentRow.rows.length === 1) {
2388
+ const pr = parentRow.rows[0];
2389
+ const parentProject = pr.project_name == null ? projectName : String(pr.project_name);
2390
+ await writeNotification({
2391
+ agentId: String(pr.assigned_to),
2392
+ agentRole: "system",
2393
+ event: "subtasks_complete",
2394
+ project: parentProject,
2395
+ summary: `All subtasks complete for "${String(pr.title)}" \u2014 ready for rollup review`,
2396
+ taskFile: String(pr.task_file)
2397
+ });
2398
+ }
2399
+ }
2400
+ }
2401
+ var init_tasks_chain = __esm({
2402
+ "src/lib/tasks-chain.ts"() {
385
2403
  "use strict";
386
2404
  init_database();
387
- init_config();
388
2405
  init_notifications();
389
- init_tasks_crud();
390
- init_tasks_review();
391
- init_tasks_crud();
392
- init_tasks_chain();
393
- init_tasks_review();
394
- init_tasks_notify();
395
2406
  }
396
2407
  });
397
2408
 
398
2409
  // src/lib/project-name.ts
399
- import { execSync as execSync5 } from "child_process";
400
- import path13 from "path";
2410
+ import { execSync as execSync6 } from "child_process";
2411
+ import path12 from "path";
401
2412
  function getProjectName(cwd) {
402
2413
  const dir = cwd ?? process.cwd();
403
- if (_cached && _cachedCwd === dir) return _cached;
2414
+ if (_cached2 && _cachedCwd === dir) return _cached2;
404
2415
  try {
405
2416
  let repoRoot;
406
2417
  try {
407
- const gitCommonDir = execSync5("git rev-parse --path-format=absolute --git-common-dir", {
2418
+ const gitCommonDir = execSync6("git rev-parse --path-format=absolute --git-common-dir", {
408
2419
  cwd: dir,
409
2420
  encoding: "utf8",
410
2421
  timeout: 2e3,
411
2422
  stdio: ["pipe", "pipe", "pipe"]
412
2423
  }).trim();
413
- repoRoot = path13.dirname(gitCommonDir);
2424
+ repoRoot = path12.dirname(gitCommonDir);
414
2425
  } catch {
415
- repoRoot = execSync5("git rev-parse --show-toplevel", {
2426
+ repoRoot = execSync6("git rev-parse --show-toplevel", {
416
2427
  cwd: dir,
417
2428
  encoding: "utf8",
418
2429
  timeout: 2e3,
419
2430
  stdio: ["pipe", "pipe", "pipe"]
420
2431
  }).trim();
421
2432
  }
422
- _cached = path13.basename(repoRoot);
2433
+ _cached2 = path12.basename(repoRoot);
423
2434
  _cachedCwd = dir;
424
- return _cached;
2435
+ return _cached2;
425
2436
  } catch {
426
- _cached = path13.basename(dir);
2437
+ _cached2 = path12.basename(dir);
427
2438
  _cachedCwd = dir;
428
- return _cached;
2439
+ return _cached2;
429
2440
  }
430
2441
  }
431
- var _cached, _cachedCwd;
2442
+ var _cached2, _cachedCwd;
432
2443
  var init_project_name = __esm({
433
2444
  "src/lib/project-name.ts"() {
434
2445
  "use strict";
435
- _cached = null;
2446
+ _cached2 = null;
436
2447
  _cachedCwd = null;
437
2448
  }
438
2449
  });
439
2450
 
2451
+ // src/lib/session-scope.ts
2452
+ var session_scope_exports = {};
2453
+ __export(session_scope_exports, {
2454
+ assertSessionScope: () => assertSessionScope,
2455
+ findSessionForProject: () => findSessionForProject,
2456
+ getSessionProject: () => getSessionProject
2457
+ });
2458
+ function getSessionProject(sessionName) {
2459
+ const sessions = listSessions();
2460
+ const entry = sessions.find((s) => s.windowName === sessionName);
2461
+ if (!entry) return null;
2462
+ const parts = entry.projectDir.split("/").filter(Boolean);
2463
+ return parts[parts.length - 1] ?? null;
2464
+ }
2465
+ function findSessionForProject(projectName) {
2466
+ const sessions = listSessions();
2467
+ for (const s of sessions) {
2468
+ const proj = s.projectDir.split("/").filter(Boolean).pop();
2469
+ if (proj === projectName && s.agentId === "exe") return s;
2470
+ }
2471
+ return null;
2472
+ }
2473
+ function assertSessionScope(actionType, targetProject) {
2474
+ try {
2475
+ const currentProject = getProjectName();
2476
+ const exeSession = resolveExeSession();
2477
+ if (!exeSession) {
2478
+ return { allowed: true, reason: "no_session" };
2479
+ }
2480
+ if (currentProject === targetProject) {
2481
+ return {
2482
+ allowed: true,
2483
+ reason: "same_session",
2484
+ currentProject,
2485
+ targetProject
2486
+ };
2487
+ }
2488
+ process.stderr.write(
2489
+ `[session-scope] BLOCKED cross-project ${actionType}: session project="${currentProject}" \u2260 target project="${targetProject}"
2490
+ `
2491
+ );
2492
+ return {
2493
+ allowed: false,
2494
+ reason: "cross_session_denied",
2495
+ currentProject,
2496
+ targetProject,
2497
+ targetSession: findSessionForProject(targetProject)?.windowName
2498
+ };
2499
+ } catch {
2500
+ return { allowed: true, reason: "no_session" };
2501
+ }
2502
+ }
2503
+ var init_session_scope = __esm({
2504
+ "src/lib/session-scope.ts"() {
2505
+ "use strict";
2506
+ init_session_registry();
2507
+ init_project_name();
2508
+ init_tmux_routing();
2509
+ }
2510
+ });
2511
+
2512
+ // src/lib/tasks-notify.ts
2513
+ async function dispatchTaskToEmployee(input) {
2514
+ if (input.assignedTo === "exe") return { dispatched: "skipped" };
2515
+ let crossProject = false;
2516
+ if (input.projectName) {
2517
+ try {
2518
+ const { assertSessionScope: assertSessionScope2 } = (init_session_scope(), __toCommonJS(session_scope_exports));
2519
+ const check = assertSessionScope2("dispatch_task", input.projectName);
2520
+ if (check.reason === "cross_session_denied") {
2521
+ crossProject = true;
2522
+ return { dispatched: "skipped", crossProject: true };
2523
+ }
2524
+ } catch {
2525
+ }
2526
+ }
2527
+ try {
2528
+ const transport = getTransport();
2529
+ const exeSession = resolveExeSession();
2530
+ if (!exeSession) return { dispatched: "session_missing" };
2531
+ const sessionName = employeeSessionName(input.assignedTo, exeSession);
2532
+ if (transport.isAlive(sessionName)) {
2533
+ const result = sendIntercom(sessionName);
2534
+ const dispatched = result === "acknowledged" || result === "debounced" || result === "queued" ? "verified" : result === "delivered" ? "sent_unverified" : "session_dead";
2535
+ return { dispatched, session: sessionName, crossProject };
2536
+ } else {
2537
+ const projectDir = input.projectDir ?? process.cwd();
2538
+ const result = ensureEmployee(input.assignedTo, exeSession, projectDir, {
2539
+ autoInstance: isMultiInstance(input.assignedTo)
2540
+ });
2541
+ if (result.status === "failed") {
2542
+ process.stderr.write(
2543
+ `[dispatch] Failed to spawn ${input.assignedTo}: ${result.error}
2544
+ `
2545
+ );
2546
+ return { dispatched: "session_missing" };
2547
+ }
2548
+ return { dispatched: "spawned", session: result.sessionName, crossProject };
2549
+ }
2550
+ } catch {
2551
+ return { dispatched: "session_missing" };
2552
+ }
2553
+ }
2554
+ function notifyTaskDone() {
2555
+ try {
2556
+ const key = getSessionKey();
2557
+ if (key && !process.env.VITEST) notifyParentExe(key);
2558
+ } catch {
2559
+ }
2560
+ }
2561
+ async function markTaskNotificationsRead(taskFile) {
2562
+ try {
2563
+ await markAsReadByTaskFile(taskFile);
2564
+ } catch {
2565
+ }
2566
+ }
2567
+ var init_tasks_notify = __esm({
2568
+ "src/lib/tasks-notify.ts"() {
2569
+ "use strict";
2570
+ init_tmux_routing();
2571
+ init_session_key();
2572
+ init_notifications();
2573
+ init_transport();
2574
+ init_employees();
2575
+ }
2576
+ });
2577
+
2578
+ // src/lib/behaviors.ts
2579
+ import crypto4 from "crypto";
2580
+ async function storeBehavior(opts) {
2581
+ const client = getClient();
2582
+ const id = crypto4.randomUUID();
2583
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2584
+ await client.execute({
2585
+ sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, priority, content, active, created_at, updated_at)
2586
+ VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)`,
2587
+ args: [id, opts.agentId, opts.projectName ?? null, opts.domain ?? null, opts.priority ?? "p1", opts.content, now, now]
2588
+ });
2589
+ return id;
2590
+ }
2591
+ var init_behaviors = __esm({
2592
+ "src/lib/behaviors.ts"() {
2593
+ "use strict";
2594
+ init_database();
2595
+ }
2596
+ });
2597
+
2598
+ // src/lib/skill-learning.ts
2599
+ var skill_learning_exports = {};
2600
+ __export(skill_learning_exports, {
2601
+ captureAndLearn: () => captureAndLearn,
2602
+ captureTrajectory: () => captureTrajectory,
2603
+ editDistance: () => editDistance,
2604
+ extractSkill: () => extractSkill,
2605
+ extractTrajectory: () => extractTrajectory,
2606
+ findSimilarTrajectories: () => findSimilarTrajectories,
2607
+ hashSignature: () => hashSignature,
2608
+ storeTrajectory: () => storeTrajectory,
2609
+ sweepTrajectories: () => sweepTrajectories
2610
+ });
2611
+ import crypto5 from "crypto";
2612
+ async function extractTrajectory(taskId, agentId) {
2613
+ const client = getClient();
2614
+ const result = await client.execute({
2615
+ sql: `SELECT tool_name, raw_text
2616
+ FROM memories
2617
+ WHERE task_id = ? AND agent_id = ?
2618
+ ORDER BY timestamp ASC`,
2619
+ args: [taskId, agentId]
2620
+ });
2621
+ if (result.rows.length === 0) return [];
2622
+ const rawTools = result.rows.map((r) => {
2623
+ const toolName = String(r.tool_name);
2624
+ if (toolName === "Bash") {
2625
+ const text = String(r.raw_text);
2626
+ const cmdMatch = text.match(/(?:command|Command).*?[:\s]+"?(\w+)/);
2627
+ return cmdMatch ? `Bash:${cmdMatch[1]}` : "Bash";
2628
+ }
2629
+ return toolName;
2630
+ });
2631
+ const signature = [];
2632
+ for (const tool of rawTools) {
2633
+ if (signature.length === 0 || signature[signature.length - 1] !== tool) {
2634
+ signature.push(tool);
2635
+ }
2636
+ }
2637
+ return signature;
2638
+ }
2639
+ function hashSignature(signature) {
2640
+ return crypto5.createHash("sha256").update(signature.join("|")).digest("hex").slice(0, 16);
2641
+ }
2642
+ async function storeTrajectory(opts) {
2643
+ const client = getClient();
2644
+ const id = crypto5.randomUUID();
2645
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2646
+ const signatureHash = hashSignature(opts.signature);
2647
+ await client.execute({
2648
+ sql: `INSERT INTO trajectories (id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at)
2649
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2650
+ args: [
2651
+ id,
2652
+ opts.taskId,
2653
+ opts.agentId,
2654
+ opts.projectName,
2655
+ opts.taskTitle,
2656
+ JSON.stringify(opts.signature),
2657
+ signatureHash,
2658
+ opts.signature.length,
2659
+ now
2660
+ ]
2661
+ });
2662
+ return id;
2663
+ }
2664
+ async function findSimilarTrajectories(signature, threshold = DEFAULT_SKILL_THRESHOLD) {
2665
+ const client = getClient();
2666
+ const hash = hashSignature(signature);
2667
+ const result = await client.execute({
2668
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
2669
+ FROM trajectories
2670
+ WHERE signature_hash = ?
2671
+ ORDER BY created_at DESC
2672
+ LIMIT 20`,
2673
+ args: [hash]
2674
+ });
2675
+ const mapRow = (r) => ({
2676
+ id: String(r.id),
2677
+ taskId: String(r.task_id),
2678
+ agentId: String(r.agent_id),
2679
+ projectName: String(r.project_name),
2680
+ taskTitle: String(r.task_title),
2681
+ signature: JSON.parse(String(r.signature)),
2682
+ signatureHash: String(r.signature_hash),
2683
+ toolCount: Number(r.tool_count),
2684
+ skillId: r.skill_id ? String(r.skill_id) : null,
2685
+ createdAt: String(r.created_at)
2686
+ });
2687
+ const matches = result.rows.map(mapRow);
2688
+ if (matches.length >= threshold) return matches;
2689
+ const nearResult = await client.execute({
2690
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
2691
+ FROM trajectories
2692
+ WHERE tool_count BETWEEN ? AND ?
2693
+ AND signature_hash != ?
2694
+ ORDER BY created_at DESC
2695
+ LIMIT 50`,
2696
+ args: [
2697
+ Math.max(1, signature.length - 3),
2698
+ signature.length + 3,
2699
+ hash
2700
+ ]
2701
+ });
2702
+ for (const r of nearResult.rows) {
2703
+ const candidateSig = JSON.parse(String(r.signature));
2704
+ if (editDistance(signature, candidateSig) <= 2) {
2705
+ matches.push(mapRow(r));
2706
+ }
2707
+ }
2708
+ return matches;
2709
+ }
2710
+ async function captureTrajectory(opts) {
2711
+ const signature = await extractTrajectory(opts.taskId, opts.agentId);
2712
+ if (signature.length < 3) {
2713
+ return { trajectoryId: "", similarCount: 0, similar: [] };
2714
+ }
2715
+ const trajectoryId = await storeTrajectory({
2716
+ taskId: opts.taskId,
2717
+ agentId: opts.agentId,
2718
+ projectName: opts.projectName,
2719
+ taskTitle: opts.taskTitle,
2720
+ signature
2721
+ });
2722
+ const similar = await findSimilarTrajectories(
2723
+ signature,
2724
+ opts.skillThreshold ?? DEFAULT_SKILL_THRESHOLD
2725
+ );
2726
+ return { trajectoryId, similarCount: similar.length, similar };
2727
+ }
2728
+ function buildExtractionPrompt(trajectories) {
2729
+ const items = trajectories.map((t, i) => {
2730
+ const sig = t.signature.join(" \u2192 ");
2731
+ return `Task ${i + 1}: "${t.taskTitle}" (${t.agentId}, ${t.projectName}) \u2014 ${t.toolCount} tool calls
2732
+ Signature: ${sig}`;
2733
+ }).join("\n\n");
2734
+ return `You are analyzing ${trajectories.length} completed tasks that followed similar procedures:
2735
+
2736
+ ${items}
2737
+
2738
+ Extract the reusable procedure. Format your response EXACTLY like this:
2739
+
2740
+ SKILL: {name \u2014 short, descriptive}
2741
+ TRIGGER: {when to use this \u2014 one sentence}
2742
+ STEPS:
2743
+ 1. ...
2744
+ 2. ...
2745
+ PITFALLS: {common mistakes to avoid}
2746
+
2747
+ Be specific and actionable. Include tool names, file patterns, and concrete commands where applicable.`;
2748
+ }
2749
+ async function extractSkill(trajectories, model) {
2750
+ if (trajectories.length === 0) return null;
2751
+ const config = await loadConfig();
2752
+ const skillModel = model ?? config.skillModel;
2753
+ const Anthropic = (await import("@anthropic-ai/sdk")).default;
2754
+ const client = new Anthropic();
2755
+ const prompt = buildExtractionPrompt(trajectories);
2756
+ const response = await client.messages.create({
2757
+ model: skillModel,
2758
+ max_tokens: 500,
2759
+ messages: [{ role: "user", content: prompt }]
2760
+ });
2761
+ const textBlock = response.content.find((b) => b.type === "text");
2762
+ const skillText = textBlock?.text;
2763
+ if (!skillText) return null;
2764
+ const agentId = trajectories[0].agentId;
2765
+ const projectName = trajectories[0].projectName;
2766
+ const skillId = await storeBehavior({
2767
+ agentId,
2768
+ content: skillText,
2769
+ domain: "skill",
2770
+ projectName
2771
+ });
2772
+ const dbClient = getClient();
2773
+ for (const t of trajectories) {
2774
+ await dbClient.execute({
2775
+ sql: "UPDATE trajectories SET skill_id = ? WHERE id = ?",
2776
+ args: [skillId, t.id]
2777
+ });
2778
+ }
2779
+ process.stderr.write(
2780
+ `[skill-learning] Skill extracted from ${trajectories.length} trajectories \u2192 behavior ${skillId}
2781
+ `
2782
+ );
2783
+ return skillId;
2784
+ }
2785
+ async function captureAndLearn(opts) {
2786
+ try {
2787
+ const config = await loadConfig();
2788
+ if (!config.skillLearning) return;
2789
+ const { trajectoryId, similarCount, similar } = await captureTrajectory({
2790
+ ...opts,
2791
+ skillThreshold: config.skillThreshold
2792
+ });
2793
+ if (!trajectoryId) return;
2794
+ if (similarCount >= config.skillThreshold) {
2795
+ const unprocessed = similar.filter((t) => !t.skillId);
2796
+ if (unprocessed.length >= config.skillThreshold) {
2797
+ extractSkill(unprocessed, config.skillModel).catch((err) => {
2798
+ process.stderr.write(
2799
+ `[skill-learning] Extraction failed: ${err instanceof Error ? err.message : String(err)}
2800
+ `
2801
+ );
2802
+ });
2803
+ }
2804
+ }
2805
+ } catch (err) {
2806
+ process.stderr.write(
2807
+ `[skill-learning] captureAndLearn failed: ${err instanceof Error ? err.message : String(err)}
2808
+ `
2809
+ );
2810
+ }
2811
+ }
2812
+ async function sweepTrajectories(threshold, model) {
2813
+ const config = await loadConfig();
2814
+ if (!config.skillLearning) return { clustersProcessed: 0, skillsExtracted: 0 };
2815
+ const t = threshold ?? config.skillThreshold;
2816
+ const client = getClient();
2817
+ const result = await client.execute({
2818
+ sql: `SELECT signature_hash, COUNT(*) as cnt
2819
+ FROM trajectories
2820
+ WHERE skill_id IS NULL
2821
+ GROUP BY signature_hash
2822
+ HAVING cnt >= ?
2823
+ ORDER BY cnt DESC
2824
+ LIMIT 10`,
2825
+ args: [t]
2826
+ });
2827
+ let clustersProcessed = 0;
2828
+ let skillsExtracted = 0;
2829
+ for (const row of result.rows) {
2830
+ const hash = String(row.signature_hash);
2831
+ const trajResult = await client.execute({
2832
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at
2833
+ FROM trajectories
2834
+ WHERE signature_hash = ? AND skill_id IS NULL
2835
+ ORDER BY created_at DESC
2836
+ LIMIT 10`,
2837
+ args: [hash]
2838
+ });
2839
+ const trajectories = trajResult.rows.map((r) => ({
2840
+ id: String(r.id),
2841
+ taskId: String(r.task_id),
2842
+ agentId: String(r.agent_id),
2843
+ projectName: String(r.project_name),
2844
+ taskTitle: String(r.task_title),
2845
+ signature: JSON.parse(String(r.signature)),
2846
+ signatureHash: String(r.signature_hash),
2847
+ toolCount: Number(r.tool_count),
2848
+ skillId: null,
2849
+ createdAt: String(r.created_at)
2850
+ }));
2851
+ if (trajectories.length >= t) {
2852
+ clustersProcessed++;
2853
+ const skillId = await extractSkill(trajectories, model ?? config.skillModel);
2854
+ if (skillId) skillsExtracted++;
2855
+ }
2856
+ }
2857
+ return { clustersProcessed, skillsExtracted };
2858
+ }
2859
+ function editDistance(a, b) {
2860
+ const m = a.length;
2861
+ const n = b.length;
2862
+ const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
2863
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
2864
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
2865
+ for (let i = 1; i <= m; i++) {
2866
+ for (let j = 1; j <= n; j++) {
2867
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
2868
+ dp[i][j] = Math.min(
2869
+ dp[i - 1][j] + 1,
2870
+ dp[i][j - 1] + 1,
2871
+ dp[i - 1][j - 1] + cost
2872
+ );
2873
+ }
2874
+ }
2875
+ return dp[m][n];
2876
+ }
2877
+ var DEFAULT_SKILL_THRESHOLD;
2878
+ var init_skill_learning = __esm({
2879
+ "src/lib/skill-learning.ts"() {
2880
+ "use strict";
2881
+ init_database();
2882
+ init_behaviors();
2883
+ init_config();
2884
+ DEFAULT_SKILL_THRESHOLD = 3;
2885
+ }
2886
+ });
2887
+
2888
+ // src/lib/tasks.ts
2889
+ var tasks_exports = {};
2890
+ __export(tasks_exports, {
2891
+ cleanupOrphanedReviews: () => cleanupOrphanedReviews,
2892
+ countNewPendingReviewsSince: () => countNewPendingReviewsSince,
2893
+ countPendingReviews: () => countPendingReviews,
2894
+ createTask: () => createTask,
2895
+ createTaskCore: () => createTaskCore,
2896
+ deleteTask: () => deleteTask,
2897
+ deleteTaskCore: () => deleteTaskCore,
2898
+ ensureArchitectureDoc: () => ensureArchitectureDoc,
2899
+ ensureGitignoreExe: () => ensureGitignoreExe,
2900
+ getReviewChecklist: () => getReviewChecklist,
2901
+ listPendingReviews: () => listPendingReviews,
2902
+ listTasks: () => listTasks,
2903
+ resolveTask: () => resolveTask,
2904
+ slugify: () => slugify,
2905
+ updateTask: () => updateTask,
2906
+ updateTaskStatus: () => updateTaskStatus,
2907
+ writeCheckpoint: () => writeCheckpoint
2908
+ });
2909
+ import path13 from "path";
2910
+ import { writeFileSync as writeFileSync5, mkdirSync as mkdirSync5, unlinkSync as unlinkSync4 } from "fs";
2911
+ async function createTask(input) {
2912
+ const result = await createTaskCore(input);
2913
+ if (!input.skipDispatch && result.status !== "blocked" && !process.env.VITEST) {
2914
+ dispatchTaskToEmployee({
2915
+ assignedTo: input.assignedTo,
2916
+ title: input.title,
2917
+ priority: input.priority,
2918
+ taskFile: result.taskFile,
2919
+ initialStatus: result.status,
2920
+ projectName: input.projectName
2921
+ });
2922
+ }
2923
+ return result;
2924
+ }
2925
+ async function updateTask(input) {
2926
+ const { row, taskFile, now, taskId } = await updateTaskStatus(input);
2927
+ try {
2928
+ const agent = String(row.assigned_to);
2929
+ const cacheDir = path13.join(EXE_AI_DIR, "session-cache");
2930
+ const cachePath = path13.join(cacheDir, `current-task-${agent}.json`);
2931
+ if (input.status === "in_progress") {
2932
+ mkdirSync5(cacheDir, { recursive: true });
2933
+ writeFileSync5(cachePath, JSON.stringify({ taskId, title: String(row.title) }));
2934
+ } else if (input.status === "done" || input.status === "blocked" || input.status === "cancelled") {
2935
+ try {
2936
+ unlinkSync4(cachePath);
2937
+ } catch {
2938
+ }
2939
+ }
2940
+ } catch {
2941
+ }
2942
+ if (input.status === "done") {
2943
+ await cleanupReviewFile(row, taskFile, input.baseDir);
2944
+ }
2945
+ if (input.status === "done" || input.status === "cancelled") {
2946
+ try {
2947
+ const client = getClient();
2948
+ const taskTitle = String(row.title);
2949
+ const escaped = taskTitle.replace(/%/g, "\\%").replace(/_/g, "\\_");
2950
+ await client.execute({
2951
+ sql: `UPDATE tasks SET status = 'cancelled', updated_at = ?
2952
+ WHERE title LIKE ? ESCAPE '\\' AND status IN ('open', 'in_progress')`,
2953
+ args: [now, `%left '${escaped}' as in\\_progress%`]
2954
+ });
2955
+ } catch {
2956
+ }
2957
+ try {
2958
+ const client = getClient();
2959
+ const cascaded = await client.execute({
2960
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
2961
+ WHERE parent_task_id = ? AND status = 'needs_review'`,
2962
+ args: [now, taskId]
2963
+ });
2964
+ if (cascaded.rowsAffected > 0) {
2965
+ process.stderr.write(
2966
+ `[cascade] Closed ${cascaded.rowsAffected} orphaned review task(s) for parent ${taskId}
2967
+ `
2968
+ );
2969
+ }
2970
+ } catch {
2971
+ }
2972
+ }
2973
+ const isTerminal = input.status === "done" || input.status === "needs_review";
2974
+ if (isTerminal) {
2975
+ const isExe = String(row.assigned_to) === "exe";
2976
+ if (!isExe) {
2977
+ notifyTaskDone();
2978
+ }
2979
+ await markTaskNotificationsRead(taskFile);
2980
+ if (input.status === "done") {
2981
+ try {
2982
+ await cascadeUnblock(taskId, input.baseDir, now);
2983
+ } catch {
2984
+ }
2985
+ orgBus.emit({
2986
+ type: "task_completed",
2987
+ taskId,
2988
+ employee: String(row.assigned_to),
2989
+ result: input.result ?? "",
2990
+ timestamp: now
2991
+ });
2992
+ if (row.parent_task_id) {
2993
+ try {
2994
+ await checkSubtaskCompletion(String(row.parent_task_id), String(row.project_name));
2995
+ } catch {
2996
+ }
2997
+ }
2998
+ }
2999
+ }
3000
+ if (input.status === "done" && String(row.assigned_to) !== "exe" && !process.env.VITEST) {
3001
+ Promise.resolve().then(() => (init_skill_learning(), skill_learning_exports)).then(
3002
+ ({ captureAndLearn: captureAndLearn2 }) => captureAndLearn2({
3003
+ taskId,
3004
+ agentId: String(row.assigned_to),
3005
+ projectName: String(row.project_name),
3006
+ taskTitle: String(row.title)
3007
+ })
3008
+ ).catch((err) => {
3009
+ process.stderr.write(
3010
+ `[updateTask] skill learning failed: ${err instanceof Error ? err.message : String(err)}
3011
+ `
3012
+ );
3013
+ });
3014
+ }
3015
+ let nextTask;
3016
+ if (isTerminal && String(row.assigned_to) !== "exe") {
3017
+ try {
3018
+ nextTask = await findNextTask(String(row.assigned_to));
3019
+ } catch {
3020
+ }
3021
+ }
3022
+ return {
3023
+ id: String(row.id),
3024
+ title: String(row.title),
3025
+ assignedTo: String(row.assigned_to),
3026
+ assignedBy: String(row.assigned_by),
3027
+ projectName: String(row.project_name),
3028
+ priority: String(row.priority),
3029
+ status: input.status,
3030
+ taskFile,
3031
+ createdAt: String(row.created_at),
3032
+ updatedAt: now,
3033
+ budgetTokens: row.budget_tokens !== void 0 && row.budget_tokens !== null ? Number(row.budget_tokens) : null,
3034
+ budgetFallbackModel: row.budget_fallback_model !== void 0 && row.budget_fallback_model !== null ? String(row.budget_fallback_model) : null,
3035
+ tokensUsed: Number(row.tokens_used ?? 0),
3036
+ tokensWarnedAt: row.tokens_warned_at !== void 0 && row.tokens_warned_at !== null ? Number(row.tokens_warned_at) : null,
3037
+ nextTask
3038
+ };
3039
+ }
3040
+ async function deleteTask(taskId, baseDir) {
3041
+ const client = getClient();
3042
+ const { taskFile, assignedTo, assignedBy, taskSlug } = await deleteTaskCore(taskId, baseDir);
3043
+ const reviewer = assignedBy || "exe";
3044
+ const reviewSlug = `review-${assignedTo}-${taskSlug}`;
3045
+ const reviewFile = `exe/${reviewer}/${reviewSlug}.md`;
3046
+ await client.execute({
3047
+ sql: "DELETE FROM tasks WHERE task_file = ? OR task_file = ?",
3048
+ args: [reviewFile, `exe/exe/${reviewSlug}.md`]
3049
+ });
3050
+ await markAsReadByTaskFile(taskFile);
3051
+ await markAsReadByTaskFile(reviewFile);
3052
+ }
3053
+ var init_tasks = __esm({
3054
+ "src/lib/tasks.ts"() {
3055
+ "use strict";
3056
+ init_database();
3057
+ init_config();
3058
+ init_notifications();
3059
+ init_state_bus();
3060
+ init_tasks_crud();
3061
+ init_tasks_review();
3062
+ init_tasks_crud();
3063
+ init_tasks_chain();
3064
+ init_tasks_review();
3065
+ init_tasks_notify();
3066
+ }
3067
+ });
3068
+
440
3069
  // src/mcp/tools/list-tasks.ts
441
3070
  init_tasks();
442
3071
  init_project_name();