@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,6 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
6
  var __esm = (fn, res) => function __init() {
5
7
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
8
  };
@@ -8,6 +10,15 @@ var __export = (target, all) => {
8
10
  for (var name in all)
9
11
  __defProp(target, name, { get: all[name], enumerable: true });
10
12
  };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
11
22
 
12
23
  // src/lib/db-retry.ts
13
24
  function isBusyError(err) {
@@ -316,6 +327,13 @@ async function ensureSchema() {
316
327
  });
317
328
  } catch {
318
329
  }
330
+ try {
331
+ await client.execute({
332
+ sql: `ALTER TABLE tasks ADD COLUMN session_scope TEXT`,
333
+ args: []
334
+ });
335
+ } catch {
336
+ }
319
337
  try {
320
338
  await client.execute({
321
339
  sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
@@ -762,6 +780,18 @@ async function ensureSchema() {
762
780
  CREATE INDEX IF NOT EXISTS idx_session_kills_agent
763
781
  ON session_kills(agent_id);
764
782
  `);
783
+ await client.execute(`
784
+ CREATE TABLE IF NOT EXISTS global_procedures (
785
+ id TEXT PRIMARY KEY,
786
+ title TEXT NOT NULL,
787
+ content TEXT NOT NULL,
788
+ priority TEXT NOT NULL DEFAULT 'p0',
789
+ domain TEXT,
790
+ active INTEGER NOT NULL DEFAULT 1,
791
+ created_at TEXT NOT NULL,
792
+ updated_at TEXT NOT NULL
793
+ )
794
+ `);
765
795
  await client.executeMultiple(`
766
796
  CREATE TABLE IF NOT EXISTS conversations (
767
797
  id TEXT PRIMARY KEY,
@@ -1167,6 +1197,61 @@ var init_config = __esm({
1167
1197
  }
1168
1198
  });
1169
1199
 
1200
+ // src/lib/state-bus.ts
1201
+ var StateBus, orgBus;
1202
+ var init_state_bus = __esm({
1203
+ "src/lib/state-bus.ts"() {
1204
+ "use strict";
1205
+ StateBus = class {
1206
+ handlers = /* @__PURE__ */ new Map();
1207
+ globalHandlers = /* @__PURE__ */ new Set();
1208
+ /** Emit an event to all subscribers */
1209
+ emit(event) {
1210
+ const typeHandlers = this.handlers.get(event.type);
1211
+ if (typeHandlers) {
1212
+ for (const handler of typeHandlers) {
1213
+ try {
1214
+ handler(event);
1215
+ } catch {
1216
+ }
1217
+ }
1218
+ }
1219
+ for (const handler of this.globalHandlers) {
1220
+ try {
1221
+ handler(event);
1222
+ } catch {
1223
+ }
1224
+ }
1225
+ }
1226
+ /** Subscribe to a specific event type */
1227
+ on(type, handler) {
1228
+ if (!this.handlers.has(type)) {
1229
+ this.handlers.set(type, /* @__PURE__ */ new Set());
1230
+ }
1231
+ this.handlers.get(type).add(handler);
1232
+ }
1233
+ /** Subscribe to ALL events */
1234
+ onAny(handler) {
1235
+ this.globalHandlers.add(handler);
1236
+ }
1237
+ /** Unsubscribe from a specific event type */
1238
+ off(type, handler) {
1239
+ this.handlers.get(type)?.delete(handler);
1240
+ }
1241
+ /** Unsubscribe from ALL events */
1242
+ offAny(handler) {
1243
+ this.globalHandlers.delete(handler);
1244
+ }
1245
+ /** Remove all listeners */
1246
+ clear() {
1247
+ this.handlers.clear();
1248
+ this.globalHandlers.clear();
1249
+ }
1250
+ };
1251
+ orgBus = new StateBus();
1252
+ }
1253
+ });
1254
+
1170
1255
  // src/lib/shard-manager.ts
1171
1256
  var shard_manager_exports = {};
1172
1257
  __export(shard_manager_exports, {
@@ -1408,6 +1493,71 @@ var init_shard_manager = __esm({
1408
1493
  }
1409
1494
  });
1410
1495
 
1496
+ // src/lib/global-procedures.ts
1497
+ var global_procedures_exports = {};
1498
+ __export(global_procedures_exports, {
1499
+ deactivateGlobalProcedure: () => deactivateGlobalProcedure,
1500
+ getGlobalProceduresBlock: () => getGlobalProceduresBlock,
1501
+ loadGlobalProcedures: () => loadGlobalProcedures,
1502
+ storeGlobalProcedure: () => storeGlobalProcedure
1503
+ });
1504
+ import { randomUUID } from "crypto";
1505
+ async function loadGlobalProcedures() {
1506
+ const client = getClient();
1507
+ const result = await client.execute({
1508
+ sql: "SELECT * FROM global_procedures WHERE active = 1 ORDER BY priority ASC, created_at ASC",
1509
+ args: []
1510
+ });
1511
+ const procedures = result.rows;
1512
+ if (procedures.length > 0) {
1513
+ _cache = procedures.map((p) => `### ${p.title}
1514
+ ${p.content}`).join("\n\n");
1515
+ } else {
1516
+ _cache = "";
1517
+ }
1518
+ _cacheLoaded = true;
1519
+ return procedures;
1520
+ }
1521
+ function getGlobalProceduresBlock() {
1522
+ if (!_cacheLoaded) return "";
1523
+ if (!_cache) return "";
1524
+ return `## Organization-Wide Procedures (MANDATORY \u2014 supersedes all other rules)
1525
+
1526
+ ${_cache}
1527
+ `;
1528
+ }
1529
+ async function storeGlobalProcedure(input) {
1530
+ const id = randomUUID();
1531
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1532
+ const client = getClient();
1533
+ await client.execute({
1534
+ sql: `INSERT INTO global_procedures (id, title, content, priority, domain, active, created_at, updated_at)
1535
+ VALUES (?, ?, ?, ?, ?, 1, ?, ?)`,
1536
+ args: [id, input.title, input.content, input.priority ?? "p0", input.domain ?? null, now, now]
1537
+ });
1538
+ await loadGlobalProcedures();
1539
+ return id;
1540
+ }
1541
+ async function deactivateGlobalProcedure(id) {
1542
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1543
+ const client = getClient();
1544
+ const result = await client.execute({
1545
+ sql: "UPDATE global_procedures SET active = 0, updated_at = ? WHERE id = ?",
1546
+ args: [now, id]
1547
+ });
1548
+ await loadGlobalProcedures();
1549
+ return result.rowsAffected > 0;
1550
+ }
1551
+ var _cache, _cacheLoaded;
1552
+ var init_global_procedures = __esm({
1553
+ "src/lib/global-procedures.ts"() {
1554
+ "use strict";
1555
+ init_database();
1556
+ _cache = "";
1557
+ _cacheLoaded = false;
1558
+ }
1559
+ });
1560
+
1411
1561
  // src/lib/store.ts
1412
1562
  var store_exports = {};
1413
1563
  __export(store_exports, {
@@ -1487,6 +1637,11 @@ async function initStore(options) {
1487
1637
  "version-query"
1488
1638
  );
1489
1639
  _nextVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
1640
+ try {
1641
+ const { loadGlobalProcedures: loadGlobalProcedures2 } = await Promise.resolve().then(() => (init_global_procedures(), global_procedures_exports));
1642
+ await loadGlobalProcedures2();
1643
+ } catch {
1644
+ }
1490
1645
  }
1491
1646
  function classifyTier(record) {
1492
1647
  if (record.tool_name === "commit_to_long_term_memory" && (record.importance ?? 0) >= 8) return 1;
@@ -1528,6 +1683,12 @@ async function writeMemory(record) {
1528
1683
  supersedes_id: record.supersedes_id ?? null
1529
1684
  };
1530
1685
  _pendingRecords.push(dbRow);
1686
+ orgBus.emit({
1687
+ type: "memory_stored",
1688
+ agentId: record.agent_id,
1689
+ project: record.project_name,
1690
+ timestamp: record.timestamp
1691
+ });
1531
1692
  const MAX_PENDING = 1e3;
1532
1693
  if (_pendingRecords.length > MAX_PENDING) {
1533
1694
  const dropped = _pendingRecords.length - MAX_PENDING;
@@ -1873,6 +2034,7 @@ var init_store = __esm({
1873
2034
  init_database();
1874
2035
  init_keychain();
1875
2036
  init_config();
2037
+ init_state_bus();
1876
2038
  INIT_MAX_RETRIES = 3;
1877
2039
  INIT_RETRY_DELAY_MS = 1e3;
1878
2040
  _pendingRecords = [];
@@ -1935,68 +2097,2813 @@ var init_project_name = __esm({
1935
2097
  }
1936
2098
  });
1937
2099
 
1938
- // src/bin/scan-tasks.ts
1939
- import { existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
2100
+ // src/lib/session-registry.ts
2101
+ import { readFileSync as readFileSync2, writeFileSync, mkdirSync as mkdirSync2, existsSync as existsSync4 } from "fs";
1940
2102
  import path5 from "path";
1941
2103
  import os3 from "os";
1942
-
1943
- // src/lib/is-main.ts
1944
- import { realpathSync } from "fs";
1945
- import { fileURLToPath } from "url";
1946
- function isMainModule(importMetaUrl) {
1947
- if (process.argv[1] == null) return false;
2104
+ function registerSession(entry) {
2105
+ const dir = path5.dirname(REGISTRY_PATH);
2106
+ if (!existsSync4(dir)) {
2107
+ mkdirSync2(dir, { recursive: true });
2108
+ }
2109
+ const sessions = listSessions();
2110
+ const idx = sessions.findIndex((s) => s.windowName === entry.windowName);
2111
+ if (idx >= 0) {
2112
+ sessions[idx] = entry;
2113
+ } else {
2114
+ sessions.push(entry);
2115
+ }
2116
+ writeFileSync(REGISTRY_PATH, JSON.stringify(sessions, null, 2));
2117
+ }
2118
+ function listSessions() {
1948
2119
  try {
1949
- const scriptPath = realpathSync(process.argv[1]);
1950
- const modulePath = realpathSync(fileURLToPath(importMetaUrl));
1951
- return scriptPath === modulePath;
2120
+ const raw = readFileSync2(REGISTRY_PATH, "utf8");
2121
+ return JSON.parse(raw);
1952
2122
  } catch {
1953
- return importMetaUrl === `file://${process.argv[1]}` || importMetaUrl === new URL(process.argv[1], "file://").href;
2123
+ return [];
1954
2124
  }
1955
2125
  }
2126
+ var REGISTRY_PATH;
2127
+ var init_session_registry = __esm({
2128
+ "src/lib/session-registry.ts"() {
2129
+ "use strict";
2130
+ REGISTRY_PATH = path5.join(os3.homedir(), ".exe-os", "session-registry.json");
2131
+ }
2132
+ });
1956
2133
 
1957
- // src/bin/scan-tasks.ts
1958
- function checkMcpHealth() {
1959
- try {
1960
- const claudeJson = path5.join(os3.homedir(), ".claude.json");
1961
- if (!existsSync4(claudeJson)) {
1962
- process.stderr.write(
1963
- "\u26A0\uFE0F MCP config missing (~/.claude.json not found) \u2014 close_task won't work. Run /exe-setup\n"
1964
- );
1965
- return;
2134
+ // src/lib/session-key.ts
2135
+ import { execSync as execSync2 } from "child_process";
2136
+ function getSessionKey() {
2137
+ if (_cached2) return _cached2;
2138
+ let pid = process.ppid;
2139
+ for (let i = 0; i < 10; i++) {
2140
+ try {
2141
+ const info = execSync2(`ps -p ${pid} -o ppid=,comm=`, {
2142
+ encoding: "utf8",
2143
+ timeout: 2e3
2144
+ }).trim();
2145
+ const match = info.match(/^\s*(\d+)\s+(.+)$/);
2146
+ if (!match) break;
2147
+ const [, ppid, cmd] = match;
2148
+ if (cmd === "claude" || cmd.endsWith("/claude")) {
2149
+ _cached2 = String(pid);
2150
+ return _cached2;
2151
+ }
2152
+ pid = parseInt(ppid, 10);
2153
+ if (pid <= 1) break;
2154
+ } catch {
2155
+ break;
1966
2156
  }
1967
- const config = JSON.parse(readFileSync2(claudeJson, "utf8"));
1968
- const servers = config.mcpServers;
1969
- if (!servers?.["exe-os"] && !servers?.["exe-mem"]) {
1970
- process.stderr.write(
1971
- "\u26A0\uFE0F MCP task tools not available \u2014 exe-os server not configured in ~/.claude.json. close_task won't work.\n"
1972
- );
2157
+ }
2158
+ _cached2 = process.env.CLAUDE_CODE_SSE_PORT ?? String(process.ppid);
2159
+ return _cached2;
2160
+ }
2161
+ var _cached2;
2162
+ var init_session_key = __esm({
2163
+ "src/lib/session-key.ts"() {
2164
+ "use strict";
2165
+ _cached2 = null;
2166
+ }
2167
+ });
2168
+
2169
+ // src/lib/tmux-transport.ts
2170
+ var tmux_transport_exports = {};
2171
+ __export(tmux_transport_exports, {
2172
+ TmuxTransport: () => TmuxTransport
2173
+ });
2174
+ import { execFileSync } from "child_process";
2175
+ var QUIET, TmuxTransport;
2176
+ var init_tmux_transport = __esm({
2177
+ "src/lib/tmux-transport.ts"() {
2178
+ "use strict";
2179
+ QUIET = {
2180
+ encoding: "utf8",
2181
+ stdio: ["pipe", "pipe", "pipe"]
2182
+ };
2183
+ TmuxTransport = class {
2184
+ getMySession() {
2185
+ try {
2186
+ return execFileSync("tmux", ["display-message", "-p", "#{session_name}"], QUIET).trim() || null;
2187
+ } catch {
2188
+ return null;
2189
+ }
2190
+ }
2191
+ listSessions() {
2192
+ try {
2193
+ return execFileSync("tmux", ["list-sessions", "-F", "#{session_name}"], QUIET).trim().split("\n").filter(Boolean);
2194
+ } catch {
2195
+ return [];
2196
+ }
2197
+ }
2198
+ isAlive(target) {
2199
+ try {
2200
+ const sessions = this.listSessions();
2201
+ if (!sessions.includes(target)) return false;
2202
+ const paneStatus = execFileSync(
2203
+ "tmux",
2204
+ ["list-panes", "-t", target, "-F", "#{pane_dead}"],
2205
+ QUIET
2206
+ ).trim();
2207
+ return paneStatus !== "1";
2208
+ } catch {
2209
+ return false;
2210
+ }
2211
+ }
2212
+ sendKeys(target, keys) {
2213
+ execFileSync("tmux", ["send-keys", "-t", target, keys, "Enter"], QUIET);
2214
+ }
2215
+ capturePane(target, lines) {
2216
+ const args = ["capture-pane", "-t", target, "-p"];
2217
+ if (lines) args.push("-S", `-${lines}`);
2218
+ return execFileSync("tmux", args, { ...QUIET, timeout: 3e3 });
2219
+ }
2220
+ isPaneInCopyMode(target) {
2221
+ try {
2222
+ const result = execFileSync(
2223
+ "tmux",
2224
+ ["display-message", "-p", "-t", target, "#{pane_in_mode}"],
2225
+ { ...QUIET, timeout: 3e3 }
2226
+ ).trim();
2227
+ return result === "1";
2228
+ } catch {
2229
+ return false;
2230
+ }
2231
+ }
2232
+ spawn(name, config) {
2233
+ try {
2234
+ const args = ["new-session", "-d", "-s", name];
2235
+ if (config.cwd) args.push("-c", config.cwd);
2236
+ args.push(config.command);
2237
+ execFileSync("tmux", args);
2238
+ return { sessionName: name };
2239
+ } catch (e) {
2240
+ return { sessionName: name, error: `spawn failed: ${e}` };
2241
+ }
2242
+ }
2243
+ kill(target) {
2244
+ try {
2245
+ execFileSync("tmux", ["kill-session", "-t", target], QUIET);
2246
+ } catch {
2247
+ }
2248
+ }
2249
+ pipeLog(target, logFile) {
2250
+ try {
2251
+ const safePath = logFile.replace(/'/g, "'\\''");
2252
+ execFileSync("tmux", ["pipe-pane", "-t", target, `cat >> '${safePath}'`], QUIET);
2253
+ } catch {
2254
+ }
2255
+ }
2256
+ };
2257
+ }
2258
+ });
2259
+
2260
+ // src/lib/transport.ts
2261
+ function getTransport() {
2262
+ if (!_transport) {
2263
+ const { TmuxTransport: TmuxTransport2 } = (init_tmux_transport(), __toCommonJS(tmux_transport_exports));
2264
+ _transport = new TmuxTransport2();
2265
+ }
2266
+ return _transport;
2267
+ }
2268
+ var _transport;
2269
+ var init_transport = __esm({
2270
+ "src/lib/transport.ts"() {
2271
+ "use strict";
2272
+ _transport = null;
2273
+ }
2274
+ });
2275
+
2276
+ // src/lib/cc-agent-support.ts
2277
+ import { execSync as execSync3 } from "child_process";
2278
+ function _resetCcAgentSupportCache() {
2279
+ _cachedSupport = null;
2280
+ }
2281
+ function claudeSupportsAgentFlag() {
2282
+ if (_cachedSupport !== null) return _cachedSupport;
2283
+ try {
2284
+ const helpOutput = execSync3("claude --help 2>&1", {
2285
+ encoding: "utf-8",
2286
+ timeout: 5e3
2287
+ });
2288
+ _cachedSupport = /(^|\s)--agent(\b|=)/.test(helpOutput);
2289
+ } catch {
2290
+ _cachedSupport = false;
2291
+ }
2292
+ return _cachedSupport;
2293
+ }
2294
+ var _cachedSupport;
2295
+ var init_cc_agent_support = __esm({
2296
+ "src/lib/cc-agent-support.ts"() {
2297
+ "use strict";
2298
+ _cachedSupport = null;
2299
+ }
2300
+ });
2301
+
2302
+ // src/lib/mcp-prefix.ts
2303
+ function expandDualPrefixTools(shortNames) {
2304
+ const out = [];
2305
+ for (const name of shortNames) {
2306
+ for (const prefix of MCP_TOOL_PREFIXES) {
2307
+ out.push(prefix + name);
1973
2308
  }
2309
+ }
2310
+ return out;
2311
+ }
2312
+ var MCP_PRIMARY_KEY, MCP_LEGACY_KEY, MCP_TOOL_PREFIXES;
2313
+ var init_mcp_prefix = __esm({
2314
+ "src/lib/mcp-prefix.ts"() {
2315
+ "use strict";
2316
+ MCP_PRIMARY_KEY = "exe-os";
2317
+ MCP_LEGACY_KEY = "exe-mem";
2318
+ MCP_TOOL_PREFIXES = [
2319
+ `mcp__${MCP_PRIMARY_KEY}__`,
2320
+ `mcp__${MCP_LEGACY_KEY}__`
2321
+ ];
2322
+ }
2323
+ });
2324
+
2325
+ // src/lib/provider-table.ts
2326
+ function detectActiveProvider(env = process.env) {
2327
+ const baseUrl = env.ANTHROPIC_BASE_URL;
2328
+ if (!baseUrl) return DEFAULT_PROVIDER;
2329
+ for (const [name, cfg] of Object.entries(PROVIDER_TABLE)) {
2330
+ if (cfg.baseUrl === baseUrl) return name;
2331
+ }
2332
+ return DEFAULT_PROVIDER;
2333
+ }
2334
+ var PROVIDER_TABLE, DEFAULT_PROVIDER;
2335
+ var init_provider_table = __esm({
2336
+ "src/lib/provider-table.ts"() {
2337
+ "use strict";
2338
+ PROVIDER_TABLE = {
2339
+ opencode: {
2340
+ baseUrl: "https://opencode.ai/zen/go",
2341
+ apiKeyEnv: "OPENCODE_API_KEY",
2342
+ defaultModel: "minimax-m2.7"
2343
+ }
2344
+ };
2345
+ DEFAULT_PROVIDER = "default";
2346
+ }
2347
+ });
2348
+
2349
+ // src/lib/intercom-queue.ts
2350
+ import { readFileSync as readFileSync3, writeFileSync as writeFileSync2, renameSync as renameSync2, existsSync as existsSync5, mkdirSync as mkdirSync3 } from "fs";
2351
+ import path6 from "path";
2352
+ import os4 from "os";
2353
+ function ensureDir() {
2354
+ const dir = path6.dirname(QUEUE_PATH);
2355
+ if (!existsSync5(dir)) mkdirSync3(dir, { recursive: true });
2356
+ }
2357
+ function readQueue() {
2358
+ try {
2359
+ if (!existsSync5(QUEUE_PATH)) return [];
2360
+ return JSON.parse(readFileSync3(QUEUE_PATH, "utf8"));
1974
2361
  } catch {
2362
+ return [];
1975
2363
  }
1976
2364
  }
1977
- async function scanFromDb(agentId, tmuxSession, projectName) {
1978
- const { getClient: getClient2, isInitialized: isInitialized2 } = await Promise.resolve().then(() => (init_database(), database_exports));
1979
- if (!isInitialized2()) {
1980
- const { initStore: initStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
1981
- await initStore2();
2365
+ function writeQueue(queue) {
2366
+ ensureDir();
2367
+ const tmp = `${QUEUE_PATH}.tmp`;
2368
+ writeFileSync2(tmp, JSON.stringify(queue, null, 2));
2369
+ renameSync2(tmp, QUEUE_PATH);
2370
+ }
2371
+ function queueIntercom(targetSession, reason) {
2372
+ const queue = readQueue();
2373
+ const existing = queue.find((q) => q.targetSession === targetSession);
2374
+ if (existing) {
2375
+ existing.attempts++;
2376
+ existing.queuedAt = (/* @__PURE__ */ new Date()).toISOString();
2377
+ existing.reason = reason;
2378
+ } else {
2379
+ queue.push({
2380
+ targetSession,
2381
+ queuedAt: (/* @__PURE__ */ new Date()).toISOString(),
2382
+ attempts: 0,
2383
+ reason
2384
+ });
1982
2385
  }
1983
- const client = getClient2();
1984
- let resolvedProject = projectName;
1985
- if (resolvedProject === void 0) {
1986
- try {
1987
- const { getProjectName: getProjectName2 } = await Promise.resolve().then(() => (init_project_name(), project_name_exports));
1988
- resolvedProject = getProjectName2();
1989
- } catch {
2386
+ writeQueue(queue);
2387
+ }
2388
+ var QUEUE_PATH, TTL_MS, INTERCOM_LOG;
2389
+ var init_intercom_queue = __esm({
2390
+ "src/lib/intercom-queue.ts"() {
2391
+ "use strict";
2392
+ QUEUE_PATH = path6.join(os4.homedir(), ".exe-os", "intercom-queue.json");
2393
+ TTL_MS = 60 * 60 * 1e3;
2394
+ INTERCOM_LOG = path6.join(os4.homedir(), ".exe-os", "intercom.log");
2395
+ }
2396
+ });
2397
+
2398
+ // src/lib/employees.ts
2399
+ import { readFile as readFile3, writeFile as writeFile3, mkdir as mkdir3 } from "fs/promises";
2400
+ import { existsSync as existsSync6, symlinkSync, readlinkSync, readFileSync as readFileSync4 } from "fs";
2401
+ import { execSync as execSync4 } from "child_process";
2402
+ import path7 from "path";
2403
+ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
2404
+ if (!existsSync6(employeesPath)) return [];
2405
+ try {
2406
+ return JSON.parse(readFileSync4(employeesPath, "utf-8"));
2407
+ } catch {
2408
+ return [];
2409
+ }
2410
+ }
2411
+ function getEmployee(employees, name) {
2412
+ return employees.find((e) => e.name.toLowerCase() === name.toLowerCase());
2413
+ }
2414
+ function isMultiInstance(agentName, employees) {
2415
+ const roster = employees ?? loadEmployeesSync();
2416
+ const emp = getEmployee(roster, agentName);
2417
+ if (!emp) return false;
2418
+ return MULTI_INSTANCE_ROLES.has(emp.role.toLowerCase());
2419
+ }
2420
+ var EMPLOYEES_PATH, MULTI_INSTANCE_ROLES;
2421
+ var init_employees = __esm({
2422
+ "src/lib/employees.ts"() {
2423
+ "use strict";
2424
+ init_config();
2425
+ EMPLOYEES_PATH = path7.join(EXE_AI_DIR, "exe-employees.json");
2426
+ MULTI_INSTANCE_ROLES = /* @__PURE__ */ new Set(["principal engineer", "content production specialist", "staff code reviewer"]);
2427
+ }
2428
+ });
2429
+
2430
+ // src/lib/license.ts
2431
+ import { readFileSync as readFileSync5, writeFileSync as writeFileSync3, existsSync as existsSync7, mkdirSync as mkdirSync4 } from "fs";
2432
+ import { randomUUID as randomUUID2 } from "crypto";
2433
+ import path8 from "path";
2434
+ import { jwtVerify, importSPKI } from "jose";
2435
+ var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH, PLAN_LIMITS;
2436
+ var init_license = __esm({
2437
+ "src/lib/license.ts"() {
2438
+ "use strict";
2439
+ init_config();
2440
+ LICENSE_PATH = path8.join(EXE_AI_DIR, "license.key");
2441
+ CACHE_PATH = path8.join(EXE_AI_DIR, "license-cache.json");
2442
+ DEVICE_ID_PATH = path8.join(EXE_AI_DIR, "device-id");
2443
+ PLAN_LIMITS = {
2444
+ free: { devices: 1, employees: 1, memories: 5e3 },
2445
+ pro: { devices: 2, employees: 5, memories: 1e5 },
2446
+ team: { devices: 10, employees: 20, memories: 1e6 },
2447
+ agency: { devices: 50, employees: 100, memories: 1e7 },
2448
+ enterprise: { devices: -1, employees: -1, memories: -1 }
2449
+ };
2450
+ }
2451
+ });
2452
+
2453
+ // src/lib/plan-limits.ts
2454
+ import { readFileSync as readFileSync6, existsSync as existsSync8 } from "fs";
2455
+ import path9 from "path";
2456
+ function getLicenseSync() {
2457
+ try {
2458
+ if (!existsSync8(CACHE_PATH2)) return freeLicense();
2459
+ const raw = JSON.parse(readFileSync6(CACHE_PATH2, "utf8"));
2460
+ if (!raw.token || typeof raw.token !== "string") return freeLicense();
2461
+ const parts = raw.token.split(".");
2462
+ if (parts.length !== 3) return freeLicense();
2463
+ const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
2464
+ const plan = payload.plan ?? "free";
2465
+ const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
2466
+ return {
2467
+ valid: true,
2468
+ plan,
2469
+ email: payload.sub ?? "",
2470
+ expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
2471
+ deviceLimit: limits.devices,
2472
+ employeeLimit: limits.employees,
2473
+ memoryLimit: limits.memories
2474
+ };
2475
+ } catch {
2476
+ return freeLicense();
2477
+ }
2478
+ }
2479
+ function freeLicense() {
2480
+ const limits = PLAN_LIMITS.free;
2481
+ return {
2482
+ valid: true,
2483
+ plan: "free",
2484
+ email: "",
2485
+ expiresAt: null,
2486
+ deviceLimit: limits.devices,
2487
+ employeeLimit: limits.employees,
2488
+ memoryLimit: limits.memories
2489
+ };
2490
+ }
2491
+ function assertEmployeeLimitSync(rosterPath) {
2492
+ const license = getLicenseSync();
2493
+ if (license.employeeLimit < 0) return;
2494
+ const filePath = rosterPath ?? EMPLOYEES_PATH;
2495
+ let count = 0;
2496
+ try {
2497
+ if (existsSync8(filePath)) {
2498
+ const raw = readFileSync6(filePath, "utf8");
2499
+ const employees = JSON.parse(raw);
2500
+ count = Array.isArray(employees) ? employees.length : 0;
1990
2501
  }
2502
+ } catch {
2503
+ throw new PlanLimitError(
2504
+ `Cannot verify employee count: roster unreadable at ${filePath}. Refusing to proceed. Check file permissions or upgrade plan.`
2505
+ );
2506
+ }
2507
+ if (count >= license.employeeLimit) {
2508
+ throw new PlanLimitError(
2509
+ `Employee limit reached: ${count}/${license.employeeLimit} employees on the ${license.plan} plan. Upgrade at https://askexe.com to add more.`
2510
+ );
2511
+ }
2512
+ }
2513
+ var PlanLimitError, CACHE_PATH2;
2514
+ var init_plan_limits = __esm({
2515
+ "src/lib/plan-limits.ts"() {
2516
+ "use strict";
2517
+ init_database();
2518
+ init_employees();
2519
+ init_license();
2520
+ init_config();
2521
+ PlanLimitError = class extends Error {
2522
+ constructor(message) {
2523
+ super(message);
2524
+ this.name = "PlanLimitError";
2525
+ }
2526
+ };
2527
+ CACHE_PATH2 = path9.join(EXE_AI_DIR, "license-cache.json");
2528
+ }
2529
+ });
2530
+
2531
+ // src/lib/notifications.ts
2532
+ import crypto2 from "crypto";
2533
+ import path10 from "path";
2534
+ import os5 from "os";
2535
+ import {
2536
+ readFileSync as readFileSync7,
2537
+ readdirSync as readdirSync2,
2538
+ unlinkSync,
2539
+ existsSync as existsSync9,
2540
+ rmdirSync
2541
+ } from "fs";
2542
+ async function writeNotification(notification) {
2543
+ try {
2544
+ const client = getClient();
2545
+ const id = crypto2.randomUUID();
2546
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2547
+ await client.execute({
2548
+ sql: `INSERT INTO notifications (id, agent_id, agent_role, event, project, summary, task_file, read, created_at)
2549
+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)`,
2550
+ args: [
2551
+ id,
2552
+ notification.agentId,
2553
+ notification.agentRole,
2554
+ notification.event,
2555
+ notification.project,
2556
+ notification.summary,
2557
+ notification.taskFile ?? null,
2558
+ now
2559
+ ]
2560
+ });
2561
+ } catch (err) {
2562
+ process.stderr.write(`[notifications] WRITE FAILED: ${err instanceof Error ? err.message : String(err)}
2563
+ `);
2564
+ }
2565
+ }
2566
+ async function markAsReadByTaskFile(taskFile) {
2567
+ try {
2568
+ const client = getClient();
2569
+ await client.execute({
2570
+ sql: "UPDATE notifications SET read = 1 WHERE task_file = ? AND read = 0",
2571
+ args: [taskFile]
2572
+ });
2573
+ } catch {
2574
+ }
2575
+ }
2576
+ var init_notifications = __esm({
2577
+ "src/lib/notifications.ts"() {
2578
+ "use strict";
2579
+ init_database();
2580
+ }
2581
+ });
2582
+
2583
+ // src/lib/session-kill-telemetry.ts
2584
+ import crypto3 from "crypto";
2585
+ async function recordSessionKill(input) {
2586
+ try {
2587
+ const client = getClient();
2588
+ await client.execute({
2589
+ sql: `INSERT INTO session_kills
2590
+ (id, session_name, agent_id, killed_at, reason,
2591
+ ticks_idle, estimated_tokens_saved)
2592
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
2593
+ args: [
2594
+ crypto3.randomUUID(),
2595
+ input.sessionName,
2596
+ input.agentId,
2597
+ (/* @__PURE__ */ new Date()).toISOString(),
2598
+ input.reason,
2599
+ input.ticksIdle ?? null,
2600
+ input.estimatedTokensSaved ?? null
2601
+ ]
2602
+ });
2603
+ } catch (err) {
2604
+ process.stderr.write(
2605
+ `[session-kill-telemetry] write failed: ${err instanceof Error ? err.message : String(err)}
2606
+ `
2607
+ );
2608
+ }
2609
+ }
2610
+ var init_session_kill_telemetry = __esm({
2611
+ "src/lib/session-kill-telemetry.ts"() {
2612
+ "use strict";
2613
+ init_database();
2614
+ }
2615
+ });
2616
+
2617
+ // src/lib/tasks-crud.ts
2618
+ import crypto4 from "crypto";
2619
+ import path11 from "path";
2620
+ import { execSync as execSync5 } from "child_process";
2621
+ import { mkdir as mkdir4, writeFile as writeFile4, appendFile } from "fs/promises";
2622
+ import { existsSync as existsSync10, readFileSync as readFileSync8 } from "fs";
2623
+ async function writeCheckpoint(input) {
2624
+ const client = getClient();
2625
+ const row = await resolveTask(client, input.taskId);
2626
+ const taskId = String(row.id);
2627
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2628
+ const blockedByIds = [];
2629
+ if (row.blocked_by) {
2630
+ blockedByIds.push(String(row.blocked_by));
2631
+ }
2632
+ const checkpoint = {
2633
+ step: input.step,
2634
+ context_summary: input.contextSummary,
2635
+ files_touched: input.filesTouched ?? [],
2636
+ blocked_by_ids: blockedByIds,
2637
+ last_checkpoint_at: now
2638
+ };
2639
+ const result = await client.execute({
2640
+ sql: `UPDATE tasks SET checkpoint = ?, checkpoint_count = checkpoint_count + 1, updated_at = ? WHERE id = ?`,
2641
+ args: [JSON.stringify(checkpoint), now, taskId]
2642
+ });
2643
+ if (result.rowsAffected === 0) {
2644
+ throw new Error(`Checkpoint write failed: task ${taskId} not found`);
2645
+ }
2646
+ const countResult = await client.execute({
2647
+ sql: "SELECT checkpoint_count FROM tasks WHERE id = ?",
2648
+ args: [taskId]
2649
+ });
2650
+ const checkpointCount = Number(countResult.rows[0]?.checkpoint_count ?? 1);
2651
+ return { checkpointCount };
2652
+ }
2653
+ function extractParentFromContext(contextBody) {
2654
+ if (!contextBody) return null;
2655
+ const match = contextBody.match(
2656
+ /Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
2657
+ );
2658
+ return match ? match[1].toLowerCase() : null;
2659
+ }
2660
+ function slugify(title) {
2661
+ return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
2662
+ }
2663
+ async function resolveTask(client, identifier) {
2664
+ let result = await client.execute({
2665
+ sql: "SELECT * FROM tasks WHERE id = ?",
2666
+ args: [identifier]
2667
+ });
2668
+ if (result.rows.length === 1) return result.rows[0];
2669
+ result = await client.execute({
2670
+ sql: "SELECT * FROM tasks WHERE task_file LIKE ?",
2671
+ args: [`%${identifier}%`]
2672
+ });
2673
+ if (result.rows.length === 1) return result.rows[0];
2674
+ if (result.rows.length > 1) {
2675
+ const exact = result.rows.filter(
2676
+ (r) => String(r.task_file).endsWith(`/${identifier}.md`)
2677
+ );
2678
+ if (exact.length === 1) return exact[0];
2679
+ const candidates = exact.length > 1 ? exact : result.rows;
2680
+ const active = candidates.filter(
2681
+ (r) => !["done", "cancelled"].includes(String(r.status))
2682
+ );
2683
+ if (active.length === 1) return active[0];
2684
+ const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
2685
+ throw new Error(
2686
+ `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
2687
+ );
2688
+ }
2689
+ result = await client.execute({
2690
+ sql: "SELECT * FROM tasks WHERE title LIKE ?",
2691
+ args: [`%${identifier}%`]
2692
+ });
2693
+ if (result.rows.length === 1) return result.rows[0];
2694
+ if (result.rows.length > 1) {
2695
+ const active = result.rows.filter(
2696
+ (r) => !["done", "cancelled"].includes(String(r.status))
2697
+ );
2698
+ if (active.length === 1) return active[0];
2699
+ const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
2700
+ throw new Error(
2701
+ `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
2702
+ );
2703
+ }
2704
+ throw new Error(`Task not found: ${identifier}`);
2705
+ }
2706
+ async function createTaskCore(input) {
2707
+ const client = getClient();
2708
+ const id = crypto4.randomUUID();
2709
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2710
+ const slug = slugify(input.title);
2711
+ const taskFile = input.taskFile ?? `exe/${input.assignedTo}/${slug}.md`;
2712
+ let blockedById = null;
2713
+ const initialStatus = input.blockedBy ? "blocked" : "open";
2714
+ if (input.blockedBy) {
2715
+ const blocker = await resolveTask(client, input.blockedBy);
2716
+ blockedById = String(blocker.id);
2717
+ }
2718
+ let parentTaskId = null;
2719
+ let parentRef = input.parentTaskId;
2720
+ if (!parentRef) {
2721
+ const extracted = extractParentFromContext(input.context);
2722
+ if (extracted) {
2723
+ parentRef = extracted;
2724
+ process.stderr.write(
2725
+ "[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
2726
+ );
2727
+ }
2728
+ }
2729
+ if (parentRef) {
2730
+ try {
2731
+ const parent = await resolveTask(client, parentRef);
2732
+ parentTaskId = String(parent.id);
2733
+ } catch (err) {
2734
+ if (!input.parentTaskId) {
2735
+ throw new Error(
2736
+ `create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
2737
+ );
2738
+ }
2739
+ throw err;
2740
+ }
2741
+ }
2742
+ let warning;
2743
+ const dupCheck = await client.execute({
2744
+ sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
2745
+ args: [input.title, input.assignedTo]
2746
+ });
2747
+ if (dupCheck.rows.length > 0) {
2748
+ warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
2749
+ }
2750
+ if (input.baseDir) {
2751
+ try {
2752
+ await mkdir4(path11.join(input.baseDir, "exe", "output"), { recursive: true });
2753
+ await mkdir4(path11.join(input.baseDir, "exe", "research"), { recursive: true });
2754
+ await ensureArchitectureDoc(input.baseDir, input.projectName);
2755
+ await ensureGitignoreExe(input.baseDir);
2756
+ } catch {
2757
+ }
2758
+ }
2759
+ const complexity = input.complexity ?? "standard";
2760
+ let sessionScope = null;
2761
+ try {
2762
+ const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
2763
+ sessionScope = resolveExeSession2();
2764
+ } catch {
2765
+ }
2766
+ await client.execute({
2767
+ 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)
2768
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2769
+ args: [
2770
+ id,
2771
+ input.title,
2772
+ input.assignedTo,
2773
+ input.assignedBy,
2774
+ input.projectName,
2775
+ input.priority,
2776
+ initialStatus,
2777
+ taskFile,
2778
+ blockedById,
2779
+ parentTaskId,
2780
+ input.reviewer ?? null,
2781
+ input.context,
2782
+ complexity,
2783
+ input.budgetTokens ?? null,
2784
+ input.budgetFallbackModel ?? null,
2785
+ 0,
2786
+ null,
2787
+ sessionScope,
2788
+ now,
2789
+ now
2790
+ ]
2791
+ });
2792
+ return {
2793
+ id,
2794
+ title: input.title,
2795
+ assignedTo: input.assignedTo,
2796
+ assignedBy: input.assignedBy,
2797
+ projectName: input.projectName,
2798
+ priority: input.priority,
2799
+ status: initialStatus,
2800
+ taskFile,
2801
+ createdAt: now,
2802
+ updatedAt: now,
2803
+ warning,
2804
+ budgetTokens: input.budgetTokens ?? null,
2805
+ budgetFallbackModel: input.budgetFallbackModel ?? null,
2806
+ tokensUsed: 0,
2807
+ tokensWarnedAt: null
2808
+ };
2809
+ }
2810
+ async function listTasks(input) {
2811
+ const client = getClient();
2812
+ const conditions = [];
2813
+ const args = [];
2814
+ if (input.assignedTo) {
2815
+ conditions.push("assigned_to = ?");
2816
+ args.push(input.assignedTo);
2817
+ }
2818
+ if (input.status) {
2819
+ conditions.push("status = ?");
2820
+ args.push(input.status);
2821
+ } else {
2822
+ conditions.push("status IN ('open', 'in_progress', 'blocked')");
2823
+ }
2824
+ if (input.projectName) {
2825
+ conditions.push("project_name = ?");
2826
+ args.push(input.projectName);
2827
+ }
2828
+ if (input.priority) {
2829
+ conditions.push("priority = ?");
2830
+ args.push(input.priority);
2831
+ }
2832
+ try {
2833
+ const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
2834
+ const session = resolveExeSession2();
2835
+ if (session) {
2836
+ conditions.push("(session_scope IS NULL OR session_scope = ?)");
2837
+ args.push(session);
2838
+ }
2839
+ } catch {
2840
+ }
2841
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2842
+ const result = await client.execute({
2843
+ 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`,
2844
+ args
2845
+ });
2846
+ return result.rows.map((r) => ({
2847
+ id: String(r.id),
2848
+ title: String(r.title),
2849
+ assignedTo: String(r.assigned_to),
2850
+ assignedBy: String(r.assigned_by),
2851
+ projectName: String(r.project_name),
2852
+ priority: String(r.priority),
2853
+ status: String(r.status),
2854
+ taskFile: String(r.task_file),
2855
+ createdAt: String(r.created_at),
2856
+ updatedAt: String(r.updated_at),
2857
+ checkpointCount: Number(r.checkpoint_count ?? 0),
2858
+ budgetTokens: r.budget_tokens !== null ? Number(r.budget_tokens) : null,
2859
+ budgetFallbackModel: r.budget_fallback_model !== null ? String(r.budget_fallback_model) : null,
2860
+ tokensUsed: Number(r.tokens_used ?? 0),
2861
+ tokensWarnedAt: r.tokens_warned_at !== null ? Number(r.tokens_warned_at) : null
2862
+ }));
2863
+ }
2864
+ function checkStaleCompletion(taskContext, taskCreatedAt) {
2865
+ if (!taskContext) return null;
2866
+ if (!DELEGATION_KEYWORDS.test(taskContext)) return null;
2867
+ try {
2868
+ const since = new Date(taskCreatedAt).toISOString();
2869
+ const branch = execSync5(
2870
+ "git rev-parse --abbrev-ref HEAD 2>/dev/null",
2871
+ { encoding: "utf8", timeout: 3e3 }
2872
+ ).trim();
2873
+ const branchArg = branch && branch !== "HEAD" ? branch : "";
2874
+ const commitCount = execSync5(
2875
+ `git log --oneline --since="${since}" ${branchArg} 2>/dev/null | wc -l`,
2876
+ { encoding: "utf8", timeout: 5e3 }
2877
+ ).trim();
2878
+ const count = parseInt(commitCount, 10);
2879
+ if (count === 0) {
2880
+ return "WARNING: task closed with no new commits since creation. Verify work was actually produced.";
2881
+ }
2882
+ return null;
2883
+ } catch {
2884
+ return null;
2885
+ }
2886
+ }
2887
+ async function updateTaskStatus(input) {
2888
+ const client = getClient();
2889
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2890
+ const row = await resolveTask(client, input.taskId);
2891
+ const taskId = String(row.id);
2892
+ const taskFile = String(row.task_file);
2893
+ if (input.status === "done" && String(row.assigned_by) === "system" && taskFile.includes("review-")) {
2894
+ process.stderr.write(
2895
+ `[updateTask] Review task "${String(row.title)}" being marked done (assigned to ${String(row.assigned_to)})
2896
+ `
2897
+ );
2898
+ }
2899
+ if (input.status === "done") {
2900
+ const existingRow = await client.execute({
2901
+ sql: "SELECT context, created_at FROM tasks WHERE id = ?",
2902
+ args: [taskId]
2903
+ });
2904
+ if (existingRow.rows.length > 0) {
2905
+ const ctx = existingRow.rows[0];
2906
+ const warning = checkStaleCompletion(ctx.context, ctx.created_at);
2907
+ if (warning) {
2908
+ input.result = input.result ? `\u26A0\uFE0F ${warning}
2909
+
2910
+ ${input.result}` : `\u26A0\uFE0F ${warning}`;
2911
+ process.stderr.write(`[tasks] ${warning} (task: ${taskId})
2912
+ `);
2913
+ }
2914
+ }
2915
+ }
2916
+ if (input.status === "in_progress") {
2917
+ const tmuxSession = process.env.TMUX_PANE ?? process.env.MY_TMUX_SESSION ?? "unknown";
2918
+ const claim = await client.execute({
2919
+ sql: `UPDATE tasks
2920
+ SET status = 'in_progress', assigned_tmux = ?, updated_at = ?
2921
+ WHERE id = ? AND status = 'open'`,
2922
+ args: [tmuxSession, now, taskId]
2923
+ });
2924
+ if (claim.rowsAffected === 0) {
2925
+ const current = await client.execute({
2926
+ sql: "SELECT status, assigned_tmux FROM tasks WHERE id = ?",
2927
+ args: [taskId]
2928
+ });
2929
+ const cur = current.rows[0];
2930
+ const status = cur?.status ?? "unknown";
2931
+ const claimedBy = cur?.assigned_tmux ? ` (claimed by ${cur.assigned_tmux})` : "";
2932
+ throw new Error(`${TASK_ALREADY_CLAIMED_PREFIX}: task ${taskId} is ${status}${claimedBy}`);
2933
+ }
2934
+ try {
2935
+ await writeCheckpoint({
2936
+ taskId,
2937
+ step: "claimed",
2938
+ contextSummary: `Task claimed by session. Transitioning open \u2192 in_progress.`
2939
+ });
2940
+ } catch {
2941
+ }
2942
+ return { row, taskFile, now, taskId };
2943
+ }
2944
+ if (input.result) {
2945
+ await client.execute({
2946
+ sql: "UPDATE tasks SET status = ?, result = ?, updated_at = ? WHERE id = ?",
2947
+ args: [input.status, input.result, now, taskId]
2948
+ });
2949
+ } else {
2950
+ await client.execute({
2951
+ sql: "UPDATE tasks SET status = ?, updated_at = ? WHERE id = ?",
2952
+ args: [input.status, now, taskId]
2953
+ });
2954
+ }
2955
+ try {
2956
+ await writeCheckpoint({
2957
+ taskId,
2958
+ step: `status_transition:${input.status}`,
2959
+ contextSummary: input.result ? `Transitioned to ${input.status}. Result: ${input.result.slice(0, 500)}` : `Transitioned to ${input.status}.`
2960
+ });
2961
+ } catch {
2962
+ }
2963
+ return { row, taskFile, now, taskId };
2964
+ }
2965
+ async function deleteTaskCore(taskId, _baseDir) {
2966
+ const client = getClient();
2967
+ const row = await resolveTask(client, taskId);
2968
+ const id = String(row.id);
2969
+ const taskFile = String(row.task_file);
2970
+ const assignedTo = String(row.assigned_to);
2971
+ const assignedBy = String(row.assigned_by);
2972
+ await client.execute({ sql: "DELETE FROM tasks WHERE id = ?", args: [id] });
2973
+ const taskSlug = taskFile.split("/").pop()?.replace(".md", "") ?? "";
2974
+ return { taskFile, assignedTo, assignedBy, taskSlug };
2975
+ }
2976
+ async function ensureArchitectureDoc(baseDir, projectName) {
2977
+ const archPath = path11.join(baseDir, "exe", "ARCHITECTURE.md");
2978
+ try {
2979
+ if (existsSync10(archPath)) return;
2980
+ const template = [
2981
+ `# ${projectName} \u2014 System Architecture`,
2982
+ "",
2983
+ "> Employees: read this before every task. Update it when you change system structure.",
2984
+ `> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
2985
+ "",
2986
+ "## Overview",
2987
+ "",
2988
+ "<!-- Describe what this system does, its main components, and how they connect. -->",
2989
+ "",
2990
+ "## Key Components",
2991
+ "",
2992
+ "<!-- List the major modules, services, or subsystems. -->",
2993
+ "",
2994
+ "## Data Flow",
2995
+ "",
2996
+ "<!-- How does data move through the system? What writes where? -->",
2997
+ "",
2998
+ "## Invariants",
2999
+ "",
3000
+ "<!-- Rules that must never be violated. What breaks if these are wrong? -->",
3001
+ "",
3002
+ "## Dependencies",
3003
+ "",
3004
+ "<!-- What depends on what? If I change X, what else is affected? -->",
3005
+ ""
3006
+ ].join("\n");
3007
+ await writeFile4(archPath, template, "utf-8");
3008
+ } catch {
3009
+ }
3010
+ }
3011
+ async function ensureGitignoreExe(baseDir) {
3012
+ const gitignorePath = path11.join(baseDir, ".gitignore");
3013
+ try {
3014
+ if (existsSync10(gitignorePath)) {
3015
+ const content = readFileSync8(gitignorePath, "utf-8");
3016
+ if (/^\/?exe\/?$/m.test(content)) return;
3017
+ await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
3018
+ } else {
3019
+ await writeFile4(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
3020
+ }
3021
+ } catch {
3022
+ }
3023
+ }
3024
+ var DELEGATION_KEYWORDS, TASK_ALREADY_CLAIMED_PREFIX;
3025
+ var init_tasks_crud = __esm({
3026
+ "src/lib/tasks-crud.ts"() {
3027
+ "use strict";
3028
+ init_database();
3029
+ DELEGATION_KEYWORDS = /parallel|delegate|wave|tom\d*-exe/i;
3030
+ TASK_ALREADY_CLAIMED_PREFIX = "TASK_ALREADY_CLAIMED";
3031
+ }
3032
+ });
3033
+
3034
+ // src/lib/tasks-review.ts
3035
+ import path12 from "path";
3036
+ import { existsSync as existsSync11, readdirSync as readdirSync3, unlinkSync as unlinkSync2 } from "fs";
3037
+ async function countPendingReviews() {
3038
+ const client = getClient();
3039
+ const result = await client.execute({
3040
+ sql: "SELECT COUNT(*) as cnt FROM tasks WHERE status = 'needs_review'",
3041
+ args: []
3042
+ });
3043
+ return Number(result.rows[0]?.cnt) || 0;
3044
+ }
3045
+ async function countNewPendingReviewsSince(sinceIso) {
3046
+ const client = getClient();
3047
+ const result = await client.execute({
3048
+ sql: `SELECT COUNT(*) as cnt FROM tasks
3049
+ WHERE status = 'needs_review' AND updated_at > ?`,
3050
+ args: [sinceIso]
3051
+ });
3052
+ return Number(result.rows[0]?.cnt) || 0;
3053
+ }
3054
+ async function listPendingReviews(limit) {
3055
+ const client = getClient();
3056
+ const result = await client.execute({
3057
+ sql: `SELECT title, assigned_to, project_name FROM tasks
3058
+ WHERE status = 'needs_review'
3059
+ ORDER BY priority ASC, created_at DESC LIMIT ?`,
3060
+ args: [limit]
3061
+ });
3062
+ return result.rows;
3063
+ }
3064
+ async function cleanupOrphanedReviews() {
3065
+ const client = getClient();
3066
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3067
+ const r1 = await client.execute({
3068
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
3069
+ WHERE status = 'needs_review'
3070
+ AND assigned_by = 'system'
3071
+ AND title LIKE 'Review:%'
3072
+ AND parent_task_id IN (SELECT id FROM tasks WHERE status IN ('done', 'cancelled'))`,
3073
+ args: [now]
3074
+ });
3075
+ const staleThreshold = new Date(Date.now() - 60 * 60 * 1e3).toISOString();
3076
+ const r2 = await client.execute({
3077
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
3078
+ WHERE status = 'needs_review'
3079
+ AND result IS NOT NULL
3080
+ AND updated_at < ?`,
3081
+ args: [now, staleThreshold]
3082
+ });
3083
+ const total = r1.rowsAffected + r2.rowsAffected;
3084
+ if (total > 0) {
3085
+ process.stderr.write(
3086
+ `[cleanup] Closed ${total} orphaned review(s): ${r1.rowsAffected} cascade + ${r2.rowsAffected} stale
3087
+ `
3088
+ );
3089
+ }
3090
+ return total;
3091
+ }
3092
+ function getReviewChecklist(role, agent, taskSlug) {
3093
+ const roleLower = role.toLowerCase();
3094
+ if (roleLower.includes("engineer") || roleLower === "principal engineer") {
3095
+ return {
3096
+ lens: "Code Quality (Engineer)",
3097
+ checklist: [
3098
+ "1. Do all tests pass? Any new tests needed?",
3099
+ "2. Is the code clean \u2014 no dead code, no TODOs left?",
3100
+ "3. Does it follow existing patterns and conventions in the codebase?",
3101
+ "4. Any regressions in the test suite?"
3102
+ ]
3103
+ };
3104
+ }
3105
+ if (roleLower === "cto" || roleLower.includes("architect")) {
3106
+ return {
3107
+ lens: "Architecture (CTO)",
3108
+ checklist: [
3109
+ "1. Does this fit the existing architecture? Consistent with ARCHITECTURE.md?",
3110
+ "2. Is it backward compatible? Any breaking changes?",
3111
+ "3. Does it introduce technical debt? Is that debt justified?",
3112
+ "4. Security implications? Any new attack surface?",
3113
+ "5. Does it scale? Performance considerations?",
3114
+ "6. Coordination: does this affect other employees' work or other projects?"
3115
+ ]
3116
+ };
3117
+ }
3118
+ if (roleLower === "coo" || roleLower.includes("operations")) {
3119
+ return {
3120
+ lens: "Strategic (COO)",
3121
+ checklist: [
3122
+ "1. Does this serve the project mission?",
3123
+ "2. Is this the right work at the right time?",
3124
+ "3. Does the architectural assessment make sense for the business?",
3125
+ "4. Any cross-project implications?"
3126
+ ]
3127
+ };
3128
+ }
3129
+ return {
3130
+ lens: "General",
3131
+ checklist: [
3132
+ "1. Read the original task's acceptance criteria",
3133
+ `2. Check git log for related commits: \`git log --oneline --author-date-order -10\``,
3134
+ "3. Verify code changes match requirements",
3135
+ "4. Check if tests were added/updated",
3136
+ `5. Look for output files in exe/output/${agent}-${taskSlug}*`
3137
+ ]
3138
+ };
3139
+ }
3140
+ async function cleanupReviewFile(row, taskFile, _baseDir) {
3141
+ if (String(row.assigned_by) !== "system" || !taskFile.includes("review-")) return;
3142
+ try {
3143
+ const client = getClient();
3144
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3145
+ const parentId = row.parent_task_id ? String(row.parent_task_id) : null;
3146
+ if (parentId) {
3147
+ const result = await client.execute({
3148
+ sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE id = ? AND status = 'needs_review'",
3149
+ args: [now, parentId]
3150
+ });
3151
+ if (result.rowsAffected > 0) {
3152
+ process.stderr.write(
3153
+ `[review-cleanup] Cascaded original task to done via parent_task_id: ${parentId}
3154
+ `
3155
+ );
3156
+ }
3157
+ } else {
3158
+ const fileName = taskFile.split("/").pop() ?? "";
3159
+ const reviewPrefix = fileName.replace(".md", "");
3160
+ const parts = reviewPrefix.split("-");
3161
+ if (parts.length >= 3 && parts[0] === "review") {
3162
+ const agent = parts[1];
3163
+ const slug = parts.slice(2).join("-");
3164
+ const originalTaskFile = `exe/${agent}/${slug}.md`;
3165
+ const result = await client.execute({
3166
+ sql: "UPDATE tasks SET status = 'done', updated_at = ? WHERE task_file = ? AND status = 'needs_review'",
3167
+ args: [now, originalTaskFile]
3168
+ });
3169
+ if (result.rowsAffected > 0) {
3170
+ process.stderr.write(
3171
+ `[review-cleanup] Cascaded original task to done (legacy path): ${originalTaskFile}
3172
+ `
3173
+ );
3174
+ }
3175
+ }
3176
+ }
3177
+ } catch (err) {
3178
+ process.stderr.write(
3179
+ `[review-cleanup] Failed to cascade original task: ${err instanceof Error ? err.message : String(err)}
3180
+ `
3181
+ );
3182
+ }
3183
+ try {
3184
+ const cacheDir = path12.join(EXE_AI_DIR, "session-cache");
3185
+ if (existsSync11(cacheDir)) {
3186
+ for (const f of readdirSync3(cacheDir)) {
3187
+ if (f.startsWith("review-notified-")) {
3188
+ unlinkSync2(path12.join(cacheDir, f));
3189
+ }
3190
+ }
3191
+ }
3192
+ } catch {
3193
+ }
3194
+ }
3195
+ var init_tasks_review = __esm({
3196
+ "src/lib/tasks-review.ts"() {
3197
+ "use strict";
3198
+ init_database();
3199
+ init_config();
3200
+ init_employees();
3201
+ init_notifications();
3202
+ init_tasks_crud();
3203
+ init_tmux_routing();
3204
+ init_session_key();
3205
+ init_state_bus();
3206
+ }
3207
+ });
3208
+
3209
+ // src/lib/tasks-chain.ts
3210
+ import path13 from "path";
3211
+ import { readFile as readFile4, writeFile as writeFile5 } from "fs/promises";
3212
+ async function cascadeUnblock(taskId, baseDir, now) {
3213
+ const client = getClient();
3214
+ const unblocked = await client.execute({
3215
+ sql: `UPDATE tasks SET status = 'open', blocked_by = NULL, updated_at = ?
3216
+ WHERE blocked_by = ? AND status = 'blocked'`,
3217
+ args: [now, taskId]
3218
+ });
3219
+ if (baseDir && unblocked.rowsAffected > 0) {
3220
+ const unblockedRows = await client.execute({
3221
+ sql: `SELECT task_file FROM tasks WHERE blocked_by IS NULL AND updated_at = ?`,
3222
+ args: [now]
3223
+ });
3224
+ for (const ur of unblockedRows.rows) {
3225
+ try {
3226
+ const ubFile = path13.join(baseDir, String(ur.task_file));
3227
+ let ubContent = await readFile4(ubFile, "utf-8");
3228
+ ubContent = ubContent.replace(/\*\*Status:\*\* blocked/, "**Status:** open");
3229
+ ubContent = ubContent.replace(/\n\*\*Blocked by:\*\*.*\n/, "\n");
3230
+ await writeFile5(ubFile, ubContent, "utf-8");
3231
+ } catch {
3232
+ }
3233
+ }
3234
+ }
3235
+ }
3236
+ async function findNextTask(assignedTo) {
3237
+ const client = getClient();
3238
+ const nextResult = await client.execute({
3239
+ sql: `SELECT title, task_file, priority FROM tasks
3240
+ WHERE assigned_to = ? AND status = 'open'
3241
+ ORDER BY priority ASC, created_at ASC
3242
+ LIMIT 1`,
3243
+ args: [assignedTo]
3244
+ });
3245
+ if (nextResult.rows.length === 1) {
3246
+ const nr = nextResult.rows[0];
3247
+ return {
3248
+ title: String(nr.title),
3249
+ priority: String(nr.priority),
3250
+ taskFile: String(nr.task_file)
3251
+ };
3252
+ }
3253
+ return void 0;
3254
+ }
3255
+ async function checkSubtaskCompletion(parentTaskId, projectName) {
3256
+ const client = getClient();
3257
+ const remaining = await client.execute({
3258
+ sql: `SELECT COUNT(*) as cnt FROM tasks
3259
+ WHERE parent_task_id = ? AND status NOT IN ('done', 'cancelled')`,
3260
+ args: [parentTaskId]
3261
+ });
3262
+ const cnt = Number(remaining.rows[0]?.cnt ?? 1);
3263
+ if (cnt === 0) {
3264
+ const parentRow = await client.execute({
3265
+ sql: `SELECT assigned_to, title, task_file, project_name FROM tasks WHERE id = ?`,
3266
+ args: [parentTaskId]
3267
+ });
3268
+ if (parentRow.rows.length === 1) {
3269
+ const pr = parentRow.rows[0];
3270
+ const parentProject = pr.project_name == null ? projectName : String(pr.project_name);
3271
+ await writeNotification({
3272
+ agentId: String(pr.assigned_to),
3273
+ agentRole: "system",
3274
+ event: "subtasks_complete",
3275
+ project: parentProject,
3276
+ summary: `All subtasks complete for "${String(pr.title)}" \u2014 ready for rollup review`,
3277
+ taskFile: String(pr.task_file)
3278
+ });
3279
+ }
3280
+ }
3281
+ }
3282
+ var init_tasks_chain = __esm({
3283
+ "src/lib/tasks-chain.ts"() {
3284
+ "use strict";
3285
+ init_database();
3286
+ init_notifications();
3287
+ }
3288
+ });
3289
+
3290
+ // src/lib/session-scope.ts
3291
+ var session_scope_exports = {};
3292
+ __export(session_scope_exports, {
3293
+ assertSessionScope: () => assertSessionScope,
3294
+ findSessionForProject: () => findSessionForProject,
3295
+ getSessionProject: () => getSessionProject
3296
+ });
3297
+ function getSessionProject(sessionName) {
3298
+ const sessions = listSessions();
3299
+ const entry = sessions.find((s) => s.windowName === sessionName);
3300
+ if (!entry) return null;
3301
+ const parts = entry.projectDir.split("/").filter(Boolean);
3302
+ return parts[parts.length - 1] ?? null;
3303
+ }
3304
+ function findSessionForProject(projectName) {
3305
+ const sessions = listSessions();
3306
+ for (const s of sessions) {
3307
+ const proj = s.projectDir.split("/").filter(Boolean).pop();
3308
+ if (proj === projectName && s.agentId === "exe") return s;
3309
+ }
3310
+ return null;
3311
+ }
3312
+ function assertSessionScope(actionType, targetProject) {
3313
+ try {
3314
+ const currentProject = getProjectName();
3315
+ const exeSession = resolveExeSession();
3316
+ if (!exeSession) {
3317
+ return { allowed: true, reason: "no_session" };
3318
+ }
3319
+ if (currentProject === targetProject) {
3320
+ return {
3321
+ allowed: true,
3322
+ reason: "same_session",
3323
+ currentProject,
3324
+ targetProject
3325
+ };
3326
+ }
3327
+ process.stderr.write(
3328
+ `[session-scope] BLOCKED cross-project ${actionType}: session project="${currentProject}" \u2260 target project="${targetProject}"
3329
+ `
3330
+ );
3331
+ return {
3332
+ allowed: false,
3333
+ reason: "cross_session_denied",
3334
+ currentProject,
3335
+ targetProject,
3336
+ targetSession: findSessionForProject(targetProject)?.windowName
3337
+ };
3338
+ } catch {
3339
+ return { allowed: true, reason: "no_session" };
3340
+ }
3341
+ }
3342
+ var init_session_scope = __esm({
3343
+ "src/lib/session-scope.ts"() {
3344
+ "use strict";
3345
+ init_session_registry();
3346
+ init_project_name();
3347
+ init_tmux_routing();
3348
+ }
3349
+ });
3350
+
3351
+ // src/lib/tasks-notify.ts
3352
+ async function dispatchTaskToEmployee(input) {
3353
+ if (input.assignedTo === "exe") return { dispatched: "skipped" };
3354
+ let crossProject = false;
3355
+ if (input.projectName) {
3356
+ try {
3357
+ const { assertSessionScope: assertSessionScope2 } = (init_session_scope(), __toCommonJS(session_scope_exports));
3358
+ const check = assertSessionScope2("dispatch_task", input.projectName);
3359
+ if (check.reason === "cross_session_denied") {
3360
+ crossProject = true;
3361
+ return { dispatched: "skipped", crossProject: true };
3362
+ }
3363
+ } catch {
3364
+ }
3365
+ }
3366
+ try {
3367
+ const transport = getTransport();
3368
+ const exeSession = resolveExeSession();
3369
+ if (!exeSession) return { dispatched: "session_missing" };
3370
+ const sessionName = employeeSessionName(input.assignedTo, exeSession);
3371
+ if (transport.isAlive(sessionName)) {
3372
+ const result = sendIntercom(sessionName);
3373
+ const dispatched = result === "acknowledged" || result === "debounced" || result === "queued" ? "verified" : result === "delivered" ? "sent_unverified" : "session_dead";
3374
+ return { dispatched, session: sessionName, crossProject };
3375
+ } else {
3376
+ const projectDir = input.projectDir ?? process.cwd();
3377
+ const result = ensureEmployee(input.assignedTo, exeSession, projectDir, {
3378
+ autoInstance: isMultiInstance(input.assignedTo)
3379
+ });
3380
+ if (result.status === "failed") {
3381
+ process.stderr.write(
3382
+ `[dispatch] Failed to spawn ${input.assignedTo}: ${result.error}
3383
+ `
3384
+ );
3385
+ return { dispatched: "session_missing" };
3386
+ }
3387
+ return { dispatched: "spawned", session: result.sessionName, crossProject };
3388
+ }
3389
+ } catch {
3390
+ return { dispatched: "session_missing" };
3391
+ }
3392
+ }
3393
+ function notifyTaskDone() {
3394
+ try {
3395
+ const key = getSessionKey();
3396
+ if (key && !process.env.VITEST) notifyParentExe(key);
3397
+ } catch {
3398
+ }
3399
+ }
3400
+ async function markTaskNotificationsRead(taskFile) {
3401
+ try {
3402
+ await markAsReadByTaskFile(taskFile);
3403
+ } catch {
3404
+ }
3405
+ }
3406
+ var init_tasks_notify = __esm({
3407
+ "src/lib/tasks-notify.ts"() {
3408
+ "use strict";
3409
+ init_tmux_routing();
3410
+ init_session_key();
3411
+ init_notifications();
3412
+ init_transport();
3413
+ init_employees();
3414
+ }
3415
+ });
3416
+
3417
+ // src/lib/behaviors.ts
3418
+ import crypto5 from "crypto";
3419
+ async function storeBehavior(opts) {
3420
+ const client = getClient();
3421
+ const id = crypto5.randomUUID();
3422
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3423
+ await client.execute({
3424
+ sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, priority, content, active, created_at, updated_at)
3425
+ VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)`,
3426
+ args: [id, opts.agentId, opts.projectName ?? null, opts.domain ?? null, opts.priority ?? "p1", opts.content, now, now]
3427
+ });
3428
+ return id;
3429
+ }
3430
+ var init_behaviors = __esm({
3431
+ "src/lib/behaviors.ts"() {
3432
+ "use strict";
3433
+ init_database();
3434
+ }
3435
+ });
3436
+
3437
+ // src/lib/skill-learning.ts
3438
+ var skill_learning_exports = {};
3439
+ __export(skill_learning_exports, {
3440
+ captureAndLearn: () => captureAndLearn,
3441
+ captureTrajectory: () => captureTrajectory,
3442
+ editDistance: () => editDistance,
3443
+ extractSkill: () => extractSkill,
3444
+ extractTrajectory: () => extractTrajectory,
3445
+ findSimilarTrajectories: () => findSimilarTrajectories,
3446
+ hashSignature: () => hashSignature,
3447
+ storeTrajectory: () => storeTrajectory,
3448
+ sweepTrajectories: () => sweepTrajectories
3449
+ });
3450
+ import crypto6 from "crypto";
3451
+ async function extractTrajectory(taskId, agentId) {
3452
+ const client = getClient();
3453
+ const result = await client.execute({
3454
+ sql: `SELECT tool_name, raw_text
3455
+ FROM memories
3456
+ WHERE task_id = ? AND agent_id = ?
3457
+ ORDER BY timestamp ASC`,
3458
+ args: [taskId, agentId]
3459
+ });
3460
+ if (result.rows.length === 0) return [];
3461
+ const rawTools = result.rows.map((r) => {
3462
+ const toolName = String(r.tool_name);
3463
+ if (toolName === "Bash") {
3464
+ const text = String(r.raw_text);
3465
+ const cmdMatch = text.match(/(?:command|Command).*?[:\s]+"?(\w+)/);
3466
+ return cmdMatch ? `Bash:${cmdMatch[1]}` : "Bash";
3467
+ }
3468
+ return toolName;
3469
+ });
3470
+ const signature = [];
3471
+ for (const tool of rawTools) {
3472
+ if (signature.length === 0 || signature[signature.length - 1] !== tool) {
3473
+ signature.push(tool);
3474
+ }
3475
+ }
3476
+ return signature;
3477
+ }
3478
+ function hashSignature(signature) {
3479
+ return crypto6.createHash("sha256").update(signature.join("|")).digest("hex").slice(0, 16);
3480
+ }
3481
+ async function storeTrajectory(opts) {
3482
+ const client = getClient();
3483
+ const id = crypto6.randomUUID();
3484
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3485
+ const signatureHash = hashSignature(opts.signature);
3486
+ await client.execute({
3487
+ sql: `INSERT INTO trajectories (id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at)
3488
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
3489
+ args: [
3490
+ id,
3491
+ opts.taskId,
3492
+ opts.agentId,
3493
+ opts.projectName,
3494
+ opts.taskTitle,
3495
+ JSON.stringify(opts.signature),
3496
+ signatureHash,
3497
+ opts.signature.length,
3498
+ now
3499
+ ]
3500
+ });
3501
+ return id;
3502
+ }
3503
+ async function findSimilarTrajectories(signature, threshold = DEFAULT_SKILL_THRESHOLD) {
3504
+ const client = getClient();
3505
+ const hash = hashSignature(signature);
3506
+ const result = await client.execute({
3507
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
3508
+ FROM trajectories
3509
+ WHERE signature_hash = ?
3510
+ ORDER BY created_at DESC
3511
+ LIMIT 20`,
3512
+ args: [hash]
3513
+ });
3514
+ const mapRow = (r) => ({
3515
+ id: String(r.id),
3516
+ taskId: String(r.task_id),
3517
+ agentId: String(r.agent_id),
3518
+ projectName: String(r.project_name),
3519
+ taskTitle: String(r.task_title),
3520
+ signature: JSON.parse(String(r.signature)),
3521
+ signatureHash: String(r.signature_hash),
3522
+ toolCount: Number(r.tool_count),
3523
+ skillId: r.skill_id ? String(r.skill_id) : null,
3524
+ createdAt: String(r.created_at)
3525
+ });
3526
+ const matches = result.rows.map(mapRow);
3527
+ if (matches.length >= threshold) return matches;
3528
+ const nearResult = await client.execute({
3529
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
3530
+ FROM trajectories
3531
+ WHERE tool_count BETWEEN ? AND ?
3532
+ AND signature_hash != ?
3533
+ ORDER BY created_at DESC
3534
+ LIMIT 50`,
3535
+ args: [
3536
+ Math.max(1, signature.length - 3),
3537
+ signature.length + 3,
3538
+ hash
3539
+ ]
3540
+ });
3541
+ for (const r of nearResult.rows) {
3542
+ const candidateSig = JSON.parse(String(r.signature));
3543
+ if (editDistance(signature, candidateSig) <= 2) {
3544
+ matches.push(mapRow(r));
3545
+ }
3546
+ }
3547
+ return matches;
3548
+ }
3549
+ async function captureTrajectory(opts) {
3550
+ const signature = await extractTrajectory(opts.taskId, opts.agentId);
3551
+ if (signature.length < 3) {
3552
+ return { trajectoryId: "", similarCount: 0, similar: [] };
3553
+ }
3554
+ const trajectoryId = await storeTrajectory({
3555
+ taskId: opts.taskId,
3556
+ agentId: opts.agentId,
3557
+ projectName: opts.projectName,
3558
+ taskTitle: opts.taskTitle,
3559
+ signature
3560
+ });
3561
+ const similar = await findSimilarTrajectories(
3562
+ signature,
3563
+ opts.skillThreshold ?? DEFAULT_SKILL_THRESHOLD
3564
+ );
3565
+ return { trajectoryId, similarCount: similar.length, similar };
3566
+ }
3567
+ function buildExtractionPrompt(trajectories) {
3568
+ const items = trajectories.map((t, i) => {
3569
+ const sig = t.signature.join(" \u2192 ");
3570
+ return `Task ${i + 1}: "${t.taskTitle}" (${t.agentId}, ${t.projectName}) \u2014 ${t.toolCount} tool calls
3571
+ Signature: ${sig}`;
3572
+ }).join("\n\n");
3573
+ return `You are analyzing ${trajectories.length} completed tasks that followed similar procedures:
3574
+
3575
+ ${items}
3576
+
3577
+ Extract the reusable procedure. Format your response EXACTLY like this:
3578
+
3579
+ SKILL: {name \u2014 short, descriptive}
3580
+ TRIGGER: {when to use this \u2014 one sentence}
3581
+ STEPS:
3582
+ 1. ...
3583
+ 2. ...
3584
+ PITFALLS: {common mistakes to avoid}
3585
+
3586
+ Be specific and actionable. Include tool names, file patterns, and concrete commands where applicable.`;
3587
+ }
3588
+ async function extractSkill(trajectories, model) {
3589
+ if (trajectories.length === 0) return null;
3590
+ const config = await loadConfig();
3591
+ const skillModel = model ?? config.skillModel;
3592
+ const Anthropic = (await import("@anthropic-ai/sdk")).default;
3593
+ const client = new Anthropic();
3594
+ const prompt = buildExtractionPrompt(trajectories);
3595
+ const response = await client.messages.create({
3596
+ model: skillModel,
3597
+ max_tokens: 500,
3598
+ messages: [{ role: "user", content: prompt }]
3599
+ });
3600
+ const textBlock = response.content.find((b) => b.type === "text");
3601
+ const skillText = textBlock?.text;
3602
+ if (!skillText) return null;
3603
+ const agentId = trajectories[0].agentId;
3604
+ const projectName = trajectories[0].projectName;
3605
+ const skillId = await storeBehavior({
3606
+ agentId,
3607
+ content: skillText,
3608
+ domain: "skill",
3609
+ projectName
3610
+ });
3611
+ const dbClient = getClient();
3612
+ for (const t of trajectories) {
3613
+ await dbClient.execute({
3614
+ sql: "UPDATE trajectories SET skill_id = ? WHERE id = ?",
3615
+ args: [skillId, t.id]
3616
+ });
3617
+ }
3618
+ process.stderr.write(
3619
+ `[skill-learning] Skill extracted from ${trajectories.length} trajectories \u2192 behavior ${skillId}
3620
+ `
3621
+ );
3622
+ return skillId;
3623
+ }
3624
+ async function captureAndLearn(opts) {
3625
+ try {
3626
+ const config = await loadConfig();
3627
+ if (!config.skillLearning) return;
3628
+ const { trajectoryId, similarCount, similar } = await captureTrajectory({
3629
+ ...opts,
3630
+ skillThreshold: config.skillThreshold
3631
+ });
3632
+ if (!trajectoryId) return;
3633
+ if (similarCount >= config.skillThreshold) {
3634
+ const unprocessed = similar.filter((t) => !t.skillId);
3635
+ if (unprocessed.length >= config.skillThreshold) {
3636
+ extractSkill(unprocessed, config.skillModel).catch((err) => {
3637
+ process.stderr.write(
3638
+ `[skill-learning] Extraction failed: ${err instanceof Error ? err.message : String(err)}
3639
+ `
3640
+ );
3641
+ });
3642
+ }
3643
+ }
3644
+ } catch (err) {
3645
+ process.stderr.write(
3646
+ `[skill-learning] captureAndLearn failed: ${err instanceof Error ? err.message : String(err)}
3647
+ `
3648
+ );
3649
+ }
3650
+ }
3651
+ async function sweepTrajectories(threshold, model) {
3652
+ const config = await loadConfig();
3653
+ if (!config.skillLearning) return { clustersProcessed: 0, skillsExtracted: 0 };
3654
+ const t = threshold ?? config.skillThreshold;
3655
+ const client = getClient();
3656
+ const result = await client.execute({
3657
+ sql: `SELECT signature_hash, COUNT(*) as cnt
3658
+ FROM trajectories
3659
+ WHERE skill_id IS NULL
3660
+ GROUP BY signature_hash
3661
+ HAVING cnt >= ?
3662
+ ORDER BY cnt DESC
3663
+ LIMIT 10`,
3664
+ args: [t]
3665
+ });
3666
+ let clustersProcessed = 0;
3667
+ let skillsExtracted = 0;
3668
+ for (const row of result.rows) {
3669
+ const hash = String(row.signature_hash);
3670
+ const trajResult = await client.execute({
3671
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at
3672
+ FROM trajectories
3673
+ WHERE signature_hash = ? AND skill_id IS NULL
3674
+ ORDER BY created_at DESC
3675
+ LIMIT 10`,
3676
+ args: [hash]
3677
+ });
3678
+ const trajectories = trajResult.rows.map((r) => ({
3679
+ id: String(r.id),
3680
+ taskId: String(r.task_id),
3681
+ agentId: String(r.agent_id),
3682
+ projectName: String(r.project_name),
3683
+ taskTitle: String(r.task_title),
3684
+ signature: JSON.parse(String(r.signature)),
3685
+ signatureHash: String(r.signature_hash),
3686
+ toolCount: Number(r.tool_count),
3687
+ skillId: null,
3688
+ createdAt: String(r.created_at)
3689
+ }));
3690
+ if (trajectories.length >= t) {
3691
+ clustersProcessed++;
3692
+ const skillId = await extractSkill(trajectories, model ?? config.skillModel);
3693
+ if (skillId) skillsExtracted++;
3694
+ }
3695
+ }
3696
+ return { clustersProcessed, skillsExtracted };
3697
+ }
3698
+ function editDistance(a, b) {
3699
+ const m = a.length;
3700
+ const n = b.length;
3701
+ const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
3702
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
3703
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
3704
+ for (let i = 1; i <= m; i++) {
3705
+ for (let j = 1; j <= n; j++) {
3706
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
3707
+ dp[i][j] = Math.min(
3708
+ dp[i - 1][j] + 1,
3709
+ dp[i][j - 1] + 1,
3710
+ dp[i - 1][j - 1] + cost
3711
+ );
3712
+ }
3713
+ }
3714
+ return dp[m][n];
3715
+ }
3716
+ var DEFAULT_SKILL_THRESHOLD;
3717
+ var init_skill_learning = __esm({
3718
+ "src/lib/skill-learning.ts"() {
3719
+ "use strict";
3720
+ init_database();
3721
+ init_behaviors();
3722
+ init_config();
3723
+ DEFAULT_SKILL_THRESHOLD = 3;
3724
+ }
3725
+ });
3726
+
3727
+ // src/lib/tasks.ts
3728
+ var tasks_exports = {};
3729
+ __export(tasks_exports, {
3730
+ cleanupOrphanedReviews: () => cleanupOrphanedReviews,
3731
+ countNewPendingReviewsSince: () => countNewPendingReviewsSince,
3732
+ countPendingReviews: () => countPendingReviews,
3733
+ createTask: () => createTask,
3734
+ createTaskCore: () => createTaskCore,
3735
+ deleteTask: () => deleteTask,
3736
+ deleteTaskCore: () => deleteTaskCore,
3737
+ ensureArchitectureDoc: () => ensureArchitectureDoc,
3738
+ ensureGitignoreExe: () => ensureGitignoreExe,
3739
+ getReviewChecklist: () => getReviewChecklist,
3740
+ listPendingReviews: () => listPendingReviews,
3741
+ listTasks: () => listTasks,
3742
+ resolveTask: () => resolveTask,
3743
+ slugify: () => slugify,
3744
+ updateTask: () => updateTask,
3745
+ updateTaskStatus: () => updateTaskStatus,
3746
+ writeCheckpoint: () => writeCheckpoint
3747
+ });
3748
+ import path14 from "path";
3749
+ import { writeFileSync as writeFileSync4, mkdirSync as mkdirSync5, unlinkSync as unlinkSync3 } from "fs";
3750
+ async function createTask(input) {
3751
+ const result = await createTaskCore(input);
3752
+ if (!input.skipDispatch && result.status !== "blocked" && !process.env.VITEST) {
3753
+ dispatchTaskToEmployee({
3754
+ assignedTo: input.assignedTo,
3755
+ title: input.title,
3756
+ priority: input.priority,
3757
+ taskFile: result.taskFile,
3758
+ initialStatus: result.status,
3759
+ projectName: input.projectName
3760
+ });
3761
+ }
3762
+ return result;
3763
+ }
3764
+ async function updateTask(input) {
3765
+ const { row, taskFile, now, taskId } = await updateTaskStatus(input);
3766
+ try {
3767
+ const agent = String(row.assigned_to);
3768
+ const cacheDir = path14.join(EXE_AI_DIR, "session-cache");
3769
+ const cachePath = path14.join(cacheDir, `current-task-${agent}.json`);
3770
+ if (input.status === "in_progress") {
3771
+ mkdirSync5(cacheDir, { recursive: true });
3772
+ writeFileSync4(cachePath, JSON.stringify({ taskId, title: String(row.title) }));
3773
+ } else if (input.status === "done" || input.status === "blocked" || input.status === "cancelled") {
3774
+ try {
3775
+ unlinkSync3(cachePath);
3776
+ } catch {
3777
+ }
3778
+ }
3779
+ } catch {
3780
+ }
3781
+ if (input.status === "done") {
3782
+ await cleanupReviewFile(row, taskFile, input.baseDir);
3783
+ }
3784
+ if (input.status === "done" || input.status === "cancelled") {
3785
+ try {
3786
+ const client = getClient();
3787
+ const taskTitle = String(row.title);
3788
+ const escaped = taskTitle.replace(/%/g, "\\%").replace(/_/g, "\\_");
3789
+ await client.execute({
3790
+ sql: `UPDATE tasks SET status = 'cancelled', updated_at = ?
3791
+ WHERE title LIKE ? ESCAPE '\\' AND status IN ('open', 'in_progress')`,
3792
+ args: [now, `%left '${escaped}' as in\\_progress%`]
3793
+ });
3794
+ } catch {
3795
+ }
3796
+ try {
3797
+ const client = getClient();
3798
+ const cascaded = await client.execute({
3799
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
3800
+ WHERE parent_task_id = ? AND status = 'needs_review'`,
3801
+ args: [now, taskId]
3802
+ });
3803
+ if (cascaded.rowsAffected > 0) {
3804
+ process.stderr.write(
3805
+ `[cascade] Closed ${cascaded.rowsAffected} orphaned review task(s) for parent ${taskId}
3806
+ `
3807
+ );
3808
+ }
3809
+ } catch {
3810
+ }
3811
+ }
3812
+ const isTerminal = input.status === "done" || input.status === "needs_review";
3813
+ if (isTerminal) {
3814
+ const isExe = String(row.assigned_to) === "exe";
3815
+ if (!isExe) {
3816
+ notifyTaskDone();
3817
+ }
3818
+ await markTaskNotificationsRead(taskFile);
3819
+ if (input.status === "done") {
3820
+ try {
3821
+ await cascadeUnblock(taskId, input.baseDir, now);
3822
+ } catch {
3823
+ }
3824
+ orgBus.emit({
3825
+ type: "task_completed",
3826
+ taskId,
3827
+ employee: String(row.assigned_to),
3828
+ result: input.result ?? "",
3829
+ timestamp: now
3830
+ });
3831
+ if (row.parent_task_id) {
3832
+ try {
3833
+ await checkSubtaskCompletion(String(row.parent_task_id), String(row.project_name));
3834
+ } catch {
3835
+ }
3836
+ }
3837
+ }
3838
+ }
3839
+ if (input.status === "done" && String(row.assigned_to) !== "exe" && !process.env.VITEST) {
3840
+ Promise.resolve().then(() => (init_skill_learning(), skill_learning_exports)).then(
3841
+ ({ captureAndLearn: captureAndLearn2 }) => captureAndLearn2({
3842
+ taskId,
3843
+ agentId: String(row.assigned_to),
3844
+ projectName: String(row.project_name),
3845
+ taskTitle: String(row.title)
3846
+ })
3847
+ ).catch((err) => {
3848
+ process.stderr.write(
3849
+ `[updateTask] skill learning failed: ${err instanceof Error ? err.message : String(err)}
3850
+ `
3851
+ );
3852
+ });
3853
+ }
3854
+ let nextTask;
3855
+ if (isTerminal && String(row.assigned_to) !== "exe") {
3856
+ try {
3857
+ nextTask = await findNextTask(String(row.assigned_to));
3858
+ } catch {
3859
+ }
3860
+ }
3861
+ return {
3862
+ id: String(row.id),
3863
+ title: String(row.title),
3864
+ assignedTo: String(row.assigned_to),
3865
+ assignedBy: String(row.assigned_by),
3866
+ projectName: String(row.project_name),
3867
+ priority: String(row.priority),
3868
+ status: input.status,
3869
+ taskFile,
3870
+ createdAt: String(row.created_at),
3871
+ updatedAt: now,
3872
+ budgetTokens: row.budget_tokens !== void 0 && row.budget_tokens !== null ? Number(row.budget_tokens) : null,
3873
+ budgetFallbackModel: row.budget_fallback_model !== void 0 && row.budget_fallback_model !== null ? String(row.budget_fallback_model) : null,
3874
+ tokensUsed: Number(row.tokens_used ?? 0),
3875
+ tokensWarnedAt: row.tokens_warned_at !== void 0 && row.tokens_warned_at !== null ? Number(row.tokens_warned_at) : null,
3876
+ nextTask
3877
+ };
3878
+ }
3879
+ async function deleteTask(taskId, baseDir) {
3880
+ const client = getClient();
3881
+ const { taskFile, assignedTo, assignedBy, taskSlug } = await deleteTaskCore(taskId, baseDir);
3882
+ const reviewer = assignedBy || "exe";
3883
+ const reviewSlug = `review-${assignedTo}-${taskSlug}`;
3884
+ const reviewFile = `exe/${reviewer}/${reviewSlug}.md`;
3885
+ await client.execute({
3886
+ sql: "DELETE FROM tasks WHERE task_file = ? OR task_file = ?",
3887
+ args: [reviewFile, `exe/exe/${reviewSlug}.md`]
3888
+ });
3889
+ await markAsReadByTaskFile(taskFile);
3890
+ await markAsReadByTaskFile(reviewFile);
3891
+ }
3892
+ var init_tasks = __esm({
3893
+ "src/lib/tasks.ts"() {
3894
+ "use strict";
3895
+ init_database();
3896
+ init_config();
3897
+ init_notifications();
3898
+ init_state_bus();
3899
+ init_tasks_crud();
3900
+ init_tasks_review();
3901
+ init_tasks_crud();
3902
+ init_tasks_chain();
3903
+ init_tasks_review();
3904
+ init_tasks_notify();
3905
+ }
3906
+ });
3907
+
3908
+ // src/lib/capacity-monitor.ts
3909
+ var capacity_monitor_exports = {};
3910
+ __export(capacity_monitor_exports, {
3911
+ CTX_FLOOR_PERCENT: () => CTX_FLOOR_PERCENT,
3912
+ _resetLastRelaunchCache: () => _resetLastRelaunchCache,
3913
+ _resetPendingCapacityKills: () => _resetPendingCapacityKills,
3914
+ confirmCapacityKill: () => confirmCapacityKill,
3915
+ createOrRefreshResumeTask: () => createOrRefreshResumeTask,
3916
+ extractContextPercent: () => extractContextPercent,
3917
+ isAtCapacity: () => isAtCapacity,
3918
+ isWithinRelaunchCooldown: () => isWithinRelaunchCooldown,
3919
+ pollCapacityDead: () => pollCapacityDead
3920
+ });
3921
+ function resumeTaskTitle(agentId) {
3922
+ return `${RESUME_TITLE_PREFIX} ${agentId} hit context capacity \u2014 continue open tasks`;
3923
+ }
3924
+ function buildResumeContext(agentId, openTasks) {
3925
+ const taskList = openTasks.map(
3926
+ (r, i) => `${i + 1}. [${String(r.priority).toUpperCase()}] ${String(r.title)} (${String(r.task_file)})`
3927
+ ).join("\n");
3928
+ return [
3929
+ "## Context",
3930
+ "",
3931
+ `${agentId} hit context capacity and was auto-relaunched by the capacity monitor.`,
3932
+ "Call recall_my_memory first \u2014 search for 'CONTEXT CHECKPOINT'. Pick up where the previous session stopped.",
3933
+ "",
3934
+ `You have ${openTasks.length} open task(s). Work through them in priority order:`,
3935
+ "",
3936
+ taskList,
3937
+ "",
3938
+ "Read each task file and chain through them. Build and commit after each one."
3939
+ ].join("\n");
3940
+ }
3941
+ function filterPaneContent(paneOutput) {
3942
+ return paneOutput.split("\n").filter((line) => {
3943
+ if (CONTENT_LINE_PREFIX.test(line)) return false;
3944
+ for (const marker of CONTENT_LINE_MARKERS) {
3945
+ if (line.includes(marker)) return false;
3946
+ }
3947
+ for (const re of SOURCE_CODE_MARKERS) {
3948
+ if (re.test(line)) return false;
3949
+ }
3950
+ return true;
3951
+ }).join("\n");
3952
+ }
3953
+ function extractContextPercent(paneOutput) {
3954
+ const match = paneOutput.match(CC_CONTEXT_BAR_RE);
3955
+ if (!match) return null;
3956
+ const parsed = Number.parseInt(match[2], 10);
3957
+ return Number.isFinite(parsed) ? parsed : null;
3958
+ }
3959
+ function isAtCapacity(paneOutput) {
3960
+ const filtered = filterPaneContent(paneOutput);
3961
+ return CAPACITY_PATTERNS.some((p) => p.test(filtered));
3962
+ }
3963
+ function confirmCapacityKill(agentId, now = Date.now()) {
3964
+ const pendingSince = _pendingCapacityKill.get(agentId);
3965
+ if (pendingSince === void 0) {
3966
+ _pendingCapacityKill.set(agentId, now);
3967
+ return false;
3968
+ }
3969
+ if (now - pendingSince > CONFIRMATION_WINDOW_MS) {
3970
+ _pendingCapacityKill.set(agentId, now);
3971
+ return false;
3972
+ }
3973
+ _pendingCapacityKill.delete(agentId);
3974
+ return true;
3975
+ }
3976
+ function _resetPendingCapacityKills() {
3977
+ _pendingCapacityKill.clear();
3978
+ }
3979
+ function _resetLastRelaunchCache() {
3980
+ _lastRelaunch.clear();
3981
+ }
3982
+ async function lastResumeCreatedAtMs(agentId) {
3983
+ const client = getClient();
3984
+ const result = await client.execute({
3985
+ sql: `SELECT MAX(created_at) AS last_created_at
3986
+ FROM tasks
3987
+ WHERE assigned_to = ? AND title LIKE ?`,
3988
+ args: [agentId, `${RESUME_TITLE_PREFIX} %`]
3989
+ });
3990
+ const raw = result.rows[0]?.last_created_at;
3991
+ if (raw === null || raw === void 0) return null;
3992
+ const parsed = Date.parse(String(raw));
3993
+ return Number.isNaN(parsed) ? null : parsed;
3994
+ }
3995
+ async function isWithinRelaunchCooldown(agentId, now = Date.now()) {
3996
+ const cached = _lastRelaunch.get(agentId);
3997
+ if (cached !== void 0) return now - cached < RELAUNCH_COOLDOWN_MS;
3998
+ const persisted = await lastResumeCreatedAtMs(agentId);
3999
+ if (persisted === null) return false;
4000
+ if (now - persisted >= RELAUNCH_COOLDOWN_MS) return false;
4001
+ _lastRelaunch.set(agentId, persisted);
4002
+ return true;
4003
+ }
4004
+ async function createOrRefreshResumeTask(agentId, projectDir, openTasks) {
4005
+ const client = getClient();
4006
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4007
+ const context = buildResumeContext(agentId, openTasks);
4008
+ const existing = await client.execute({
4009
+ sql: `SELECT id FROM tasks
4010
+ WHERE assigned_to = ?
4011
+ AND title LIKE ?
4012
+ AND status IN (${RESUME_ACTIVE_STATUSES.map(() => "?").join(", ")})
4013
+ ORDER BY created_at DESC
4014
+ LIMIT 1`,
4015
+ args: [agentId, RESUME_TITLE_LIKE_PATTERN, ...RESUME_ACTIVE_STATUSES]
4016
+ });
4017
+ if (existing.rows.length > 0) {
4018
+ const taskId = String(existing.rows[0].id);
4019
+ await client.execute({
4020
+ sql: `UPDATE tasks SET context = ?, updated_at = ? WHERE id = ?`,
4021
+ args: [context, now, taskId]
4022
+ });
4023
+ return { created: false, taskId };
4024
+ }
4025
+ const { createTask: createTask2 } = await Promise.resolve().then(() => (init_tasks(), tasks_exports));
4026
+ const task = await createTask2({
4027
+ title: resumeTaskTitle(agentId),
4028
+ assignedTo: agentId,
4029
+ assignedBy: "system",
4030
+ projectName: projectDir.split("/").pop() ?? "unknown",
4031
+ priority: "p0",
4032
+ context,
4033
+ baseDir: projectDir
4034
+ });
4035
+ return { created: true, taskId: task.id };
4036
+ }
4037
+ async function pollCapacityDead() {
4038
+ const transport = getTransport();
4039
+ const relaunched = [];
4040
+ const registered = listSessions().filter(
4041
+ (s) => s.agentId !== "exe"
4042
+ );
4043
+ if (registered.length === 0) return [];
4044
+ let liveSessions;
4045
+ try {
4046
+ liveSessions = transport.listSessions();
4047
+ } catch {
4048
+ return [];
4049
+ }
4050
+ for (const entry of registered) {
4051
+ const { windowName, agentId, projectDir } = entry;
4052
+ if (!liveSessions.includes(windowName)) continue;
4053
+ if (await isWithinRelaunchCooldown(agentId)) continue;
4054
+ let pane;
4055
+ try {
4056
+ pane = transport.capturePane(windowName, 15);
4057
+ } catch {
4058
+ continue;
4059
+ }
4060
+ if (!isAtCapacity(pane)) continue;
4061
+ const ctxPct = extractContextPercent(pane);
4062
+ if (ctxPct !== null && ctxPct < CTX_FLOOR_PERCENT) {
4063
+ process.stderr.write(
4064
+ `[capacity-monitor] ctx-floor: ${agentId} at ${ctxPct}% in ${windowName} \u2014 below ${CTX_FLOOR_PERCENT}%. Skipping capacity kill (likely self-referential content or false positive).
4065
+ `
4066
+ );
4067
+ continue;
4068
+ }
4069
+ if (!confirmCapacityKill(agentId)) {
4070
+ process.stderr.write(
4071
+ `[capacity-monitor] ${agentId} matched capacity pattern once in ${windowName}. Awaiting confirmation on next tick.
4072
+ `
4073
+ );
4074
+ continue;
4075
+ }
4076
+ const verify = await verifyPaneAtCapacity(windowName);
4077
+ if (!verify.atCapacity) {
4078
+ process.stderr.write(
4079
+ `[capacity-monitor] verifyPaneAtCapacity rejected kill for ${agentId} in ${windowName} (reason: ${verify.reason}). Skipping.
4080
+ `
4081
+ );
4082
+ void recordSessionKill({
4083
+ sessionName: windowName,
4084
+ agentId,
4085
+ reason: "capacity_false_positive_blocked"
4086
+ });
4087
+ continue;
4088
+ }
4089
+ process.stderr.write(
4090
+ `[capacity-monitor] Detected ${agentId} at capacity in session ${windowName} (confirmed). Auto-relaunching.
4091
+ `
4092
+ );
4093
+ try {
4094
+ transport.kill(windowName);
4095
+ void recordSessionKill({
4096
+ sessionName: windowName,
4097
+ agentId,
4098
+ reason: "capacity"
4099
+ });
4100
+ const client = getClient();
4101
+ const openTasks = await client.execute({
4102
+ sql: `SELECT id, title, priority, task_file, status
4103
+ FROM tasks
4104
+ WHERE assigned_to = ? AND status IN ('open', 'in_progress')
4105
+ ORDER BY
4106
+ CASE priority WHEN 'p0' THEN 0 WHEN 'p1' THEN 1 WHEN 'p2' THEN 2 ELSE 3 END,
4107
+ created_at ASC
4108
+ LIMIT 10`,
4109
+ args: [agentId]
4110
+ });
4111
+ if (openTasks.rows.length === 0) {
4112
+ process.stderr.write(
4113
+ `[capacity-monitor] ${agentId} has no open tasks \u2014 skipping relaunch.
4114
+ `
4115
+ );
4116
+ continue;
4117
+ }
4118
+ const { created } = await createOrRefreshResumeTask(
4119
+ agentId,
4120
+ projectDir,
4121
+ openTasks.rows
4122
+ );
4123
+ if (created) {
4124
+ await writeNotification({
4125
+ agentId: "system",
4126
+ agentRole: "daemon",
4127
+ event: "capacity_relaunch",
4128
+ project: projectDir.split("/").pop() ?? "unknown",
4129
+ summary: `${agentId} hit context capacity. Auto-relaunched with ${openTasks.rows.length} open task(s).`
4130
+ });
4131
+ }
4132
+ _lastRelaunch.set(agentId, Date.now());
4133
+ if (created) relaunched.push(agentId);
4134
+ } catch (err) {
4135
+ process.stderr.write(
4136
+ `[capacity-monitor] Failed to relaunch ${agentId}: ${err instanceof Error ? err.message : String(err)}
4137
+ `
4138
+ );
4139
+ }
4140
+ }
4141
+ return relaunched;
4142
+ }
4143
+ 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;
4144
+ var init_capacity_monitor = __esm({
4145
+ "src/lib/capacity-monitor.ts"() {
4146
+ "use strict";
4147
+ init_session_registry();
4148
+ init_transport();
4149
+ init_notifications();
4150
+ init_database();
4151
+ init_session_kill_telemetry();
4152
+ init_tmux_routing();
4153
+ CAPACITY_PATTERNS = [
4154
+ /conversation is too long/i,
4155
+ /maximum context length/i,
4156
+ /context window.*(?:limit|exceed|full)/i,
4157
+ /reached.*(?:token|context).*limit/i
4158
+ ];
4159
+ CONTENT_LINE_PREFIX = /^[\s>#\-*[]/;
4160
+ CONTENT_LINE_MARKERS = [
4161
+ "RESUME:",
4162
+ "intercom",
4163
+ "capacity-monitor",
4164
+ "CAPACITY_PATTERNS",
4165
+ "isAtCapacity",
4166
+ "CONTENT_LINE_MARKERS",
4167
+ "pollCapacityDead",
4168
+ "confirmCapacityKill",
4169
+ "session_kills",
4170
+ "capacity-monitor.test"
4171
+ ];
4172
+ SOURCE_CODE_MARKERS = [
4173
+ /["'`/].*(?:maximum context length|conversation is too long)/i,
4174
+ /(?:maximum context length|conversation is too long).*["'`/]/i
4175
+ ];
4176
+ RELAUNCH_COOLDOWN_MS = 5 * 60 * 1e3;
4177
+ _lastRelaunch = /* @__PURE__ */ new Map();
4178
+ RESUME_TITLE_PREFIX = "RESUME:";
4179
+ RESUME_TITLE_LIKE_PATTERN = `${RESUME_TITLE_PREFIX} % hit context capacity%`;
4180
+ RESUME_ACTIVE_STATUSES = ["open", "in_progress"];
4181
+ CONFIRMATION_WINDOW_MS = 3 * 60 * 1e3;
4182
+ _pendingCapacityKill = /* @__PURE__ */ new Map();
4183
+ CC_CONTEXT_BAR_RE = /([\u2588\u2591\u2592\u2593]{10})\s+(\d+)%/;
4184
+ CTX_FLOOR_PERCENT = 50;
4185
+ }
4186
+ });
4187
+
4188
+ // src/lib/tmux-routing.ts
4189
+ var tmux_routing_exports = {};
4190
+ __export(tmux_routing_exports, {
4191
+ acquireSpawnLock: () => acquireSpawnLock,
4192
+ employeeSessionName: () => employeeSessionName,
4193
+ ensureEmployee: () => ensureEmployee,
4194
+ extractRootExe: () => extractRootExe,
4195
+ findFreeInstance: () => findFreeInstance,
4196
+ getDispatchedBy: () => getDispatchedBy,
4197
+ getMySession: () => getMySession,
4198
+ getParentExe: () => getParentExe,
4199
+ getSessionState: () => getSessionState,
4200
+ isEmployeeAlive: () => isEmployeeAlive,
4201
+ isExeSession: () => isExeSession,
4202
+ isSessionBusy: () => isSessionBusy,
4203
+ notifyParentExe: () => notifyParentExe,
4204
+ parseParentExe: () => parseParentExe,
4205
+ registerParentExe: () => registerParentExe,
4206
+ releaseSpawnLock: () => releaseSpawnLock,
4207
+ resolveExeSession: () => resolveExeSession,
4208
+ sendIntercom: () => sendIntercom,
4209
+ spawnEmployee: () => spawnEmployee,
4210
+ verifyPaneAtCapacity: () => verifyPaneAtCapacity
4211
+ });
4212
+ import { execFileSync as execFileSync2, execSync as execSync6 } from "child_process";
4213
+ import { readFileSync as readFileSync9, writeFileSync as writeFileSync5, mkdirSync as mkdirSync6, existsSync as existsSync12, appendFileSync } from "fs";
4214
+ import path15 from "path";
4215
+ import os6 from "os";
4216
+ import { fileURLToPath as fileURLToPath2 } from "url";
4217
+ import { unlinkSync as unlinkSync4 } from "fs";
4218
+ function spawnLockPath(sessionName) {
4219
+ return path15.join(SPAWN_LOCK_DIR, `${sessionName}.lock`);
4220
+ }
4221
+ function isProcessAlive(pid) {
4222
+ try {
4223
+ process.kill(pid, 0);
4224
+ return true;
4225
+ } catch {
4226
+ return false;
4227
+ }
4228
+ }
4229
+ function acquireSpawnLock(sessionName) {
4230
+ if (!existsSync12(SPAWN_LOCK_DIR)) {
4231
+ mkdirSync6(SPAWN_LOCK_DIR, { recursive: true });
4232
+ }
4233
+ const lockFile = spawnLockPath(sessionName);
4234
+ if (existsSync12(lockFile)) {
4235
+ try {
4236
+ const lock = JSON.parse(readFileSync9(lockFile, "utf8"));
4237
+ const age = Date.now() - lock.timestamp;
4238
+ if (isProcessAlive(lock.pid) && age < 6e4) {
4239
+ return false;
4240
+ }
4241
+ } catch {
4242
+ }
4243
+ }
4244
+ writeFileSync5(lockFile, JSON.stringify({ pid: process.pid, timestamp: Date.now() }));
4245
+ return true;
4246
+ }
4247
+ function releaseSpawnLock(sessionName) {
4248
+ try {
4249
+ unlinkSync4(spawnLockPath(sessionName));
4250
+ } catch {
4251
+ }
4252
+ }
4253
+ function resolveBehaviorsExporterScript() {
4254
+ try {
4255
+ const thisFile = fileURLToPath2(import.meta.url);
4256
+ const scriptPath = path15.join(
4257
+ path15.dirname(thisFile),
4258
+ "..",
4259
+ "bin",
4260
+ "exe-export-behaviors.js"
4261
+ );
4262
+ return existsSync12(scriptPath) ? scriptPath : null;
4263
+ } catch {
4264
+ return null;
4265
+ }
4266
+ }
4267
+ function exportBehaviorsSync(agentId, projectName, sessionKey) {
4268
+ const script = resolveBehaviorsExporterScript();
4269
+ if (!script) return null;
4270
+ try {
4271
+ const output = execFileSync2(
4272
+ process.execPath,
4273
+ [script, agentId, projectName, sessionKey],
4274
+ { encoding: "utf-8", timeout: BEHAVIORS_EXPORT_TIMEOUT_MS }
4275
+ ).trim();
4276
+ return output.length > 0 ? output : null;
4277
+ } catch (err) {
4278
+ process.stderr.write(
4279
+ `[tmux-routing] behaviors export failed for ${agentId}: ${err instanceof Error ? err.message : String(err)}
4280
+ `
4281
+ );
4282
+ return null;
4283
+ }
4284
+ }
4285
+ function getMySession() {
4286
+ return getTransport().getMySession();
4287
+ }
4288
+ function employeeSessionName(employee, exeSession, instance) {
4289
+ if (!/^exe\d+$/.test(exeSession)) {
4290
+ const root = extractRootExe(exeSession);
4291
+ if (root) {
4292
+ process.stderr.write(
4293
+ `[tmux-routing] WARN: exeSession="${exeSession}" is not a root exe session, using "${root}" instead
4294
+ `
4295
+ );
4296
+ exeSession = root;
4297
+ } else {
4298
+ throw new Error(
4299
+ `Invalid exeSession "${exeSession}" \u2014 must be a root exe session (e.g., "exe1"), not an agent session`
4300
+ );
4301
+ }
4302
+ }
4303
+ const suffix = instance != null && instance > 0 ? String(instance) : "";
4304
+ const name = `${employee}${suffix}-${exeSession}`;
4305
+ if (!VALID_SESSION_NAME.test(name)) {
4306
+ throw new Error(
4307
+ `Invalid session name "${name}" \u2014 must match {agent}-exe{N} or {agent}{instance}-exe{N}`
4308
+ );
4309
+ }
4310
+ return name;
4311
+ }
4312
+ function parseParentExe(sessionName, agentId) {
4313
+ const escaped = agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4314
+ const regex = new RegExp(`^${escaped}\\d*-(.+)$`);
4315
+ const match = sessionName.match(regex);
4316
+ return match?.[1] ?? null;
4317
+ }
4318
+ function extractRootExe(name) {
4319
+ const match = name.match(/(exe\d+)$/);
4320
+ return match?.[1] ?? null;
4321
+ }
4322
+ function registerParentExe(sessionKey, parentExe, dispatchedBy) {
4323
+ if (!existsSync12(SESSION_CACHE)) {
4324
+ mkdirSync6(SESSION_CACHE, { recursive: true });
4325
+ }
4326
+ const rootExe = extractRootExe(parentExe) ?? parentExe;
4327
+ const filePath = path15.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`);
4328
+ writeFileSync5(filePath, JSON.stringify({
4329
+ parentExe: rootExe,
4330
+ dispatchedBy: dispatchedBy || rootExe,
4331
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString()
4332
+ }));
4333
+ }
4334
+ function getParentExe(sessionKey) {
4335
+ try {
4336
+ const data = JSON.parse(readFileSync9(path15.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
4337
+ return data.parentExe || null;
4338
+ } catch {
4339
+ return null;
4340
+ }
4341
+ }
4342
+ function getDispatchedBy(sessionKey) {
4343
+ try {
4344
+ const data = JSON.parse(readFileSync9(
4345
+ path15.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`),
4346
+ "utf8"
4347
+ ));
4348
+ return data.dispatchedBy ?? data.parentExe ?? null;
4349
+ } catch {
4350
+ return null;
4351
+ }
4352
+ }
4353
+ function resolveExeSession() {
4354
+ const mySession = getMySession();
4355
+ if (!mySession) return null;
4356
+ try {
4357
+ const key = getSessionKey();
4358
+ const parentExe = getParentExe(key);
4359
+ if (parentExe) {
4360
+ return extractRootExe(parentExe) ?? parentExe;
4361
+ }
4362
+ } catch {
4363
+ }
4364
+ return extractRootExe(mySession) ?? mySession;
4365
+ }
4366
+ function isEmployeeAlive(sessionName) {
4367
+ return getTransport().isAlive(sessionName);
4368
+ }
4369
+ function findFreeInstance(employeeName, exeSession, maxInstances = 10, isAlive = isEmployeeAlive) {
4370
+ const base = employeeSessionName(employeeName, exeSession);
4371
+ if (!isAlive(base) && acquireSpawnLock(base)) return 0;
4372
+ for (let i = 2; i <= maxInstances; i++) {
4373
+ const candidate = employeeSessionName(employeeName, exeSession, i);
4374
+ if (!isAlive(candidate) && acquireSpawnLock(candidate)) return i;
4375
+ }
4376
+ return null;
4377
+ }
4378
+ async function verifyPaneAtCapacity(sessionName) {
4379
+ const transport = getTransport();
4380
+ if (!transport.isAlive(sessionName)) {
4381
+ return { atCapacity: false, reason: `session ${sessionName} is not alive` };
4382
+ }
4383
+ let pane;
4384
+ try {
4385
+ pane = transport.capturePane(sessionName, VERIFY_PANE_LINES);
4386
+ } catch (err) {
4387
+ return {
4388
+ atCapacity: false,
4389
+ reason: `capture-pane failed: ${err instanceof Error ? err.message : String(err)}`
4390
+ };
4391
+ }
4392
+ const { isAtCapacity: isAtCapacity2 } = await Promise.resolve().then(() => (init_capacity_monitor(), capacity_monitor_exports));
4393
+ if (!isAtCapacity2(pane)) {
4394
+ return {
4395
+ atCapacity: false,
4396
+ reason: `last ${VERIFY_PANE_LINES} lines show normal work, no capacity banner`
4397
+ };
4398
+ }
4399
+ return {
4400
+ atCapacity: true,
4401
+ reason: "capacity banner matched in recent pane output"
4402
+ };
4403
+ }
4404
+ function readDebounceState() {
4405
+ try {
4406
+ if (!existsSync12(DEBOUNCE_FILE)) return {};
4407
+ return JSON.parse(readFileSync9(DEBOUNCE_FILE, "utf8"));
4408
+ } catch {
4409
+ return {};
4410
+ }
4411
+ }
4412
+ function writeDebounceState(state) {
4413
+ try {
4414
+ if (!existsSync12(SESSION_CACHE)) mkdirSync6(SESSION_CACHE, { recursive: true });
4415
+ writeFileSync5(DEBOUNCE_FILE, JSON.stringify(state));
4416
+ } catch {
4417
+ }
4418
+ }
4419
+ function isDebounced(targetSession) {
4420
+ const state = readDebounceState();
4421
+ const lastSent = state[targetSession] ?? 0;
4422
+ return Date.now() - lastSent < INTERCOM_DEBOUNCE_MS;
4423
+ }
4424
+ function recordDebounce(targetSession) {
4425
+ const state = readDebounceState();
4426
+ state[targetSession] = Date.now();
4427
+ const cutoff = Date.now() - DEBOUNCE_CLEANUP_AGE_MS;
4428
+ for (const key of Object.keys(state)) {
4429
+ if ((state[key] ?? 0) < cutoff) delete state[key];
4430
+ }
4431
+ writeDebounceState(state);
4432
+ }
4433
+ function logIntercom(msg) {
4434
+ const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${msg}
4435
+ `;
4436
+ process.stderr.write(`[intercom] ${msg}
4437
+ `);
4438
+ try {
4439
+ appendFileSync(INTERCOM_LOG2, line);
4440
+ } catch {
4441
+ }
4442
+ }
4443
+ function getSessionState(sessionName) {
4444
+ const transport = getTransport();
4445
+ if (!transport.isAlive(sessionName)) return "offline";
4446
+ try {
4447
+ const pane = transport.capturePane(sessionName, 5);
4448
+ if (!pane.includes("\u276F") && !pane.includes("Claude Code") && !BUSY_PATTERN.test(pane) && !/Running…/.test(pane)) {
4449
+ if (/\$\s*$/.test(pane) || /% $/.test(pane.trimEnd())) {
4450
+ return "no_claude";
4451
+ }
4452
+ }
4453
+ if (/Running…/.test(pane)) return "tool";
4454
+ if (BUSY_PATTERN.test(pane)) return "thinking";
4455
+ return "idle";
4456
+ } catch {
4457
+ return "offline";
4458
+ }
4459
+ }
4460
+ function isSessionBusy(sessionName) {
4461
+ const state = getSessionState(sessionName);
4462
+ return state === "thinking" || state === "tool";
4463
+ }
4464
+ function isExeSession(sessionName) {
4465
+ return /^exe\d*$/.test(sessionName);
4466
+ }
4467
+ function sendIntercom(targetSession) {
4468
+ const transport = getTransport();
4469
+ if (isExeSession(targetSession)) {
4470
+ logIntercom(`SKIP_EXE \u2192 ${targetSession} (exe sessions use prompt-submit hook)`);
4471
+ return "skipped_exe";
4472
+ }
4473
+ if (isDebounced(targetSession)) {
4474
+ logIntercom(`DEBOUNCE \u2192 ${targetSession} (cross-process file debounce)`);
4475
+ return "debounced";
4476
+ }
4477
+ try {
4478
+ const sessions = transport.listSessions();
4479
+ if (!sessions.includes(targetSession)) {
4480
+ logIntercom(`SKIP \u2192 ${targetSession} (session not found)`);
4481
+ return "failed";
4482
+ }
4483
+ const sessionState = getSessionState(targetSession);
4484
+ if (sessionState === "no_claude") {
4485
+ queueIntercom(targetSession, "claude not running in session");
4486
+ recordDebounce(targetSession);
4487
+ logIntercom(`QUEUED \u2192 ${targetSession} (no claude process \u2014 raw shell detected)`);
4488
+ return "queued";
4489
+ }
4490
+ if (sessionState === "thinking" || sessionState === "tool") {
4491
+ queueIntercom(targetSession, "session busy at send time");
4492
+ recordDebounce(targetSession);
4493
+ logIntercom(`QUEUED \u2192 ${targetSession} (session busy, will retry from queue)`);
4494
+ return "queued";
4495
+ }
4496
+ if (transport.isPaneInCopyMode(targetSession)) {
4497
+ logIntercom(`COPY_MODE \u2192 ${targetSession} (exiting copy mode first)`);
4498
+ transport.sendKeys(targetSession, "q");
4499
+ }
4500
+ transport.sendKeys(targetSession, "/exe-intercom");
4501
+ recordDebounce(targetSession);
4502
+ logIntercom(`DELIVERED \u2192 ${targetSession} (fire-and-forget)`);
4503
+ return "delivered";
4504
+ } catch {
4505
+ logIntercom(`FAIL \u2192 ${targetSession}`);
4506
+ return "failed";
4507
+ }
4508
+ }
4509
+ function notifyParentExe(sessionKey) {
4510
+ const target = getDispatchedBy(sessionKey);
4511
+ if (!target) {
4512
+ process.stderr.write(`[intercom] notifyParentExe: no dispatcher found for key ${sessionKey}
4513
+ `);
4514
+ return false;
4515
+ }
4516
+ process.stderr.write(`[intercom] notifyParentExe \u2192 ${target}
4517
+ `);
4518
+ const result = sendIntercom(target);
4519
+ if (result === "failed") {
4520
+ const rootExe = resolveExeSession();
4521
+ if (rootExe && rootExe !== target) {
4522
+ process.stderr.write(`[intercom] notifyParentExe: dispatcher ${target} dead, falling back to root exe ${rootExe}
4523
+ `);
4524
+ const fallback = sendIntercom(rootExe);
4525
+ return fallback !== "failed";
4526
+ }
4527
+ return false;
4528
+ }
4529
+ return true;
4530
+ }
4531
+ function ensureEmployee(employeeName, exeSession, projectDir, opts) {
4532
+ if (employeeName === "exe") {
4533
+ return { status: "failed", sessionName: "", error: "exe is the COO, not a dispatchable employee" };
4534
+ }
4535
+ try {
4536
+ assertEmployeeLimitSync();
4537
+ } catch (err) {
4538
+ if (err instanceof PlanLimitError) {
4539
+ return { status: "failed", sessionName: "", error: err.message };
4540
+ }
4541
+ }
4542
+ if (/-exe\d*$/.test(employeeName)) {
4543
+ const bare = employeeName.replace(/-exe\d*$/, "").replace(/\d+$/, "");
4544
+ return {
4545
+ status: "failed",
4546
+ sessionName: "",
4547
+ error: `Error: pass employee name ('${bare}'), not session name ('${employeeName}')`
4548
+ };
4549
+ }
4550
+ if (!/^exe\d+$/.test(exeSession)) {
4551
+ const root = extractRootExe(exeSession);
4552
+ if (root) {
4553
+ process.stderr.write(
4554
+ `[ensureEmployee] WARN: caller passed exeSession="${exeSession}" (not a root exe). Auto-correcting to "${root}".
4555
+ `
4556
+ );
4557
+ exeSession = root;
4558
+ } else {
4559
+ return {
4560
+ status: "failed",
4561
+ sessionName: "",
4562
+ error: `Invalid exeSession "${exeSession}" \u2014 must be a root exe session (e.g., "exe1")`
4563
+ };
4564
+ }
4565
+ }
4566
+ let effectiveInstance = opts?.instance;
4567
+ if (effectiveInstance === void 0 && opts?.autoInstance) {
4568
+ const free = findFreeInstance(
4569
+ employeeName,
4570
+ exeSession,
4571
+ opts.maxAutoInstances ?? 10
4572
+ );
4573
+ if (free === null) {
4574
+ return {
4575
+ status: "failed",
4576
+ sessionName: employeeSessionName(employeeName, exeSession),
4577
+ error: `All ${opts.maxAutoInstances ?? 10} instances of ${employeeName} are alive \u2014 cap reached`
4578
+ };
4579
+ }
4580
+ effectiveInstance = free === 0 ? void 0 : free;
4581
+ }
4582
+ const sessionName = employeeSessionName(employeeName, exeSession, effectiveInstance);
4583
+ if (isEmployeeAlive(sessionName)) {
4584
+ const result2 = sendIntercom(sessionName);
4585
+ if (result2 === "acknowledged" || result2 === "skipped_exe" || result2 === "debounced" || result2 === "queued") {
4586
+ return { status: "intercom_sent", sessionName };
4587
+ }
4588
+ if (result2 === "delivered") {
4589
+ return { status: "intercom_unprocessed", sessionName };
4590
+ }
4591
+ return { status: "failed", sessionName, error: "intercom delivery failed" };
4592
+ }
4593
+ const spawnOpts = { ...opts, instance: effectiveInstance };
4594
+ const result = spawnEmployee(employeeName, exeSession, projectDir, spawnOpts);
4595
+ if (result.error) {
4596
+ return { status: "failed", sessionName, error: result.error };
4597
+ }
4598
+ return { status: "spawned", sessionName };
4599
+ }
4600
+ function spawnEmployee(employeeName, exeSession, projectDir, opts) {
4601
+ const transport = getTransport();
4602
+ const sessionName = employeeSessionName(employeeName, exeSession, opts?.instance);
4603
+ const instanceLabel = opts?.instance != null && opts.instance > 0 ? `${employeeName}${opts.instance}` : employeeName;
4604
+ const logDir = path15.join(os6.homedir(), ".exe-os", "session-logs");
4605
+ const logFile = path15.join(logDir, `${instanceLabel}-${Date.now()}.log`);
4606
+ if (!existsSync12(logDir)) {
4607
+ mkdirSync6(logDir, { recursive: true });
4608
+ }
4609
+ transport.kill(sessionName);
4610
+ let cleanupSuffix = "";
4611
+ try {
4612
+ const thisFile = fileURLToPath2(import.meta.url);
4613
+ const cleanupScript = path15.join(path15.dirname(thisFile), "..", "bin", "exe-session-cleanup.js");
4614
+ if (existsSync12(cleanupScript)) {
4615
+ cleanupSuffix = `; ${process.execPath} "${cleanupScript}" "${employeeName}" "${exeSession}"`;
4616
+ }
4617
+ } catch {
4618
+ }
4619
+ try {
4620
+ const claudeJsonPath = path15.join(os6.homedir(), ".claude.json");
4621
+ let claudeJson = {};
4622
+ try {
4623
+ claudeJson = JSON.parse(readFileSync9(claudeJsonPath, "utf8"));
4624
+ } catch {
4625
+ }
4626
+ if (!claudeJson.projects) claudeJson.projects = {};
4627
+ const projects = claudeJson.projects;
4628
+ const trustDir = opts?.cwd ?? projectDir;
4629
+ if (!projects[trustDir]) projects[trustDir] = {};
4630
+ projects[trustDir].hasTrustDialogAccepted = true;
4631
+ writeFileSync5(claudeJsonPath, JSON.stringify(claudeJson, null, 2) + "\n");
4632
+ } catch {
4633
+ }
4634
+ try {
4635
+ const settingsDir = path15.join(os6.homedir(), ".claude", "projects");
4636
+ const normalizedKey = (opts?.cwd ?? projectDir).replace(/\//g, "-").replace(/^-/, "");
4637
+ const projSettingsDir = path15.join(settingsDir, normalizedKey);
4638
+ const settingsPath = path15.join(projSettingsDir, "settings.json");
4639
+ let settings = {};
4640
+ try {
4641
+ settings = JSON.parse(readFileSync9(settingsPath, "utf8"));
4642
+ } catch {
4643
+ }
4644
+ const perms = settings.permissions ?? {};
4645
+ const allow = perms.allow ?? [];
4646
+ const toolNames = [
4647
+ "recall_my_memory",
4648
+ "store_memory",
4649
+ "create_task",
4650
+ "update_task",
4651
+ "list_tasks",
4652
+ "get_task",
4653
+ "ask_team_memory",
4654
+ "store_behavior",
4655
+ "get_identity",
4656
+ "send_message"
4657
+ ];
4658
+ const requiredTools = expandDualPrefixTools(toolNames);
4659
+ let changed = false;
4660
+ for (const tool of requiredTools) {
4661
+ if (!allow.includes(tool)) {
4662
+ allow.push(tool);
4663
+ changed = true;
4664
+ }
4665
+ }
4666
+ if (changed) {
4667
+ perms.allow = allow;
4668
+ settings.permissions = perms;
4669
+ mkdirSync6(projSettingsDir, { recursive: true });
4670
+ writeFileSync5(settingsPath, JSON.stringify(settings, null, 2) + "\n");
4671
+ }
4672
+ } catch {
4673
+ }
4674
+ const spawnCwd = opts?.cwd ?? projectDir;
4675
+ const useExeAgent = !!(opts?.model && opts?.provider);
4676
+ const ccProvider = useExeAgent ? DEFAULT_PROVIDER : detectActiveProvider();
4677
+ const useBinSymlink = ccProvider !== DEFAULT_PROVIDER;
4678
+ let identityFlag = "";
4679
+ let behaviorsFlag = "";
4680
+ let legacyFallbackWarned = false;
4681
+ if (!useExeAgent && !useBinSymlink) {
4682
+ const identityPath = path15.join(
4683
+ os6.homedir(),
4684
+ ".exe-os",
4685
+ "identity",
4686
+ `${employeeName}.md`
4687
+ );
4688
+ _resetCcAgentSupportCache();
4689
+ const hasAgentFlag = claudeSupportsAgentFlag();
4690
+ if (hasAgentFlag) {
4691
+ identityFlag = ` --agent ${employeeName}`;
4692
+ } else if (existsSync12(identityPath)) {
4693
+ identityFlag = ` --append-system-prompt-file ${identityPath}`;
4694
+ legacyFallbackWarned = true;
4695
+ }
4696
+ const behaviorsFile = exportBehaviorsSync(
4697
+ employeeName,
4698
+ path15.basename(spawnCwd),
4699
+ sessionName
4700
+ );
4701
+ if (behaviorsFile) {
4702
+ behaviorsFlag = ` --append-system-prompt-file ${behaviorsFile}`;
4703
+ }
4704
+ }
4705
+ if (legacyFallbackWarned) {
4706
+ process.stderr.write(
4707
+ `[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.
4708
+ `
4709
+ );
4710
+ }
4711
+ let sessionContextFlag = "";
4712
+ try {
4713
+ const ctxDir = path15.join(os6.homedir(), ".exe-os", "session-cache");
4714
+ mkdirSync6(ctxDir, { recursive: true });
4715
+ const ctxFile = path15.join(ctxDir, `session-context-${sessionName}.md`);
4716
+ const ctxContent = [
4717
+ `## Session Context`,
4718
+ `You are running in tmux session: ${sessionName}.`,
4719
+ `Your parent exe session is ${exeSession}.`,
4720
+ `Your employees (if any) use the -${exeSession} suffix (e.g., tom-${exeSession}).`
4721
+ ].join("\n");
4722
+ writeFileSync5(ctxFile, ctxContent);
4723
+ sessionContextFlag = ` --append-system-prompt-file ${ctxFile}`;
4724
+ } catch {
4725
+ }
4726
+ let envPrefix = `EXE_SESSION=${exeSession} EXE_SESSION_NAME=${sessionName}`;
4727
+ if (ccProvider !== DEFAULT_PROVIDER) {
4728
+ const cfg = PROVIDER_TABLE[ccProvider];
4729
+ if (cfg?.apiKeyEnv) {
4730
+ const keyVal = process.env[cfg.apiKeyEnv];
4731
+ if (keyVal) {
4732
+ envPrefix = `${envPrefix} ${cfg.apiKeyEnv}=${keyVal}`;
4733
+ }
4734
+ }
4735
+ }
4736
+ let spawnCommand;
4737
+ if (useExeAgent) {
4738
+ spawnCommand = `${envPrefix} exe-agent --employee ${employeeName} --model ${opts.model} --provider ${opts.provider}${cleanupSuffix}`;
4739
+ } else if (useBinSymlink) {
4740
+ const binName = `${employeeName}-${ccProvider}`;
4741
+ process.stderr.write(
4742
+ `[tmux-routing] provider cascade: ${ccProvider} \u2192 spawning ${binName}
4743
+ `
4744
+ );
4745
+ spawnCommand = `${envPrefix} ${binName}${cleanupSuffix}`;
4746
+ } else {
4747
+ spawnCommand = `${envPrefix} claude --dangerously-skip-permissions${identityFlag}${behaviorsFlag}${sessionContextFlag}${cleanupSuffix}`;
4748
+ }
4749
+ const spawnResult = transport.spawn(sessionName, {
4750
+ cwd: spawnCwd,
4751
+ command: spawnCommand
4752
+ });
4753
+ if (spawnResult.error) {
4754
+ releaseSpawnLock(sessionName);
4755
+ return { sessionName, error: `tmux new-session failed: ${spawnResult.error}` };
4756
+ }
4757
+ transport.pipeLog(sessionName, logFile);
4758
+ try {
4759
+ const mySession = getMySession();
4760
+ const dispatchInfo = path15.join(SESSION_CACHE, `dispatch-info-${sessionName}.json`);
4761
+ writeFileSync5(dispatchInfo, JSON.stringify({
4762
+ dispatchedBy: mySession,
4763
+ rootExe: exeSession,
4764
+ provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
4765
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
4766
+ }));
4767
+ } catch {
4768
+ }
4769
+ let booted = false;
4770
+ for (let i = 0; i < 30; i++) {
4771
+ try {
4772
+ execSync6("sleep 0.5");
4773
+ } catch {
4774
+ }
4775
+ try {
4776
+ const pane = transport.capturePane(sessionName);
4777
+ if (useExeAgent) {
4778
+ if (pane.includes("[exe-agent]") || pane.includes("online")) {
4779
+ booted = true;
4780
+ break;
4781
+ }
4782
+ } else {
4783
+ if (pane.includes("Claude Code") || pane.includes("\u276F")) {
4784
+ booted = true;
4785
+ break;
4786
+ }
4787
+ }
4788
+ } catch {
4789
+ }
4790
+ }
4791
+ if (!booted) {
4792
+ releaseSpawnLock(sessionName);
4793
+ return { sessionName, error: `${useExeAgent ? "exe-agent" : "claude"} did not boot within 15s` };
4794
+ }
4795
+ if (!useExeAgent) {
4796
+ try {
4797
+ transport.sendKeys(sessionName, `/exe-call ${employeeName}`);
4798
+ } catch {
4799
+ }
4800
+ }
4801
+ registerSession({
4802
+ windowName: sessionName,
4803
+ agentId: employeeName,
4804
+ projectDir: spawnCwd,
4805
+ parentExe: exeSession,
4806
+ pid: 0,
4807
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString()
4808
+ });
4809
+ releaseSpawnLock(sessionName);
4810
+ return { sessionName };
4811
+ }
4812
+ 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;
4813
+ var init_tmux_routing = __esm({
4814
+ "src/lib/tmux-routing.ts"() {
4815
+ "use strict";
4816
+ init_session_registry();
4817
+ init_session_key();
4818
+ init_transport();
4819
+ init_cc_agent_support();
4820
+ init_mcp_prefix();
4821
+ init_provider_table();
4822
+ init_intercom_queue();
4823
+ init_plan_limits();
4824
+ SPAWN_LOCK_DIR = path15.join(os6.homedir(), ".exe-os", "spawn-locks");
4825
+ SESSION_CACHE = path15.join(os6.homedir(), ".exe-os", "session-cache");
4826
+ BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
4827
+ VALID_SESSION_NAME = /^[a-z]+-exe\d+$|^[a-z]+\d+-exe\d+$/;
4828
+ VERIFY_PANE_LINES = 200;
4829
+ INTERCOM_DEBOUNCE_MS = 3e4;
4830
+ INTERCOM_LOG2 = path15.join(os6.homedir(), ".exe-os", "intercom.log");
4831
+ DEBOUNCE_FILE = path15.join(SESSION_CACHE, "intercom-debounce.json");
4832
+ DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
4833
+ BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
4834
+ }
4835
+ });
4836
+
4837
+ // src/bin/scan-tasks.ts
4838
+ import { existsSync as existsSync13, readFileSync as readFileSync10 } from "fs";
4839
+ import path16 from "path";
4840
+ import os7 from "os";
4841
+
4842
+ // src/lib/is-main.ts
4843
+ import { realpathSync } from "fs";
4844
+ import { fileURLToPath } from "url";
4845
+ function isMainModule(importMetaUrl) {
4846
+ if (process.argv[1] == null) return false;
4847
+ try {
4848
+ const scriptPath = realpathSync(process.argv[1]);
4849
+ const modulePath = realpathSync(fileURLToPath(importMetaUrl));
4850
+ return scriptPath === modulePath;
4851
+ } catch {
4852
+ return importMetaUrl === `file://${process.argv[1]}` || importMetaUrl === new URL(process.argv[1], "file://").href;
4853
+ }
4854
+ }
4855
+
4856
+ // src/bin/scan-tasks.ts
4857
+ function checkMcpHealth() {
4858
+ try {
4859
+ const claudeJson = path16.join(os7.homedir(), ".claude.json");
4860
+ if (!existsSync13(claudeJson)) {
4861
+ process.stderr.write(
4862
+ "\u26A0\uFE0F MCP config missing (~/.claude.json not found) \u2014 close_task won't work. Run /exe-setup\n"
4863
+ );
4864
+ return;
4865
+ }
4866
+ const config = JSON.parse(readFileSync10(claudeJson, "utf8"));
4867
+ const servers = config.mcpServers;
4868
+ if (!servers?.["exe-os"] && !servers?.["exe-mem"]) {
4869
+ process.stderr.write(
4870
+ "\u26A0\uFE0F MCP task tools not available \u2014 exe-os server not configured in ~/.claude.json. close_task won't work.\n"
4871
+ );
4872
+ }
4873
+ } catch {
4874
+ }
4875
+ }
4876
+ async function scanFromDb(agentId, tmuxSession, projectName) {
4877
+ const { getClient: getClient2, isInitialized: isInitialized2 } = await Promise.resolve().then(() => (init_database(), database_exports));
4878
+ if (!isInitialized2()) {
4879
+ const { initStore: initStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
4880
+ await initStore2();
4881
+ }
4882
+ const client = getClient2();
4883
+ let resolvedProject = projectName;
4884
+ if (resolvedProject === void 0) {
4885
+ try {
4886
+ const { getProjectName: getProjectName2 } = await Promise.resolve().then(() => (init_project_name(), project_name_exports));
4887
+ resolvedProject = getProjectName2();
4888
+ } catch {
4889
+ }
4890
+ }
4891
+ let resolvedSession = null;
4892
+ try {
4893
+ const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
4894
+ resolvedSession = resolveExeSession2();
4895
+ } catch {
1991
4896
  }
4897
+ const sessionFilter = resolvedSession ? " AND (session_scope IS NULL OR session_scope = ?)" : "";
4898
+ const sessionArgs = resolvedSession ? [resolvedSession] : [];
1992
4899
  const sql = resolvedProject ? `SELECT id, title, priority, status, assigned_tmux, checkpoint, checkpoint_count FROM tasks
1993
- WHERE assigned_to = ? AND project_name = ? AND status IN ('open', 'in_progress', 'blocked', 'needs_review')
4900
+ WHERE assigned_to = ? AND project_name = ?${sessionFilter} AND status IN ('open', 'in_progress', 'blocked', 'needs_review')
1994
4901
  ORDER BY CASE status WHEN 'in_progress' THEN 0 WHEN 'open' THEN 1 WHEN 'blocked' THEN 2 ELSE 3 END,
1995
4902
  priority ASC, created_at DESC` : `SELECT id, title, priority, status, assigned_tmux, checkpoint, checkpoint_count FROM tasks
1996
- WHERE assigned_to = ? AND status IN ('open', 'in_progress', 'blocked', 'needs_review')
4903
+ WHERE assigned_to = ?${sessionFilter} AND status IN ('open', 'in_progress', 'blocked', 'needs_review')
1997
4904
  ORDER BY CASE status WHEN 'in_progress' THEN 0 WHEN 'open' THEN 1 WHEN 'blocked' THEN 2 ELSE 3 END,
1998
4905
  priority ASC, created_at DESC`;
1999
- const args = resolvedProject ? [agentId, resolvedProject] : [agentId];
4906
+ const args = resolvedProject ? [agentId, resolvedProject, ...sessionArgs] : [agentId, ...sessionArgs];
2000
4907
  const result = await client.execute({ sql, args });
2001
4908
  const open = [];
2002
4909
  const inProgress = [];
@@ -2106,8 +5013,8 @@ async function main() {
2106
5013
  const agentId = folderArg.startsWith("exe/") ? folderArg.slice(4) : folderArg;
2107
5014
  let tmuxSession;
2108
5015
  try {
2109
- const { execSync: execSync2 } = await import("child_process");
2110
- const out = execSync2("tmux display-message -p '#{session_name}' 2>/dev/null", {
5016
+ const { execSync: execSync7 } = await import("child_process");
5017
+ const out = execSync7("tmux display-message -p '#{session_name}' 2>/dev/null", {
2111
5018
  encoding: "utf8",
2112
5019
  timeout: 1e3
2113
5020
  }).trim();