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