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