@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
@@ -322,6 +322,13 @@ async function ensureSchema() {
322
322
  });
323
323
  } catch {
324
324
  }
325
+ try {
326
+ await client.execute({
327
+ sql: `ALTER TABLE tasks ADD COLUMN session_scope TEXT`,
328
+ args: []
329
+ });
330
+ } catch {
331
+ }
325
332
  try {
326
333
  await client.execute({
327
334
  sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
@@ -768,6 +775,18 @@ async function ensureSchema() {
768
775
  CREATE INDEX IF NOT EXISTS idx_session_kills_agent
769
776
  ON session_kills(agent_id);
770
777
  `);
778
+ await client.execute(`
779
+ CREATE TABLE IF NOT EXISTS global_procedures (
780
+ id TEXT PRIMARY KEY,
781
+ title TEXT NOT NULL,
782
+ content TEXT NOT NULL,
783
+ priority TEXT NOT NULL DEFAULT 'p0',
784
+ domain TEXT,
785
+ active INTEGER NOT NULL DEFAULT 1,
786
+ created_at TEXT NOT NULL,
787
+ updated_at TEXT NOT NULL
788
+ )
789
+ `);
771
790
  await client.executeMultiple(`
772
791
  CREATE TABLE IF NOT EXISTS conversations (
773
792
  id TEXT PRIMARY KEY,
@@ -1165,6 +1184,61 @@ var init_config = __esm({
1165
1184
  }
1166
1185
  });
1167
1186
 
1187
+ // src/lib/state-bus.ts
1188
+ var StateBus, orgBus;
1189
+ var init_state_bus = __esm({
1190
+ "src/lib/state-bus.ts"() {
1191
+ "use strict";
1192
+ StateBus = class {
1193
+ handlers = /* @__PURE__ */ new Map();
1194
+ globalHandlers = /* @__PURE__ */ new Set();
1195
+ /** Emit an event to all subscribers */
1196
+ emit(event) {
1197
+ const typeHandlers = this.handlers.get(event.type);
1198
+ if (typeHandlers) {
1199
+ for (const handler of typeHandlers) {
1200
+ try {
1201
+ handler(event);
1202
+ } catch {
1203
+ }
1204
+ }
1205
+ }
1206
+ for (const handler of this.globalHandlers) {
1207
+ try {
1208
+ handler(event);
1209
+ } catch {
1210
+ }
1211
+ }
1212
+ }
1213
+ /** Subscribe to a specific event type */
1214
+ on(type, handler) {
1215
+ if (!this.handlers.has(type)) {
1216
+ this.handlers.set(type, /* @__PURE__ */ new Set());
1217
+ }
1218
+ this.handlers.get(type).add(handler);
1219
+ }
1220
+ /** Subscribe to ALL events */
1221
+ onAny(handler) {
1222
+ this.globalHandlers.add(handler);
1223
+ }
1224
+ /** Unsubscribe from a specific event type */
1225
+ off(type, handler) {
1226
+ this.handlers.get(type)?.delete(handler);
1227
+ }
1228
+ /** Unsubscribe from ALL events */
1229
+ offAny(handler) {
1230
+ this.globalHandlers.delete(handler);
1231
+ }
1232
+ /** Remove all listeners */
1233
+ clear() {
1234
+ this.handlers.clear();
1235
+ this.globalHandlers.clear();
1236
+ }
1237
+ };
1238
+ orgBus = new StateBus();
1239
+ }
1240
+ });
1241
+
1168
1242
  // src/lib/shard-manager.ts
1169
1243
  var shard_manager_exports = {};
1170
1244
  __export(shard_manager_exports, {
@@ -1406,6 +1480,71 @@ var init_shard_manager = __esm({
1406
1480
  }
1407
1481
  });
1408
1482
 
1483
+ // src/lib/global-procedures.ts
1484
+ var global_procedures_exports = {};
1485
+ __export(global_procedures_exports, {
1486
+ deactivateGlobalProcedure: () => deactivateGlobalProcedure,
1487
+ getGlobalProceduresBlock: () => getGlobalProceduresBlock,
1488
+ loadGlobalProcedures: () => loadGlobalProcedures,
1489
+ storeGlobalProcedure: () => storeGlobalProcedure
1490
+ });
1491
+ import { randomUUID } from "crypto";
1492
+ async function loadGlobalProcedures() {
1493
+ const client = getClient();
1494
+ const result = await client.execute({
1495
+ sql: "SELECT * FROM global_procedures WHERE active = 1 ORDER BY priority ASC, created_at ASC",
1496
+ args: []
1497
+ });
1498
+ const procedures = result.rows;
1499
+ if (procedures.length > 0) {
1500
+ _cache = procedures.map((p) => `### ${p.title}
1501
+ ${p.content}`).join("\n\n");
1502
+ } else {
1503
+ _cache = "";
1504
+ }
1505
+ _cacheLoaded = true;
1506
+ return procedures;
1507
+ }
1508
+ function getGlobalProceduresBlock() {
1509
+ if (!_cacheLoaded) return "";
1510
+ if (!_cache) return "";
1511
+ return `## Organization-Wide Procedures (MANDATORY \u2014 supersedes all other rules)
1512
+
1513
+ ${_cache}
1514
+ `;
1515
+ }
1516
+ async function storeGlobalProcedure(input) {
1517
+ const id = randomUUID();
1518
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1519
+ const client = getClient();
1520
+ await client.execute({
1521
+ sql: `INSERT INTO global_procedures (id, title, content, priority, domain, active, created_at, updated_at)
1522
+ VALUES (?, ?, ?, ?, ?, 1, ?, ?)`,
1523
+ args: [id, input.title, input.content, input.priority ?? "p0", input.domain ?? null, now, now]
1524
+ });
1525
+ await loadGlobalProcedures();
1526
+ return id;
1527
+ }
1528
+ async function deactivateGlobalProcedure(id) {
1529
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1530
+ const client = getClient();
1531
+ const result = await client.execute({
1532
+ sql: "UPDATE global_procedures SET active = 0, updated_at = ? WHERE id = ?",
1533
+ args: [now, id]
1534
+ });
1535
+ await loadGlobalProcedures();
1536
+ return result.rowsAffected > 0;
1537
+ }
1538
+ var _cache, _cacheLoaded;
1539
+ var init_global_procedures = __esm({
1540
+ "src/lib/global-procedures.ts"() {
1541
+ "use strict";
1542
+ init_database();
1543
+ _cache = "";
1544
+ _cacheLoaded = false;
1545
+ }
1546
+ });
1547
+
1409
1548
  // src/lib/project-name.ts
1410
1549
  import { execSync } from "child_process";
1411
1550
  import path4 from "path";
@@ -1451,7 +1590,7 @@ var init_project_name = __esm({
1451
1590
  // src/lib/exe-daemon-client.ts
1452
1591
  import net from "net";
1453
1592
  import { spawn } from "child_process";
1454
- import { randomUUID } from "crypto";
1593
+ import { randomUUID as randomUUID2 } from "crypto";
1455
1594
  import { existsSync as existsSync4, unlinkSync, readFileSync as readFileSync2, openSync, closeSync, statSync } from "fs";
1456
1595
  import path5 from "path";
1457
1596
  import { fileURLToPath } from "url";
@@ -1643,7 +1782,7 @@ function sendRequest(texts, priority) {
1643
1782
  resolve({ error: "Not connected" });
1644
1783
  return;
1645
1784
  }
1646
- const id = randomUUID();
1785
+ const id = randomUUID2();
1647
1786
  const timer = setTimeout(() => {
1648
1787
  _pending.delete(id);
1649
1788
  resolve({ error: "Request timeout" });
@@ -1661,7 +1800,7 @@ function sendRequest(texts, priority) {
1661
1800
  async function pingDaemon() {
1662
1801
  if (!_socket || !_connected) return null;
1663
1802
  return new Promise((resolve) => {
1664
- const id = randomUUID();
1803
+ const id = randomUUID2();
1665
1804
  const timer = setTimeout(() => {
1666
1805
  _pending.delete(id);
1667
1806
  resolve(null);
@@ -1826,10 +1965,10 @@ async function disposeEmbedder() {
1826
1965
  async function embedDirect(text) {
1827
1966
  const llamaCpp = await import("node-llama-cpp");
1828
1967
  const { MODELS_DIR: MODELS_DIR2 } = await Promise.resolve().then(() => (init_config(), config_exports));
1829
- const { existsSync: existsSync14 } = await import("fs");
1830
- const path16 = await import("path");
1831
- const modelPath = path16.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
1832
- if (!existsSync14(modelPath)) {
1968
+ const { existsSync: existsSync15 } = await import("fs");
1969
+ const path18 = await import("path");
1970
+ const modelPath = path18.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
1971
+ if (!existsSync15(modelPath)) {
1833
1972
  throw new Error(`Embedding model not found at ${modelPath}. Run '/exe-setup' to download it.`);
1834
1973
  }
1835
1974
  const llama = await llamaCpp.getLlama();
@@ -1873,15 +2012,30 @@ async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
1873
2012
  return [];
1874
2013
  }
1875
2014
  }
2015
+ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
2016
+ if (!existsSync5(employeesPath)) return [];
2017
+ try {
2018
+ return JSON.parse(readFileSync3(employeesPath, "utf-8"));
2019
+ } catch {
2020
+ return [];
2021
+ }
2022
+ }
1876
2023
  function getEmployee(employees, name) {
1877
2024
  return employees.find((e) => e.name.toLowerCase() === name.toLowerCase());
1878
2025
  }
1879
- var EMPLOYEES_PATH;
2026
+ function isMultiInstance(agentName2, employees) {
2027
+ const roster = employees ?? loadEmployeesSync();
2028
+ const emp = getEmployee(roster, agentName2);
2029
+ if (!emp) return false;
2030
+ return MULTI_INSTANCE_ROLES.has(emp.role.toLowerCase());
2031
+ }
2032
+ var EMPLOYEES_PATH, MULTI_INSTANCE_ROLES;
1880
2033
  var init_employees = __esm({
1881
2034
  "src/lib/employees.ts"() {
1882
2035
  "use strict";
1883
2036
  init_config();
1884
2037
  EMPLOYEES_PATH = path6.join(EXE_AI_DIR, "exe-employees.json");
2038
+ MULTI_INSTANCE_ROLES = /* @__PURE__ */ new Set(["principal engineer", "content production specialist", "staff code reviewer"]);
1885
2039
  }
1886
2040
  });
1887
2041
 
@@ -1920,6 +2074,16 @@ async function writeNotification(notification) {
1920
2074
  `);
1921
2075
  }
1922
2076
  }
2077
+ async function markAsReadByTaskFile(taskFile) {
2078
+ try {
2079
+ const client = getClient();
2080
+ await client.execute({
2081
+ sql: "UPDATE notifications SET read = 1 WHERE task_file = ? AND read = 0",
2082
+ args: [taskFile]
2083
+ });
2084
+ } catch {
2085
+ }
2086
+ }
1923
2087
  var init_notifications = __esm({
1924
2088
  "src/lib/notifications.ts"() {
1925
2089
  "use strict";
@@ -1927,254 +2091,66 @@ var init_notifications = __esm({
1927
2091
  }
1928
2092
  });
1929
2093
 
1930
- // src/lib/tasks-crud.ts
1931
- import crypto3 from "crypto";
2094
+ // src/lib/session-registry.ts
2095
+ import { readFileSync as readFileSync5, writeFileSync, mkdirSync as mkdirSync2, existsSync as existsSync7 } from "fs";
1932
2096
  import path8 from "path";
1933
- import { execSync as execSync3 } from "child_process";
1934
- import { mkdir as mkdir4, writeFile as writeFile4, appendFile } from "fs/promises";
1935
- import { existsSync as existsSync7, readFileSync as readFileSync5 } from "fs";
1936
- function extractParentFromContext(contextBody) {
1937
- if (!contextBody) return null;
1938
- const match = contextBody.match(
1939
- /Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
1940
- );
1941
- return match ? match[1].toLowerCase() : null;
1942
- }
1943
- function slugify(title) {
1944
- return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
1945
- }
1946
- async function resolveTask(client, identifier) {
1947
- let result = await client.execute({
1948
- sql: "SELECT * FROM tasks WHERE id = ?",
1949
- args: [identifier]
1950
- });
1951
- if (result.rows.length === 1) return result.rows[0];
1952
- result = await client.execute({
1953
- sql: "SELECT * FROM tasks WHERE task_file LIKE ?",
1954
- args: [`%${identifier}%`]
1955
- });
1956
- if (result.rows.length === 1) return result.rows[0];
1957
- if (result.rows.length > 1) {
1958
- const exact = result.rows.filter(
1959
- (r) => String(r.task_file).endsWith(`/${identifier}.md`)
1960
- );
1961
- if (exact.length === 1) return exact[0];
1962
- const candidates = exact.length > 1 ? exact : result.rows;
1963
- const active = candidates.filter(
1964
- (r) => !["done", "cancelled"].includes(String(r.status))
1965
- );
1966
- if (active.length === 1) return active[0];
1967
- const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
1968
- throw new Error(
1969
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
1970
- );
1971
- }
1972
- result = await client.execute({
1973
- sql: "SELECT * FROM tasks WHERE title LIKE ?",
1974
- args: [`%${identifier}%`]
1975
- });
1976
- if (result.rows.length === 1) return result.rows[0];
1977
- if (result.rows.length > 1) {
1978
- const active = result.rows.filter(
1979
- (r) => !["done", "cancelled"].includes(String(r.status))
1980
- );
1981
- if (active.length === 1) return active[0];
1982
- const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
1983
- throw new Error(
1984
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
1985
- );
2097
+ import os4 from "os";
2098
+ function registerSession(entry) {
2099
+ const dir = path8.dirname(REGISTRY_PATH);
2100
+ if (!existsSync7(dir)) {
2101
+ mkdirSync2(dir, { recursive: true });
2102
+ }
2103
+ const sessions = listSessions();
2104
+ const idx = sessions.findIndex((s) => s.windowName === entry.windowName);
2105
+ if (idx >= 0) {
2106
+ sessions[idx] = entry;
2107
+ } else {
2108
+ sessions.push(entry);
1986
2109
  }
1987
- throw new Error(`Task not found: ${identifier}`);
2110
+ writeFileSync(REGISTRY_PATH, JSON.stringify(sessions, null, 2));
1988
2111
  }
1989
- async function createTaskCore(input) {
1990
- const client = getClient();
1991
- const id = crypto3.randomUUID();
1992
- const now = (/* @__PURE__ */ new Date()).toISOString();
1993
- const slug = slugify(input.title);
1994
- const taskFile = input.taskFile ?? `exe/${input.assignedTo}/${slug}.md`;
1995
- let blockedById = null;
1996
- const initialStatus = input.blockedBy ? "blocked" : "open";
1997
- if (input.blockedBy) {
1998
- const blocker = await resolveTask(client, input.blockedBy);
1999
- blockedById = String(blocker.id);
2112
+ function listSessions() {
2113
+ try {
2114
+ const raw = readFileSync5(REGISTRY_PATH, "utf8");
2115
+ return JSON.parse(raw);
2116
+ } catch {
2117
+ return [];
2000
2118
  }
2001
- let parentTaskId = null;
2002
- let parentRef = input.parentTaskId;
2003
- if (!parentRef) {
2004
- const extracted = extractParentFromContext(input.context);
2005
- if (extracted) {
2006
- parentRef = extracted;
2007
- process.stderr.write(
2008
- "[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
2009
- );
2010
- }
2119
+ }
2120
+ var REGISTRY_PATH;
2121
+ var init_session_registry = __esm({
2122
+ "src/lib/session-registry.ts"() {
2123
+ "use strict";
2124
+ REGISTRY_PATH = path8.join(os4.homedir(), ".exe-os", "session-registry.json");
2011
2125
  }
2012
- if (parentRef) {
2126
+ });
2127
+
2128
+ // src/lib/session-key.ts
2129
+ import { execSync as execSync3 } from "child_process";
2130
+ function getSessionKey() {
2131
+ if (_cached2) return _cached2;
2132
+ let pid = process.ppid;
2133
+ for (let i = 0; i < 10; i++) {
2013
2134
  try {
2014
- const parent = await resolveTask(client, parentRef);
2015
- parentTaskId = String(parent.id);
2016
- } catch (err) {
2017
- if (!input.parentTaskId) {
2018
- throw new Error(
2019
- `create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
2020
- );
2135
+ const info = execSync3(`ps -p ${pid} -o ppid=,comm=`, {
2136
+ encoding: "utf8",
2137
+ timeout: 2e3
2138
+ }).trim();
2139
+ const match = info.match(/^\s*(\d+)\s+(.+)$/);
2140
+ if (!match) break;
2141
+ const [, ppid, cmd] = match;
2142
+ if (cmd === "claude" || cmd.endsWith("/claude")) {
2143
+ _cached2 = String(pid);
2144
+ return _cached2;
2021
2145
  }
2022
- throw err;
2023
- }
2024
- }
2025
- let warning;
2026
- const dupCheck = await client.execute({
2027
- sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
2028
- args: [input.title, input.assignedTo]
2029
- });
2030
- if (dupCheck.rows.length > 0) {
2031
- warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
2032
- }
2033
- if (input.baseDir) {
2034
- try {
2035
- await mkdir4(path8.join(input.baseDir, "exe", "output"), { recursive: true });
2036
- await mkdir4(path8.join(input.baseDir, "exe", "research"), { recursive: true });
2037
- await ensureArchitectureDoc(input.baseDir, input.projectName);
2038
- await ensureGitignoreExe(input.baseDir);
2146
+ pid = parseInt(ppid, 10);
2147
+ if (pid <= 1) break;
2039
2148
  } catch {
2149
+ break;
2040
2150
  }
2041
2151
  }
2042
- const complexity = input.complexity ?? "standard";
2043
- await client.execute({
2044
- sql: `INSERT INTO tasks (id, title, assigned_to, assigned_by, project_name, priority, status, task_file, blocked_by, parent_task_id, reviewer, context, complexity, budget_tokens, budget_fallback_model, tokens_used, tokens_warned_at, created_at, updated_at)
2045
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2046
- args: [
2047
- id,
2048
- input.title,
2049
- input.assignedTo,
2050
- input.assignedBy,
2051
- input.projectName,
2052
- input.priority,
2053
- initialStatus,
2054
- taskFile,
2055
- blockedById,
2056
- parentTaskId,
2057
- input.reviewer ?? null,
2058
- input.context,
2059
- complexity,
2060
- input.budgetTokens ?? null,
2061
- input.budgetFallbackModel ?? null,
2062
- 0,
2063
- null,
2064
- now,
2065
- now
2066
- ]
2067
- });
2068
- return {
2069
- id,
2070
- title: input.title,
2071
- assignedTo: input.assignedTo,
2072
- assignedBy: input.assignedBy,
2073
- projectName: input.projectName,
2074
- priority: input.priority,
2075
- status: initialStatus,
2076
- taskFile,
2077
- createdAt: now,
2078
- updatedAt: now,
2079
- warning,
2080
- budgetTokens: input.budgetTokens ?? null,
2081
- budgetFallbackModel: input.budgetFallbackModel ?? null,
2082
- tokensUsed: 0,
2083
- tokensWarnedAt: null
2084
- };
2085
- }
2086
- async function ensureArchitectureDoc(baseDir, projectName) {
2087
- const archPath = path8.join(baseDir, "exe", "ARCHITECTURE.md");
2088
- try {
2089
- if (existsSync7(archPath)) return;
2090
- const template = [
2091
- `# ${projectName} \u2014 System Architecture`,
2092
- "",
2093
- "> Employees: read this before every task. Update it when you change system structure.",
2094
- `> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
2095
- "",
2096
- "## Overview",
2097
- "",
2098
- "<!-- Describe what this system does, its main components, and how they connect. -->",
2099
- "",
2100
- "## Key Components",
2101
- "",
2102
- "<!-- List the major modules, services, or subsystems. -->",
2103
- "",
2104
- "## Data Flow",
2105
- "",
2106
- "<!-- How does data move through the system? What writes where? -->",
2107
- "",
2108
- "## Invariants",
2109
- "",
2110
- "<!-- Rules that must never be violated. What breaks if these are wrong? -->",
2111
- "",
2112
- "## Dependencies",
2113
- "",
2114
- "<!-- What depends on what? If I change X, what else is affected? -->",
2115
- ""
2116
- ].join("\n");
2117
- await writeFile4(archPath, template, "utf-8");
2118
- } catch {
2119
- }
2120
- }
2121
- async function ensureGitignoreExe(baseDir) {
2122
- const gitignorePath = path8.join(baseDir, ".gitignore");
2123
- try {
2124
- if (existsSync7(gitignorePath)) {
2125
- const content = readFileSync5(gitignorePath, "utf-8");
2126
- if (/^\/?exe\/?$/m.test(content)) return;
2127
- await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
2128
- } else {
2129
- await writeFile4(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
2130
- }
2131
- } catch {
2132
- }
2133
- }
2134
- var init_tasks_crud = __esm({
2135
- "src/lib/tasks-crud.ts"() {
2136
- "use strict";
2137
- init_database();
2138
- }
2139
- });
2140
-
2141
- // src/lib/session-registry.ts
2142
- import path9 from "path";
2143
- import os4 from "os";
2144
- var REGISTRY_PATH;
2145
- var init_session_registry = __esm({
2146
- "src/lib/session-registry.ts"() {
2147
- "use strict";
2148
- REGISTRY_PATH = path9.join(os4.homedir(), ".exe-os", "session-registry.json");
2149
- }
2150
- });
2151
-
2152
- // src/lib/session-key.ts
2153
- import { execSync as execSync4 } from "child_process";
2154
- function getSessionKey() {
2155
- if (_cached2) return _cached2;
2156
- let pid = process.ppid;
2157
- for (let i = 0; i < 10; i++) {
2158
- try {
2159
- const info = execSync4(`ps -p ${pid} -o ppid=,comm=`, {
2160
- encoding: "utf8",
2161
- timeout: 2e3
2162
- }).trim();
2163
- const match = info.match(/^\s*(\d+)\s+(.+)$/);
2164
- if (!match) break;
2165
- const [, ppid, cmd] = match;
2166
- if (cmd === "claude" || cmd.endsWith("/claude")) {
2167
- _cached2 = String(pid);
2168
- return _cached2;
2169
- }
2170
- pid = parseInt(ppid, 10);
2171
- if (pid <= 1) break;
2172
- } catch {
2173
- break;
2174
- }
2175
- }
2176
- _cached2 = process.env.CLAUDE_CODE_SSE_PORT ?? String(process.ppid);
2177
- return _cached2;
2152
+ _cached2 = process.env.CLAUDE_CODE_SSE_PORT ?? String(process.ppid);
2153
+ return _cached2;
2178
2154
  }
2179
2155
  var _cached2;
2180
2156
  var init_session_key = __esm({
@@ -2292,14 +2268,41 @@ var init_transport = __esm({
2292
2268
  });
2293
2269
 
2294
2270
  // src/lib/cc-agent-support.ts
2295
- import { execSync as execSync5 } from "child_process";
2271
+ import { execSync as execSync4 } from "child_process";
2272
+ function _resetCcAgentSupportCache() {
2273
+ _cachedSupport = null;
2274
+ }
2275
+ function claudeSupportsAgentFlag() {
2276
+ if (_cachedSupport !== null) return _cachedSupport;
2277
+ try {
2278
+ const helpOutput = execSync4("claude --help 2>&1", {
2279
+ encoding: "utf-8",
2280
+ timeout: 5e3
2281
+ });
2282
+ _cachedSupport = /(^|\s)--agent(\b|=)/.test(helpOutput);
2283
+ } catch {
2284
+ _cachedSupport = false;
2285
+ }
2286
+ return _cachedSupport;
2287
+ }
2288
+ var _cachedSupport;
2296
2289
  var init_cc_agent_support = __esm({
2297
2290
  "src/lib/cc-agent-support.ts"() {
2298
2291
  "use strict";
2292
+ _cachedSupport = null;
2299
2293
  }
2300
2294
  });
2301
2295
 
2302
2296
  // src/lib/mcp-prefix.ts
2297
+ function expandDualPrefixTools(shortNames) {
2298
+ const out = [];
2299
+ for (const name of shortNames) {
2300
+ for (const prefix of MCP_TOOL_PREFIXES) {
2301
+ out.push(prefix + name);
2302
+ }
2303
+ }
2304
+ return out;
2305
+ }
2303
2306
  var MCP_PRIMARY_KEY, MCP_LEGACY_KEY, MCP_TOOL_PREFIXES;
2304
2307
  var init_mcp_prefix = __esm({
2305
2308
  "src/lib/mcp-prefix.ts"() {
@@ -2314,19 +2317,36 @@ var init_mcp_prefix = __esm({
2314
2317
  });
2315
2318
 
2316
2319
  // src/lib/provider-table.ts
2320
+ function detectActiveProvider(env = process.env) {
2321
+ const baseUrl = env.ANTHROPIC_BASE_URL;
2322
+ if (!baseUrl) return DEFAULT_PROVIDER;
2323
+ for (const [name, cfg] of Object.entries(PROVIDER_TABLE)) {
2324
+ if (cfg.baseUrl === baseUrl) return name;
2325
+ }
2326
+ return DEFAULT_PROVIDER;
2327
+ }
2328
+ var PROVIDER_TABLE, DEFAULT_PROVIDER;
2317
2329
  var init_provider_table = __esm({
2318
2330
  "src/lib/provider-table.ts"() {
2319
2331
  "use strict";
2332
+ PROVIDER_TABLE = {
2333
+ opencode: {
2334
+ baseUrl: "https://opencode.ai/zen/go",
2335
+ apiKeyEnv: "OPENCODE_API_KEY",
2336
+ defaultModel: "minimax-m2.7"
2337
+ }
2338
+ };
2339
+ DEFAULT_PROVIDER = "default";
2320
2340
  }
2321
2341
  });
2322
2342
 
2323
2343
  // src/lib/intercom-queue.ts
2324
- import { readFileSync as readFileSync6, writeFileSync, renameSync as renameSync2, existsSync as existsSync8, mkdirSync as mkdirSync2 } from "fs";
2325
- import path10 from "path";
2344
+ import { readFileSync as readFileSync6, writeFileSync as writeFileSync2, renameSync as renameSync2, existsSync as existsSync8, mkdirSync as mkdirSync3 } from "fs";
2345
+ import path9 from "path";
2326
2346
  import os5 from "os";
2327
2347
  function ensureDir() {
2328
- const dir = path10.dirname(QUEUE_PATH);
2329
- if (!existsSync8(dir)) mkdirSync2(dir, { recursive: true });
2348
+ const dir = path9.dirname(QUEUE_PATH);
2349
+ if (!existsSync8(dir)) mkdirSync3(dir, { recursive: true });
2330
2350
  }
2331
2351
  function readQueue() {
2332
2352
  try {
@@ -2339,7 +2359,7 @@ function readQueue() {
2339
2359
  function writeQueue(queue) {
2340
2360
  ensureDir();
2341
2361
  const tmp = `${QUEUE_PATH}.tmp`;
2342
- writeFileSync(tmp, JSON.stringify(queue, null, 2));
2362
+ writeFileSync2(tmp, JSON.stringify(queue, null, 2));
2343
2363
  renameSync2(tmp, QUEUE_PATH);
2344
2364
  }
2345
2365
  function queueIntercom(targetSession, reason) {
@@ -2363,176 +2383,2189 @@ var QUEUE_PATH, TTL_MS, INTERCOM_LOG;
2363
2383
  var init_intercom_queue = __esm({
2364
2384
  "src/lib/intercom-queue.ts"() {
2365
2385
  "use strict";
2366
- QUEUE_PATH = path10.join(os5.homedir(), ".exe-os", "intercom-queue.json");
2386
+ QUEUE_PATH = path9.join(os5.homedir(), ".exe-os", "intercom-queue.json");
2367
2387
  TTL_MS = 60 * 60 * 1e3;
2368
- INTERCOM_LOG = path10.join(os5.homedir(), ".exe-os", "intercom.log");
2388
+ INTERCOM_LOG = path9.join(os5.homedir(), ".exe-os", "intercom.log");
2369
2389
  }
2370
2390
  });
2371
2391
 
2372
2392
  // src/lib/license.ts
2373
- import { readFileSync as readFileSync7, writeFileSync as writeFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync3 } from "fs";
2374
- import { randomUUID as randomUUID2 } from "crypto";
2375
- import path11 from "path";
2393
+ import { readFileSync as readFileSync7, writeFileSync as writeFileSync3, existsSync as existsSync9, mkdirSync as mkdirSync4 } from "fs";
2394
+ import { randomUUID as randomUUID3 } from "crypto";
2395
+ import path10 from "path";
2376
2396
  import { jwtVerify, importSPKI } from "jose";
2377
- var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH;
2397
+ var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH, PLAN_LIMITS;
2378
2398
  var init_license = __esm({
2379
2399
  "src/lib/license.ts"() {
2380
2400
  "use strict";
2381
2401
  init_config();
2382
- LICENSE_PATH = path11.join(EXE_AI_DIR, "license.key");
2383
- CACHE_PATH = path11.join(EXE_AI_DIR, "license-cache.json");
2384
- DEVICE_ID_PATH = path11.join(EXE_AI_DIR, "device-id");
2402
+ LICENSE_PATH = path10.join(EXE_AI_DIR, "license.key");
2403
+ CACHE_PATH = path10.join(EXE_AI_DIR, "license-cache.json");
2404
+ DEVICE_ID_PATH = path10.join(EXE_AI_DIR, "device-id");
2405
+ PLAN_LIMITS = {
2406
+ free: { devices: 1, employees: 1, memories: 5e3 },
2407
+ pro: { devices: 2, employees: 5, memories: 1e5 },
2408
+ team: { devices: 10, employees: 20, memories: 1e6 },
2409
+ agency: { devices: 50, employees: 100, memories: 1e7 },
2410
+ enterprise: { devices: -1, employees: -1, memories: -1 }
2411
+ };
2412
+ }
2413
+ });
2414
+
2415
+ // src/lib/plan-limits.ts
2416
+ import { readFileSync as readFileSync8, existsSync as existsSync10 } from "fs";
2417
+ import path11 from "path";
2418
+ function getLicenseSync() {
2419
+ try {
2420
+ if (!existsSync10(CACHE_PATH2)) return freeLicense();
2421
+ const raw = JSON.parse(readFileSync8(CACHE_PATH2, "utf8"));
2422
+ if (!raw.token || typeof raw.token !== "string") return freeLicense();
2423
+ const parts = raw.token.split(".");
2424
+ if (parts.length !== 3) return freeLicense();
2425
+ const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
2426
+ const plan = payload.plan ?? "free";
2427
+ const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
2428
+ return {
2429
+ valid: true,
2430
+ plan,
2431
+ email: payload.sub ?? "",
2432
+ expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
2433
+ deviceLimit: limits.devices,
2434
+ employeeLimit: limits.employees,
2435
+ memoryLimit: limits.memories
2436
+ };
2437
+ } catch {
2438
+ return freeLicense();
2439
+ }
2440
+ }
2441
+ function freeLicense() {
2442
+ const limits = PLAN_LIMITS.free;
2443
+ return {
2444
+ valid: true,
2445
+ plan: "free",
2446
+ email: "",
2447
+ expiresAt: null,
2448
+ deviceLimit: limits.devices,
2449
+ employeeLimit: limits.employees,
2450
+ memoryLimit: limits.memories
2451
+ };
2452
+ }
2453
+ function assertEmployeeLimitSync(rosterPath) {
2454
+ const license = getLicenseSync();
2455
+ if (license.employeeLimit < 0) return;
2456
+ const filePath = rosterPath ?? EMPLOYEES_PATH;
2457
+ let count = 0;
2458
+ try {
2459
+ if (existsSync10(filePath)) {
2460
+ const raw = readFileSync8(filePath, "utf8");
2461
+ const employees = JSON.parse(raw);
2462
+ count = Array.isArray(employees) ? employees.length : 0;
2463
+ }
2464
+ } catch {
2465
+ throw new PlanLimitError(
2466
+ `Cannot verify employee count: roster unreadable at ${filePath}. Refusing to proceed. Check file permissions or upgrade plan.`
2467
+ );
2468
+ }
2469
+ if (count >= license.employeeLimit) {
2470
+ throw new PlanLimitError(
2471
+ `Employee limit reached: ${count}/${license.employeeLimit} employees on the ${license.plan} plan. Upgrade at https://askexe.com to add more.`
2472
+ );
2473
+ }
2474
+ }
2475
+ var PlanLimitError, CACHE_PATH2;
2476
+ var init_plan_limits = __esm({
2477
+ "src/lib/plan-limits.ts"() {
2478
+ "use strict";
2479
+ init_database();
2480
+ init_employees();
2481
+ init_license();
2482
+ init_config();
2483
+ PlanLimitError = class extends Error {
2484
+ constructor(message) {
2485
+ super(message);
2486
+ this.name = "PlanLimitError";
2487
+ }
2488
+ };
2489
+ CACHE_PATH2 = path11.join(EXE_AI_DIR, "license-cache.json");
2490
+ }
2491
+ });
2492
+
2493
+ // src/lib/session-kill-telemetry.ts
2494
+ import crypto3 from "crypto";
2495
+ async function recordSessionKill(input) {
2496
+ try {
2497
+ const client = getClient();
2498
+ await client.execute({
2499
+ sql: `INSERT INTO session_kills
2500
+ (id, session_name, agent_id, killed_at, reason,
2501
+ ticks_idle, estimated_tokens_saved)
2502
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
2503
+ args: [
2504
+ crypto3.randomUUID(),
2505
+ input.sessionName,
2506
+ input.agentId,
2507
+ (/* @__PURE__ */ new Date()).toISOString(),
2508
+ input.reason,
2509
+ input.ticksIdle ?? null,
2510
+ input.estimatedTokensSaved ?? null
2511
+ ]
2512
+ });
2513
+ } catch (err) {
2514
+ process.stderr.write(
2515
+ `[session-kill-telemetry] write failed: ${err instanceof Error ? err.message : String(err)}
2516
+ `
2517
+ );
2518
+ }
2519
+ }
2520
+ var init_session_kill_telemetry = __esm({
2521
+ "src/lib/session-kill-telemetry.ts"() {
2522
+ "use strict";
2523
+ init_database();
2524
+ }
2525
+ });
2526
+
2527
+ // src/lib/tasks-chain.ts
2528
+ import path12 from "path";
2529
+ import { readFile as readFile4, writeFile as writeFile4 } from "fs/promises";
2530
+ async function cascadeUnblock(taskId, baseDir, now) {
2531
+ const client = getClient();
2532
+ const unblocked = await client.execute({
2533
+ sql: `UPDATE tasks SET status = 'open', blocked_by = NULL, updated_at = ?
2534
+ WHERE blocked_by = ? AND status = 'blocked'`,
2535
+ args: [now, taskId]
2536
+ });
2537
+ if (baseDir && unblocked.rowsAffected > 0) {
2538
+ const unblockedRows = await client.execute({
2539
+ sql: `SELECT task_file FROM tasks WHERE blocked_by IS NULL AND updated_at = ?`,
2540
+ args: [now]
2541
+ });
2542
+ for (const ur of unblockedRows.rows) {
2543
+ try {
2544
+ const ubFile = path12.join(baseDir, String(ur.task_file));
2545
+ let ubContent = await readFile4(ubFile, "utf-8");
2546
+ ubContent = ubContent.replace(/\*\*Status:\*\* blocked/, "**Status:** open");
2547
+ ubContent = ubContent.replace(/\n\*\*Blocked by:\*\*.*\n/, "\n");
2548
+ await writeFile4(ubFile, ubContent, "utf-8");
2549
+ } catch {
2550
+ }
2551
+ }
2552
+ }
2553
+ }
2554
+ async function findNextTask(assignedTo) {
2555
+ const client = getClient();
2556
+ const nextResult = await client.execute({
2557
+ sql: `SELECT title, task_file, priority FROM tasks
2558
+ WHERE assigned_to = ? AND status = 'open'
2559
+ ORDER BY priority ASC, created_at ASC
2560
+ LIMIT 1`,
2561
+ args: [assignedTo]
2562
+ });
2563
+ if (nextResult.rows.length === 1) {
2564
+ const nr = nextResult.rows[0];
2565
+ return {
2566
+ title: String(nr.title),
2567
+ priority: String(nr.priority),
2568
+ taskFile: String(nr.task_file)
2569
+ };
2570
+ }
2571
+ return void 0;
2572
+ }
2573
+ async function checkSubtaskCompletion(parentTaskId, projectName) {
2574
+ const client = getClient();
2575
+ const remaining = await client.execute({
2576
+ sql: `SELECT COUNT(*) as cnt FROM tasks
2577
+ WHERE parent_task_id = ? AND status NOT IN ('done', 'cancelled')`,
2578
+ args: [parentTaskId]
2579
+ });
2580
+ const cnt = Number(remaining.rows[0]?.cnt ?? 1);
2581
+ if (cnt === 0) {
2582
+ const parentRow = await client.execute({
2583
+ sql: `SELECT assigned_to, title, task_file, project_name FROM tasks WHERE id = ?`,
2584
+ args: [parentTaskId]
2585
+ });
2586
+ if (parentRow.rows.length === 1) {
2587
+ const pr = parentRow.rows[0];
2588
+ const parentProject = pr.project_name == null ? projectName : String(pr.project_name);
2589
+ await writeNotification({
2590
+ agentId: String(pr.assigned_to),
2591
+ agentRole: "system",
2592
+ event: "subtasks_complete",
2593
+ project: parentProject,
2594
+ summary: `All subtasks complete for "${String(pr.title)}" \u2014 ready for rollup review`,
2595
+ taskFile: String(pr.task_file)
2596
+ });
2597
+ }
2598
+ }
2599
+ }
2600
+ var init_tasks_chain = __esm({
2601
+ "src/lib/tasks-chain.ts"() {
2602
+ "use strict";
2603
+ init_database();
2604
+ init_notifications();
2605
+ }
2606
+ });
2607
+
2608
+ // src/lib/session-scope.ts
2609
+ var session_scope_exports = {};
2610
+ __export(session_scope_exports, {
2611
+ assertSessionScope: () => assertSessionScope,
2612
+ findSessionForProject: () => findSessionForProject,
2613
+ getSessionProject: () => getSessionProject
2614
+ });
2615
+ function getSessionProject(sessionName) {
2616
+ const sessions = listSessions();
2617
+ const entry = sessions.find((s) => s.windowName === sessionName);
2618
+ if (!entry) return null;
2619
+ const parts = entry.projectDir.split("/").filter(Boolean);
2620
+ return parts[parts.length - 1] ?? null;
2621
+ }
2622
+ function findSessionForProject(projectName) {
2623
+ const sessions = listSessions();
2624
+ for (const s of sessions) {
2625
+ const proj = s.projectDir.split("/").filter(Boolean).pop();
2626
+ if (proj === projectName && s.agentId === "exe") return s;
2627
+ }
2628
+ return null;
2629
+ }
2630
+ function assertSessionScope(actionType, targetProject) {
2631
+ try {
2632
+ const currentProject = getProjectName();
2633
+ const exeSession2 = resolveExeSession();
2634
+ if (!exeSession2) {
2635
+ return { allowed: true, reason: "no_session" };
2636
+ }
2637
+ if (currentProject === targetProject) {
2638
+ return {
2639
+ allowed: true,
2640
+ reason: "same_session",
2641
+ currentProject,
2642
+ targetProject
2643
+ };
2644
+ }
2645
+ process.stderr.write(
2646
+ `[session-scope] BLOCKED cross-project ${actionType}: session project="${currentProject}" \u2260 target project="${targetProject}"
2647
+ `
2648
+ );
2649
+ return {
2650
+ allowed: false,
2651
+ reason: "cross_session_denied",
2652
+ currentProject,
2653
+ targetProject,
2654
+ targetSession: findSessionForProject(targetProject)?.windowName
2655
+ };
2656
+ } catch {
2657
+ return { allowed: true, reason: "no_session" };
2658
+ }
2659
+ }
2660
+ var init_session_scope = __esm({
2661
+ "src/lib/session-scope.ts"() {
2662
+ "use strict";
2663
+ init_session_registry();
2664
+ init_project_name();
2665
+ init_tmux_routing();
2666
+ }
2667
+ });
2668
+
2669
+ // src/lib/tasks-notify.ts
2670
+ async function dispatchTaskToEmployee(input) {
2671
+ if (input.assignedTo === "exe") return { dispatched: "skipped" };
2672
+ let crossProject = false;
2673
+ if (input.projectName) {
2674
+ try {
2675
+ const { assertSessionScope: assertSessionScope2 } = (init_session_scope(), __toCommonJS(session_scope_exports));
2676
+ const check = assertSessionScope2("dispatch_task", input.projectName);
2677
+ if (check.reason === "cross_session_denied") {
2678
+ crossProject = true;
2679
+ return { dispatched: "skipped", crossProject: true };
2680
+ }
2681
+ } catch {
2682
+ }
2683
+ }
2684
+ try {
2685
+ const transport = getTransport();
2686
+ const exeSession2 = resolveExeSession();
2687
+ if (!exeSession2) return { dispatched: "session_missing" };
2688
+ const sessionName = employeeSessionName(input.assignedTo, exeSession2);
2689
+ if (transport.isAlive(sessionName)) {
2690
+ const result = sendIntercom(sessionName);
2691
+ const dispatched = result === "acknowledged" || result === "debounced" || result === "queued" ? "verified" : result === "delivered" ? "sent_unverified" : "session_dead";
2692
+ return { dispatched, session: sessionName, crossProject };
2693
+ } else {
2694
+ const projectDir = input.projectDir ?? process.cwd();
2695
+ const result = ensureEmployee(input.assignedTo, exeSession2, projectDir, {
2696
+ autoInstance: isMultiInstance(input.assignedTo)
2697
+ });
2698
+ if (result.status === "failed") {
2699
+ process.stderr.write(
2700
+ `[dispatch] Failed to spawn ${input.assignedTo}: ${result.error}
2701
+ `
2702
+ );
2703
+ return { dispatched: "session_missing" };
2704
+ }
2705
+ return { dispatched: "spawned", session: result.sessionName, crossProject };
2706
+ }
2707
+ } catch {
2708
+ return { dispatched: "session_missing" };
2709
+ }
2710
+ }
2711
+ function notifyTaskDone() {
2712
+ try {
2713
+ const key = getSessionKey();
2714
+ if (key && !process.env.VITEST) notifyParentExe(key);
2715
+ } catch {
2716
+ }
2717
+ }
2718
+ async function markTaskNotificationsRead(taskFile) {
2719
+ try {
2720
+ await markAsReadByTaskFile(taskFile);
2721
+ } catch {
2722
+ }
2723
+ }
2724
+ var init_tasks_notify = __esm({
2725
+ "src/lib/tasks-notify.ts"() {
2726
+ "use strict";
2727
+ init_tmux_routing();
2728
+ init_session_key();
2729
+ init_notifications();
2730
+ init_transport();
2731
+ init_employees();
2732
+ }
2733
+ });
2734
+
2735
+ // src/lib/behaviors.ts
2736
+ import crypto4 from "crypto";
2737
+ async function storeBehavior(opts) {
2738
+ const client = getClient();
2739
+ const id = crypto4.randomUUID();
2740
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2741
+ await client.execute({
2742
+ sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, priority, content, active, created_at, updated_at)
2743
+ VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)`,
2744
+ args: [id, opts.agentId, opts.projectName ?? null, opts.domain ?? null, opts.priority ?? "p1", opts.content, now, now]
2745
+ });
2746
+ return id;
2747
+ }
2748
+ var init_behaviors = __esm({
2749
+ "src/lib/behaviors.ts"() {
2750
+ "use strict";
2751
+ init_database();
2752
+ }
2753
+ });
2754
+
2755
+ // src/lib/skill-learning.ts
2756
+ var skill_learning_exports = {};
2757
+ __export(skill_learning_exports, {
2758
+ captureAndLearn: () => captureAndLearn,
2759
+ captureTrajectory: () => captureTrajectory,
2760
+ editDistance: () => editDistance,
2761
+ extractSkill: () => extractSkill,
2762
+ extractTrajectory: () => extractTrajectory,
2763
+ findSimilarTrajectories: () => findSimilarTrajectories,
2764
+ hashSignature: () => hashSignature,
2765
+ storeTrajectory: () => storeTrajectory,
2766
+ sweepTrajectories: () => sweepTrajectories
2767
+ });
2768
+ import crypto5 from "crypto";
2769
+ async function extractTrajectory(taskId, agentId) {
2770
+ const client = getClient();
2771
+ const result = await client.execute({
2772
+ sql: `SELECT tool_name, raw_text
2773
+ FROM memories
2774
+ WHERE task_id = ? AND agent_id = ?
2775
+ ORDER BY timestamp ASC`,
2776
+ args: [taskId, agentId]
2777
+ });
2778
+ if (result.rows.length === 0) return [];
2779
+ const rawTools = result.rows.map((r) => {
2780
+ const toolName = String(r.tool_name);
2781
+ if (toolName === "Bash") {
2782
+ const text = String(r.raw_text);
2783
+ const cmdMatch = text.match(/(?:command|Command).*?[:\s]+"?(\w+)/);
2784
+ return cmdMatch ? `Bash:${cmdMatch[1]}` : "Bash";
2785
+ }
2786
+ return toolName;
2787
+ });
2788
+ const signature = [];
2789
+ for (const tool of rawTools) {
2790
+ if (signature.length === 0 || signature[signature.length - 1] !== tool) {
2791
+ signature.push(tool);
2792
+ }
2793
+ }
2794
+ return signature;
2795
+ }
2796
+ function hashSignature(signature) {
2797
+ return crypto5.createHash("sha256").update(signature.join("|")).digest("hex").slice(0, 16);
2798
+ }
2799
+ async function storeTrajectory(opts) {
2800
+ const client = getClient();
2801
+ const id = crypto5.randomUUID();
2802
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2803
+ const signatureHash = hashSignature(opts.signature);
2804
+ await client.execute({
2805
+ sql: `INSERT INTO trajectories (id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at)
2806
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2807
+ args: [
2808
+ id,
2809
+ opts.taskId,
2810
+ opts.agentId,
2811
+ opts.projectName,
2812
+ opts.taskTitle,
2813
+ JSON.stringify(opts.signature),
2814
+ signatureHash,
2815
+ opts.signature.length,
2816
+ now
2817
+ ]
2818
+ });
2819
+ return id;
2820
+ }
2821
+ async function findSimilarTrajectories(signature, threshold = DEFAULT_SKILL_THRESHOLD) {
2822
+ const client = getClient();
2823
+ const hash = hashSignature(signature);
2824
+ const result = await client.execute({
2825
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
2826
+ FROM trajectories
2827
+ WHERE signature_hash = ?
2828
+ ORDER BY created_at DESC
2829
+ LIMIT 20`,
2830
+ args: [hash]
2831
+ });
2832
+ const mapRow = (r) => ({
2833
+ id: String(r.id),
2834
+ taskId: String(r.task_id),
2835
+ agentId: String(r.agent_id),
2836
+ projectName: String(r.project_name),
2837
+ taskTitle: String(r.task_title),
2838
+ signature: JSON.parse(String(r.signature)),
2839
+ signatureHash: String(r.signature_hash),
2840
+ toolCount: Number(r.tool_count),
2841
+ skillId: r.skill_id ? String(r.skill_id) : null,
2842
+ createdAt: String(r.created_at)
2843
+ });
2844
+ const matches = result.rows.map(mapRow);
2845
+ if (matches.length >= threshold) return matches;
2846
+ const nearResult = await client.execute({
2847
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
2848
+ FROM trajectories
2849
+ WHERE tool_count BETWEEN ? AND ?
2850
+ AND signature_hash != ?
2851
+ ORDER BY created_at DESC
2852
+ LIMIT 50`,
2853
+ args: [
2854
+ Math.max(1, signature.length - 3),
2855
+ signature.length + 3,
2856
+ hash
2857
+ ]
2858
+ });
2859
+ for (const r of nearResult.rows) {
2860
+ const candidateSig = JSON.parse(String(r.signature));
2861
+ if (editDistance(signature, candidateSig) <= 2) {
2862
+ matches.push(mapRow(r));
2863
+ }
2864
+ }
2865
+ return matches;
2866
+ }
2867
+ async function captureTrajectory(opts) {
2868
+ const signature = await extractTrajectory(opts.taskId, opts.agentId);
2869
+ if (signature.length < 3) {
2870
+ return { trajectoryId: "", similarCount: 0, similar: [] };
2871
+ }
2872
+ const trajectoryId = await storeTrajectory({
2873
+ taskId: opts.taskId,
2874
+ agentId: opts.agentId,
2875
+ projectName: opts.projectName,
2876
+ taskTitle: opts.taskTitle,
2877
+ signature
2878
+ });
2879
+ const similar = await findSimilarTrajectories(
2880
+ signature,
2881
+ opts.skillThreshold ?? DEFAULT_SKILL_THRESHOLD
2882
+ );
2883
+ return { trajectoryId, similarCount: similar.length, similar };
2884
+ }
2885
+ function buildExtractionPrompt(trajectories) {
2886
+ const items = trajectories.map((t, i) => {
2887
+ const sig = t.signature.join(" \u2192 ");
2888
+ return `Task ${i + 1}: "${t.taskTitle}" (${t.agentId}, ${t.projectName}) \u2014 ${t.toolCount} tool calls
2889
+ Signature: ${sig}`;
2890
+ }).join("\n\n");
2891
+ return `You are analyzing ${trajectories.length} completed tasks that followed similar procedures:
2892
+
2893
+ ${items}
2894
+
2895
+ Extract the reusable procedure. Format your response EXACTLY like this:
2896
+
2897
+ SKILL: {name \u2014 short, descriptive}
2898
+ TRIGGER: {when to use this \u2014 one sentence}
2899
+ STEPS:
2900
+ 1. ...
2901
+ 2. ...
2902
+ PITFALLS: {common mistakes to avoid}
2903
+
2904
+ Be specific and actionable. Include tool names, file patterns, and concrete commands where applicable.`;
2905
+ }
2906
+ async function extractSkill(trajectories, model) {
2907
+ if (trajectories.length === 0) return null;
2908
+ const config = await loadConfig();
2909
+ const skillModel = model ?? config.skillModel;
2910
+ const Anthropic = (await import("@anthropic-ai/sdk")).default;
2911
+ const client = new Anthropic();
2912
+ const prompt = buildExtractionPrompt(trajectories);
2913
+ const response = await client.messages.create({
2914
+ model: skillModel,
2915
+ max_tokens: 500,
2916
+ messages: [{ role: "user", content: prompt }]
2917
+ });
2918
+ const textBlock = response.content.find((b) => b.type === "text");
2919
+ const skillText = textBlock?.text;
2920
+ if (!skillText) return null;
2921
+ const agentId = trajectories[0].agentId;
2922
+ const projectName = trajectories[0].projectName;
2923
+ const skillId = await storeBehavior({
2924
+ agentId,
2925
+ content: skillText,
2926
+ domain: "skill",
2927
+ projectName
2928
+ });
2929
+ const dbClient = getClient();
2930
+ for (const t of trajectories) {
2931
+ await dbClient.execute({
2932
+ sql: "UPDATE trajectories SET skill_id = ? WHERE id = ?",
2933
+ args: [skillId, t.id]
2934
+ });
2935
+ }
2936
+ process.stderr.write(
2937
+ `[skill-learning] Skill extracted from ${trajectories.length} trajectories \u2192 behavior ${skillId}
2938
+ `
2939
+ );
2940
+ return skillId;
2941
+ }
2942
+ async function captureAndLearn(opts) {
2943
+ try {
2944
+ const config = await loadConfig();
2945
+ if (!config.skillLearning) return;
2946
+ const { trajectoryId, similarCount, similar } = await captureTrajectory({
2947
+ ...opts,
2948
+ skillThreshold: config.skillThreshold
2949
+ });
2950
+ if (!trajectoryId) return;
2951
+ if (similarCount >= config.skillThreshold) {
2952
+ const unprocessed = similar.filter((t) => !t.skillId);
2953
+ if (unprocessed.length >= config.skillThreshold) {
2954
+ extractSkill(unprocessed, config.skillModel).catch((err) => {
2955
+ process.stderr.write(
2956
+ `[skill-learning] Extraction failed: ${err instanceof Error ? err.message : String(err)}
2957
+ `
2958
+ );
2959
+ });
2960
+ }
2961
+ }
2962
+ } catch (err) {
2963
+ process.stderr.write(
2964
+ `[skill-learning] captureAndLearn failed: ${err instanceof Error ? err.message : String(err)}
2965
+ `
2966
+ );
2967
+ }
2968
+ }
2969
+ async function sweepTrajectories(threshold, model) {
2970
+ const config = await loadConfig();
2971
+ if (!config.skillLearning) return { clustersProcessed: 0, skillsExtracted: 0 };
2972
+ const t = threshold ?? config.skillThreshold;
2973
+ const client = getClient();
2974
+ const result = await client.execute({
2975
+ sql: `SELECT signature_hash, COUNT(*) as cnt
2976
+ FROM trajectories
2977
+ WHERE skill_id IS NULL
2978
+ GROUP BY signature_hash
2979
+ HAVING cnt >= ?
2980
+ ORDER BY cnt DESC
2981
+ LIMIT 10`,
2982
+ args: [t]
2983
+ });
2984
+ let clustersProcessed = 0;
2985
+ let skillsExtracted = 0;
2986
+ for (const row of result.rows) {
2987
+ const hash = String(row.signature_hash);
2988
+ const trajResult = await client.execute({
2989
+ sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at
2990
+ FROM trajectories
2991
+ WHERE signature_hash = ? AND skill_id IS NULL
2992
+ ORDER BY created_at DESC
2993
+ LIMIT 10`,
2994
+ args: [hash]
2995
+ });
2996
+ const trajectories = trajResult.rows.map((r) => ({
2997
+ id: String(r.id),
2998
+ taskId: String(r.task_id),
2999
+ agentId: String(r.agent_id),
3000
+ projectName: String(r.project_name),
3001
+ taskTitle: String(r.task_title),
3002
+ signature: JSON.parse(String(r.signature)),
3003
+ signatureHash: String(r.signature_hash),
3004
+ toolCount: Number(r.tool_count),
3005
+ skillId: null,
3006
+ createdAt: String(r.created_at)
3007
+ }));
3008
+ if (trajectories.length >= t) {
3009
+ clustersProcessed++;
3010
+ const skillId = await extractSkill(trajectories, model ?? config.skillModel);
3011
+ if (skillId) skillsExtracted++;
3012
+ }
3013
+ }
3014
+ return { clustersProcessed, skillsExtracted };
3015
+ }
3016
+ function editDistance(a, b) {
3017
+ const m = a.length;
3018
+ const n = b.length;
3019
+ const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
3020
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
3021
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
3022
+ for (let i = 1; i <= m; i++) {
3023
+ for (let j = 1; j <= n; j++) {
3024
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
3025
+ dp[i][j] = Math.min(
3026
+ dp[i - 1][j] + 1,
3027
+ dp[i][j - 1] + 1,
3028
+ dp[i - 1][j - 1] + cost
3029
+ );
3030
+ }
3031
+ }
3032
+ return dp[m][n];
3033
+ }
3034
+ var DEFAULT_SKILL_THRESHOLD;
3035
+ var init_skill_learning = __esm({
3036
+ "src/lib/skill-learning.ts"() {
3037
+ "use strict";
3038
+ init_database();
3039
+ init_behaviors();
3040
+ init_config();
3041
+ DEFAULT_SKILL_THRESHOLD = 3;
3042
+ }
3043
+ });
3044
+
3045
+ // src/lib/tasks.ts
3046
+ var tasks_exports = {};
3047
+ __export(tasks_exports, {
3048
+ cleanupOrphanedReviews: () => cleanupOrphanedReviews,
3049
+ countNewPendingReviewsSince: () => countNewPendingReviewsSince,
3050
+ countPendingReviews: () => countPendingReviews,
3051
+ createTask: () => createTask,
3052
+ createTaskCore: () => createTaskCore,
3053
+ deleteTask: () => deleteTask,
3054
+ deleteTaskCore: () => deleteTaskCore,
3055
+ ensureArchitectureDoc: () => ensureArchitectureDoc,
3056
+ ensureGitignoreExe: () => ensureGitignoreExe,
3057
+ getReviewChecklist: () => getReviewChecklist,
3058
+ listPendingReviews: () => listPendingReviews,
3059
+ listTasks: () => listTasks,
3060
+ resolveTask: () => resolveTask,
3061
+ slugify: () => slugify,
3062
+ updateTask: () => updateTask,
3063
+ updateTaskStatus: () => updateTaskStatus,
3064
+ writeCheckpoint: () => writeCheckpoint
3065
+ });
3066
+ import path13 from "path";
3067
+ import { writeFileSync as writeFileSync4, mkdirSync as mkdirSync5, unlinkSync as unlinkSync3 } from "fs";
3068
+ async function createTask(input) {
3069
+ const result = await createTaskCore(input);
3070
+ if (!input.skipDispatch && result.status !== "blocked" && !process.env.VITEST) {
3071
+ dispatchTaskToEmployee({
3072
+ assignedTo: input.assignedTo,
3073
+ title: input.title,
3074
+ priority: input.priority,
3075
+ taskFile: result.taskFile,
3076
+ initialStatus: result.status,
3077
+ projectName: input.projectName
3078
+ });
3079
+ }
3080
+ return result;
3081
+ }
3082
+ async function updateTask(input) {
3083
+ const { row, taskFile, now, taskId } = await updateTaskStatus(input);
3084
+ try {
3085
+ const agent = String(row.assigned_to);
3086
+ const cacheDir = path13.join(EXE_AI_DIR, "session-cache");
3087
+ const cachePath = path13.join(cacheDir, `current-task-${agent}.json`);
3088
+ if (input.status === "in_progress") {
3089
+ mkdirSync5(cacheDir, { recursive: true });
3090
+ writeFileSync4(cachePath, JSON.stringify({ taskId, title: String(row.title) }));
3091
+ } else if (input.status === "done" || input.status === "blocked" || input.status === "cancelled") {
3092
+ try {
3093
+ unlinkSync3(cachePath);
3094
+ } catch {
3095
+ }
3096
+ }
3097
+ } catch {
3098
+ }
3099
+ if (input.status === "done") {
3100
+ await cleanupReviewFile(row, taskFile, input.baseDir);
3101
+ }
3102
+ if (input.status === "done" || input.status === "cancelled") {
3103
+ try {
3104
+ const client = getClient();
3105
+ const taskTitle = String(row.title);
3106
+ const escaped = taskTitle.replace(/%/g, "\\%").replace(/_/g, "\\_");
3107
+ await client.execute({
3108
+ sql: `UPDATE tasks SET status = 'cancelled', updated_at = ?
3109
+ WHERE title LIKE ? ESCAPE '\\' AND status IN ('open', 'in_progress')`,
3110
+ args: [now, `%left '${escaped}' as in\\_progress%`]
3111
+ });
3112
+ } catch {
3113
+ }
3114
+ try {
3115
+ const client = getClient();
3116
+ const cascaded = await client.execute({
3117
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
3118
+ WHERE parent_task_id = ? AND status = 'needs_review'`,
3119
+ args: [now, taskId]
3120
+ });
3121
+ if (cascaded.rowsAffected > 0) {
3122
+ process.stderr.write(
3123
+ `[cascade] Closed ${cascaded.rowsAffected} orphaned review task(s) for parent ${taskId}
3124
+ `
3125
+ );
3126
+ }
3127
+ } catch {
3128
+ }
3129
+ }
3130
+ const isTerminal = input.status === "done" || input.status === "needs_review";
3131
+ if (isTerminal) {
3132
+ const isExe = String(row.assigned_to) === "exe";
3133
+ if (!isExe) {
3134
+ notifyTaskDone();
3135
+ }
3136
+ await markTaskNotificationsRead(taskFile);
3137
+ if (input.status === "done") {
3138
+ try {
3139
+ await cascadeUnblock(taskId, input.baseDir, now);
3140
+ } catch {
3141
+ }
3142
+ orgBus.emit({
3143
+ type: "task_completed",
3144
+ taskId,
3145
+ employee: String(row.assigned_to),
3146
+ result: input.result ?? "",
3147
+ timestamp: now
3148
+ });
3149
+ if (row.parent_task_id) {
3150
+ try {
3151
+ await checkSubtaskCompletion(String(row.parent_task_id), String(row.project_name));
3152
+ } catch {
3153
+ }
3154
+ }
3155
+ }
3156
+ }
3157
+ if (input.status === "done" && String(row.assigned_to) !== "exe" && !process.env.VITEST) {
3158
+ Promise.resolve().then(() => (init_skill_learning(), skill_learning_exports)).then(
3159
+ ({ captureAndLearn: captureAndLearn2 }) => captureAndLearn2({
3160
+ taskId,
3161
+ agentId: String(row.assigned_to),
3162
+ projectName: String(row.project_name),
3163
+ taskTitle: String(row.title)
3164
+ })
3165
+ ).catch((err) => {
3166
+ process.stderr.write(
3167
+ `[updateTask] skill learning failed: ${err instanceof Error ? err.message : String(err)}
3168
+ `
3169
+ );
3170
+ });
3171
+ }
3172
+ let nextTask;
3173
+ if (isTerminal && String(row.assigned_to) !== "exe") {
3174
+ try {
3175
+ nextTask = await findNextTask(String(row.assigned_to));
3176
+ } catch {
3177
+ }
3178
+ }
3179
+ return {
3180
+ id: String(row.id),
3181
+ title: String(row.title),
3182
+ assignedTo: String(row.assigned_to),
3183
+ assignedBy: String(row.assigned_by),
3184
+ projectName: String(row.project_name),
3185
+ priority: String(row.priority),
3186
+ status: input.status,
3187
+ taskFile,
3188
+ createdAt: String(row.created_at),
3189
+ updatedAt: now,
3190
+ budgetTokens: row.budget_tokens !== void 0 && row.budget_tokens !== null ? Number(row.budget_tokens) : null,
3191
+ budgetFallbackModel: row.budget_fallback_model !== void 0 && row.budget_fallback_model !== null ? String(row.budget_fallback_model) : null,
3192
+ tokensUsed: Number(row.tokens_used ?? 0),
3193
+ tokensWarnedAt: row.tokens_warned_at !== void 0 && row.tokens_warned_at !== null ? Number(row.tokens_warned_at) : null,
3194
+ nextTask
3195
+ };
3196
+ }
3197
+ async function deleteTask(taskId, baseDir) {
3198
+ const client = getClient();
3199
+ const { taskFile, assignedTo, assignedBy, taskSlug } = await deleteTaskCore(taskId, baseDir);
3200
+ const reviewer = assignedBy || "exe";
3201
+ const reviewSlug = `review-${assignedTo}-${taskSlug}`;
3202
+ const reviewFile = `exe/${reviewer}/${reviewSlug}.md`;
3203
+ await client.execute({
3204
+ sql: "DELETE FROM tasks WHERE task_file = ? OR task_file = ?",
3205
+ args: [reviewFile, `exe/exe/${reviewSlug}.md`]
3206
+ });
3207
+ await markAsReadByTaskFile(taskFile);
3208
+ await markAsReadByTaskFile(reviewFile);
3209
+ }
3210
+ var init_tasks = __esm({
3211
+ "src/lib/tasks.ts"() {
3212
+ "use strict";
3213
+ init_database();
3214
+ init_config();
3215
+ init_notifications();
3216
+ init_state_bus();
3217
+ init_tasks_crud();
3218
+ init_tasks_review();
3219
+ init_tasks_crud();
3220
+ init_tasks_chain();
3221
+ init_tasks_review();
3222
+ init_tasks_notify();
3223
+ }
3224
+ });
3225
+
3226
+ // src/lib/capacity-monitor.ts
3227
+ var capacity_monitor_exports = {};
3228
+ __export(capacity_monitor_exports, {
3229
+ CTX_FLOOR_PERCENT: () => CTX_FLOOR_PERCENT,
3230
+ _resetLastRelaunchCache: () => _resetLastRelaunchCache,
3231
+ _resetPendingCapacityKills: () => _resetPendingCapacityKills,
3232
+ confirmCapacityKill: () => confirmCapacityKill,
3233
+ createOrRefreshResumeTask: () => createOrRefreshResumeTask,
3234
+ extractContextPercent: () => extractContextPercent,
3235
+ isAtCapacity: () => isAtCapacity,
3236
+ isWithinRelaunchCooldown: () => isWithinRelaunchCooldown,
3237
+ pollCapacityDead: () => pollCapacityDead
3238
+ });
3239
+ function resumeTaskTitle(agentId) {
3240
+ return `${RESUME_TITLE_PREFIX} ${agentId} hit context capacity \u2014 continue open tasks`;
3241
+ }
3242
+ function buildResumeContext(agentId, openTasks) {
3243
+ const taskList = openTasks.map(
3244
+ (r, i) => `${i + 1}. [${String(r.priority).toUpperCase()}] ${String(r.title)} (${String(r.task_file)})`
3245
+ ).join("\n");
3246
+ return [
3247
+ "## Context",
3248
+ "",
3249
+ `${agentId} hit context capacity and was auto-relaunched by the capacity monitor.`,
3250
+ "Call recall_my_memory first \u2014 search for 'CONTEXT CHECKPOINT'. Pick up where the previous session stopped.",
3251
+ "",
3252
+ `You have ${openTasks.length} open task(s). Work through them in priority order:`,
3253
+ "",
3254
+ taskList,
3255
+ "",
3256
+ "Read each task file and chain through them. Build and commit after each one."
3257
+ ].join("\n");
3258
+ }
3259
+ function filterPaneContent(paneOutput) {
3260
+ return paneOutput.split("\n").filter((line) => {
3261
+ if (CONTENT_LINE_PREFIX.test(line)) return false;
3262
+ for (const marker of CONTENT_LINE_MARKERS) {
3263
+ if (line.includes(marker)) return false;
3264
+ }
3265
+ for (const re of SOURCE_CODE_MARKERS) {
3266
+ if (re.test(line)) return false;
3267
+ }
3268
+ return true;
3269
+ }).join("\n");
3270
+ }
3271
+ function extractContextPercent(paneOutput) {
3272
+ const match = paneOutput.match(CC_CONTEXT_BAR_RE);
3273
+ if (!match) return null;
3274
+ const parsed = Number.parseInt(match[2], 10);
3275
+ return Number.isFinite(parsed) ? parsed : null;
3276
+ }
3277
+ function isAtCapacity(paneOutput) {
3278
+ const filtered = filterPaneContent(paneOutput);
3279
+ return CAPACITY_PATTERNS.some((p) => p.test(filtered));
3280
+ }
3281
+ function confirmCapacityKill(agentId, now = Date.now()) {
3282
+ const pendingSince = _pendingCapacityKill.get(agentId);
3283
+ if (pendingSince === void 0) {
3284
+ _pendingCapacityKill.set(agentId, now);
3285
+ return false;
3286
+ }
3287
+ if (now - pendingSince > CONFIRMATION_WINDOW_MS) {
3288
+ _pendingCapacityKill.set(agentId, now);
3289
+ return false;
3290
+ }
3291
+ _pendingCapacityKill.delete(agentId);
3292
+ return true;
3293
+ }
3294
+ function _resetPendingCapacityKills() {
3295
+ _pendingCapacityKill.clear();
3296
+ }
3297
+ function _resetLastRelaunchCache() {
3298
+ _lastRelaunch.clear();
3299
+ }
3300
+ async function lastResumeCreatedAtMs(agentId) {
3301
+ const client = getClient();
3302
+ const result = await client.execute({
3303
+ sql: `SELECT MAX(created_at) AS last_created_at
3304
+ FROM tasks
3305
+ WHERE assigned_to = ? AND title LIKE ?`,
3306
+ args: [agentId, `${RESUME_TITLE_PREFIX} %`]
3307
+ });
3308
+ const raw = result.rows[0]?.last_created_at;
3309
+ if (raw === null || raw === void 0) return null;
3310
+ const parsed = Date.parse(String(raw));
3311
+ return Number.isNaN(parsed) ? null : parsed;
3312
+ }
3313
+ async function isWithinRelaunchCooldown(agentId, now = Date.now()) {
3314
+ const cached = _lastRelaunch.get(agentId);
3315
+ if (cached !== void 0) return now - cached < RELAUNCH_COOLDOWN_MS;
3316
+ const persisted = await lastResumeCreatedAtMs(agentId);
3317
+ if (persisted === null) return false;
3318
+ if (now - persisted >= RELAUNCH_COOLDOWN_MS) return false;
3319
+ _lastRelaunch.set(agentId, persisted);
3320
+ return true;
3321
+ }
3322
+ async function createOrRefreshResumeTask(agentId, projectDir, openTasks) {
3323
+ const client = getClient();
3324
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3325
+ const context = buildResumeContext(agentId, openTasks);
3326
+ const existing = await client.execute({
3327
+ sql: `SELECT id FROM tasks
3328
+ WHERE assigned_to = ?
3329
+ AND title LIKE ?
3330
+ AND status IN (${RESUME_ACTIVE_STATUSES.map(() => "?").join(", ")})
3331
+ ORDER BY created_at DESC
3332
+ LIMIT 1`,
3333
+ args: [agentId, RESUME_TITLE_LIKE_PATTERN, ...RESUME_ACTIVE_STATUSES]
3334
+ });
3335
+ if (existing.rows.length > 0) {
3336
+ const taskId = String(existing.rows[0].id);
3337
+ await client.execute({
3338
+ sql: `UPDATE tasks SET context = ?, updated_at = ? WHERE id = ?`,
3339
+ args: [context, now, taskId]
3340
+ });
3341
+ return { created: false, taskId };
3342
+ }
3343
+ const { createTask: createTask2 } = await Promise.resolve().then(() => (init_tasks(), tasks_exports));
3344
+ const task = await createTask2({
3345
+ title: resumeTaskTitle(agentId),
3346
+ assignedTo: agentId,
3347
+ assignedBy: "system",
3348
+ projectName: projectDir.split("/").pop() ?? "unknown",
3349
+ priority: "p0",
3350
+ context,
3351
+ baseDir: projectDir
3352
+ });
3353
+ return { created: true, taskId: task.id };
3354
+ }
3355
+ async function pollCapacityDead() {
3356
+ const transport = getTransport();
3357
+ const relaunched = [];
3358
+ const registered = listSessions().filter(
3359
+ (s) => s.agentId !== "exe"
3360
+ );
3361
+ if (registered.length === 0) return [];
3362
+ let liveSessions;
3363
+ try {
3364
+ liveSessions = transport.listSessions();
3365
+ } catch {
3366
+ return [];
3367
+ }
3368
+ for (const entry of registered) {
3369
+ const { windowName, agentId, projectDir } = entry;
3370
+ if (!liveSessions.includes(windowName)) continue;
3371
+ if (await isWithinRelaunchCooldown(agentId)) continue;
3372
+ let pane;
3373
+ try {
3374
+ pane = transport.capturePane(windowName, 15);
3375
+ } catch {
3376
+ continue;
3377
+ }
3378
+ if (!isAtCapacity(pane)) continue;
3379
+ const ctxPct = extractContextPercent(pane);
3380
+ if (ctxPct !== null && ctxPct < CTX_FLOOR_PERCENT) {
3381
+ process.stderr.write(
3382
+ `[capacity-monitor] ctx-floor: ${agentId} at ${ctxPct}% in ${windowName} \u2014 below ${CTX_FLOOR_PERCENT}%. Skipping capacity kill (likely self-referential content or false positive).
3383
+ `
3384
+ );
3385
+ continue;
3386
+ }
3387
+ if (!confirmCapacityKill(agentId)) {
3388
+ process.stderr.write(
3389
+ `[capacity-monitor] ${agentId} matched capacity pattern once in ${windowName}. Awaiting confirmation on next tick.
3390
+ `
3391
+ );
3392
+ continue;
3393
+ }
3394
+ const verify = await verifyPaneAtCapacity(windowName);
3395
+ if (!verify.atCapacity) {
3396
+ process.stderr.write(
3397
+ `[capacity-monitor] verifyPaneAtCapacity rejected kill for ${agentId} in ${windowName} (reason: ${verify.reason}). Skipping.
3398
+ `
3399
+ );
3400
+ void recordSessionKill({
3401
+ sessionName: windowName,
3402
+ agentId,
3403
+ reason: "capacity_false_positive_blocked"
3404
+ });
3405
+ continue;
3406
+ }
3407
+ process.stderr.write(
3408
+ `[capacity-monitor] Detected ${agentId} at capacity in session ${windowName} (confirmed). Auto-relaunching.
3409
+ `
3410
+ );
3411
+ try {
3412
+ transport.kill(windowName);
3413
+ void recordSessionKill({
3414
+ sessionName: windowName,
3415
+ agentId,
3416
+ reason: "capacity"
3417
+ });
3418
+ const client = getClient();
3419
+ const openTasks = await client.execute({
3420
+ sql: `SELECT id, title, priority, task_file, status
3421
+ FROM tasks
3422
+ WHERE assigned_to = ? AND status IN ('open', 'in_progress')
3423
+ ORDER BY
3424
+ CASE priority WHEN 'p0' THEN 0 WHEN 'p1' THEN 1 WHEN 'p2' THEN 2 ELSE 3 END,
3425
+ created_at ASC
3426
+ LIMIT 10`,
3427
+ args: [agentId]
3428
+ });
3429
+ if (openTasks.rows.length === 0) {
3430
+ process.stderr.write(
3431
+ `[capacity-monitor] ${agentId} has no open tasks \u2014 skipping relaunch.
3432
+ `
3433
+ );
3434
+ continue;
3435
+ }
3436
+ const { created } = await createOrRefreshResumeTask(
3437
+ agentId,
3438
+ projectDir,
3439
+ openTasks.rows
3440
+ );
3441
+ if (created) {
3442
+ await writeNotification({
3443
+ agentId: "system",
3444
+ agentRole: "daemon",
3445
+ event: "capacity_relaunch",
3446
+ project: projectDir.split("/").pop() ?? "unknown",
3447
+ summary: `${agentId} hit context capacity. Auto-relaunched with ${openTasks.rows.length} open task(s).`
3448
+ });
3449
+ }
3450
+ _lastRelaunch.set(agentId, Date.now());
3451
+ if (created) relaunched.push(agentId);
3452
+ } catch (err) {
3453
+ process.stderr.write(
3454
+ `[capacity-monitor] Failed to relaunch ${agentId}: ${err instanceof Error ? err.message : String(err)}
3455
+ `
3456
+ );
3457
+ }
3458
+ }
3459
+ return relaunched;
3460
+ }
3461
+ 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;
3462
+ var init_capacity_monitor = __esm({
3463
+ "src/lib/capacity-monitor.ts"() {
3464
+ "use strict";
3465
+ init_session_registry();
3466
+ init_transport();
3467
+ init_notifications();
3468
+ init_database();
3469
+ init_session_kill_telemetry();
3470
+ init_tmux_routing();
3471
+ CAPACITY_PATTERNS = [
3472
+ /conversation is too long/i,
3473
+ /maximum context length/i,
3474
+ /context window.*(?:limit|exceed|full)/i,
3475
+ /reached.*(?:token|context).*limit/i
3476
+ ];
3477
+ CONTENT_LINE_PREFIX = /^[\s>#\-*[]/;
3478
+ CONTENT_LINE_MARKERS = [
3479
+ "RESUME:",
3480
+ "intercom",
3481
+ "capacity-monitor",
3482
+ "CAPACITY_PATTERNS",
3483
+ "isAtCapacity",
3484
+ "CONTENT_LINE_MARKERS",
3485
+ "pollCapacityDead",
3486
+ "confirmCapacityKill",
3487
+ "session_kills",
3488
+ "capacity-monitor.test"
3489
+ ];
3490
+ SOURCE_CODE_MARKERS = [
3491
+ /["'`/].*(?:maximum context length|conversation is too long)/i,
3492
+ /(?:maximum context length|conversation is too long).*["'`/]/i
3493
+ ];
3494
+ RELAUNCH_COOLDOWN_MS = 5 * 60 * 1e3;
3495
+ _lastRelaunch = /* @__PURE__ */ new Map();
3496
+ RESUME_TITLE_PREFIX = "RESUME:";
3497
+ RESUME_TITLE_LIKE_PATTERN = `${RESUME_TITLE_PREFIX} % hit context capacity%`;
3498
+ RESUME_ACTIVE_STATUSES = ["open", "in_progress"];
3499
+ CONFIRMATION_WINDOW_MS = 3 * 60 * 1e3;
3500
+ _pendingCapacityKill = /* @__PURE__ */ new Map();
3501
+ CC_CONTEXT_BAR_RE = /([\u2588\u2591\u2592\u2593]{10})\s+(\d+)%/;
3502
+ CTX_FLOOR_PERCENT = 50;
3503
+ }
3504
+ });
3505
+
3506
+ // src/lib/tmux-routing.ts
3507
+ var tmux_routing_exports = {};
3508
+ __export(tmux_routing_exports, {
3509
+ acquireSpawnLock: () => acquireSpawnLock2,
3510
+ employeeSessionName: () => employeeSessionName,
3511
+ ensureEmployee: () => ensureEmployee,
3512
+ extractRootExe: () => extractRootExe,
3513
+ findFreeInstance: () => findFreeInstance,
3514
+ getDispatchedBy: () => getDispatchedBy,
3515
+ getMySession: () => getMySession,
3516
+ getParentExe: () => getParentExe,
3517
+ getSessionState: () => getSessionState,
3518
+ isEmployeeAlive: () => isEmployeeAlive,
3519
+ isExeSession: () => isExeSession,
3520
+ isSessionBusy: () => isSessionBusy,
3521
+ notifyParentExe: () => notifyParentExe,
3522
+ parseParentExe: () => parseParentExe,
3523
+ registerParentExe: () => registerParentExe,
3524
+ releaseSpawnLock: () => releaseSpawnLock2,
3525
+ resolveExeSession: () => resolveExeSession,
3526
+ sendIntercom: () => sendIntercom,
3527
+ spawnEmployee: () => spawnEmployee,
3528
+ verifyPaneAtCapacity: () => verifyPaneAtCapacity
3529
+ });
3530
+ import { execFileSync as execFileSync2, execSync as execSync5 } from "child_process";
3531
+ import { readFileSync as readFileSync9, writeFileSync as writeFileSync5, mkdirSync as mkdirSync6, existsSync as existsSync11, appendFileSync } from "fs";
3532
+ import path14 from "path";
3533
+ import os6 from "os";
3534
+ import { fileURLToPath as fileURLToPath2 } from "url";
3535
+ import { unlinkSync as unlinkSync4 } from "fs";
3536
+ function spawnLockPath(sessionName) {
3537
+ return path14.join(SPAWN_LOCK_DIR, `${sessionName}.lock`);
3538
+ }
3539
+ function isProcessAlive(pid) {
3540
+ try {
3541
+ process.kill(pid, 0);
3542
+ return true;
3543
+ } catch {
3544
+ return false;
3545
+ }
3546
+ }
3547
+ function acquireSpawnLock2(sessionName) {
3548
+ if (!existsSync11(SPAWN_LOCK_DIR)) {
3549
+ mkdirSync6(SPAWN_LOCK_DIR, { recursive: true });
3550
+ }
3551
+ const lockFile = spawnLockPath(sessionName);
3552
+ if (existsSync11(lockFile)) {
3553
+ try {
3554
+ const lock = JSON.parse(readFileSync9(lockFile, "utf8"));
3555
+ const age = Date.now() - lock.timestamp;
3556
+ if (isProcessAlive(lock.pid) && age < 6e4) {
3557
+ return false;
3558
+ }
3559
+ } catch {
3560
+ }
3561
+ }
3562
+ writeFileSync5(lockFile, JSON.stringify({ pid: process.pid, timestamp: Date.now() }));
3563
+ return true;
3564
+ }
3565
+ function releaseSpawnLock2(sessionName) {
3566
+ try {
3567
+ unlinkSync4(spawnLockPath(sessionName));
3568
+ } catch {
3569
+ }
3570
+ }
3571
+ function resolveBehaviorsExporterScript() {
3572
+ try {
3573
+ const thisFile = fileURLToPath2(import.meta.url);
3574
+ const scriptPath = path14.join(
3575
+ path14.dirname(thisFile),
3576
+ "..",
3577
+ "bin",
3578
+ "exe-export-behaviors.js"
3579
+ );
3580
+ return existsSync11(scriptPath) ? scriptPath : null;
3581
+ } catch {
3582
+ return null;
3583
+ }
3584
+ }
3585
+ function exportBehaviorsSync(agentId, projectName, sessionKey) {
3586
+ const script = resolveBehaviorsExporterScript();
3587
+ if (!script) return null;
3588
+ try {
3589
+ const output = execFileSync2(
3590
+ process.execPath,
3591
+ [script, agentId, projectName, sessionKey],
3592
+ { encoding: "utf-8", timeout: BEHAVIORS_EXPORT_TIMEOUT_MS }
3593
+ ).trim();
3594
+ return output.length > 0 ? output : null;
3595
+ } catch (err) {
3596
+ process.stderr.write(
3597
+ `[tmux-routing] behaviors export failed for ${agentId}: ${err instanceof Error ? err.message : String(err)}
3598
+ `
3599
+ );
3600
+ return null;
3601
+ }
3602
+ }
3603
+ function getMySession() {
3604
+ return getTransport().getMySession();
3605
+ }
3606
+ function employeeSessionName(employee, exeSession2, instance) {
3607
+ if (!/^exe\d+$/.test(exeSession2)) {
3608
+ const root = extractRootExe(exeSession2);
3609
+ if (root) {
3610
+ process.stderr.write(
3611
+ `[tmux-routing] WARN: exeSession="${exeSession2}" is not a root exe session, using "${root}" instead
3612
+ `
3613
+ );
3614
+ exeSession2 = root;
3615
+ } else {
3616
+ throw new Error(
3617
+ `Invalid exeSession "${exeSession2}" \u2014 must be a root exe session (e.g., "exe1"), not an agent session`
3618
+ );
3619
+ }
3620
+ }
3621
+ const suffix = instance != null && instance > 0 ? String(instance) : "";
3622
+ const name = `${employee}${suffix}-${exeSession2}`;
3623
+ if (!VALID_SESSION_NAME.test(name)) {
3624
+ throw new Error(
3625
+ `Invalid session name "${name}" \u2014 must match {agent}-exe{N} or {agent}{instance}-exe{N}`
3626
+ );
3627
+ }
3628
+ return name;
3629
+ }
3630
+ function parseParentExe(sessionName, agentId) {
3631
+ const escaped = agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3632
+ const regex = new RegExp(`^${escaped}\\d*-(.+)$`);
3633
+ const match = sessionName.match(regex);
3634
+ return match?.[1] ?? null;
3635
+ }
3636
+ function extractRootExe(name) {
3637
+ const match = name.match(/(exe\d+)$/);
3638
+ return match?.[1] ?? null;
3639
+ }
3640
+ function registerParentExe(sessionKey, parentExe, dispatchedBy) {
3641
+ if (!existsSync11(SESSION_CACHE)) {
3642
+ mkdirSync6(SESSION_CACHE, { recursive: true });
3643
+ }
3644
+ const rootExe = extractRootExe(parentExe) ?? parentExe;
3645
+ const filePath = path14.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`);
3646
+ writeFileSync5(filePath, JSON.stringify({
3647
+ parentExe: rootExe,
3648
+ dispatchedBy: dispatchedBy || rootExe,
3649
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString()
3650
+ }));
3651
+ }
3652
+ function getParentExe(sessionKey) {
3653
+ try {
3654
+ const data = JSON.parse(readFileSync9(path14.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
3655
+ return data.parentExe || null;
3656
+ } catch {
3657
+ return null;
3658
+ }
3659
+ }
3660
+ function getDispatchedBy(sessionKey) {
3661
+ try {
3662
+ const data = JSON.parse(readFileSync9(
3663
+ path14.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`),
3664
+ "utf8"
3665
+ ));
3666
+ return data.dispatchedBy ?? data.parentExe ?? null;
3667
+ } catch {
3668
+ return null;
3669
+ }
3670
+ }
3671
+ function resolveExeSession() {
3672
+ const mySession = getMySession();
3673
+ if (!mySession) return null;
3674
+ try {
3675
+ const key = getSessionKey();
3676
+ const parentExe = getParentExe(key);
3677
+ if (parentExe) {
3678
+ return extractRootExe(parentExe) ?? parentExe;
3679
+ }
3680
+ } catch {
3681
+ }
3682
+ return extractRootExe(mySession) ?? mySession;
3683
+ }
3684
+ function isEmployeeAlive(sessionName) {
3685
+ return getTransport().isAlive(sessionName);
3686
+ }
3687
+ function findFreeInstance(employeeName, exeSession2, maxInstances = 10, isAlive = isEmployeeAlive) {
3688
+ const base = employeeSessionName(employeeName, exeSession2);
3689
+ if (!isAlive(base) && acquireSpawnLock2(base)) return 0;
3690
+ for (let i = 2; i <= maxInstances; i++) {
3691
+ const candidate = employeeSessionName(employeeName, exeSession2, i);
3692
+ if (!isAlive(candidate) && acquireSpawnLock2(candidate)) return i;
3693
+ }
3694
+ return null;
3695
+ }
3696
+ async function verifyPaneAtCapacity(sessionName) {
3697
+ const transport = getTransport();
3698
+ if (!transport.isAlive(sessionName)) {
3699
+ return { atCapacity: false, reason: `session ${sessionName} is not alive` };
3700
+ }
3701
+ let pane;
3702
+ try {
3703
+ pane = transport.capturePane(sessionName, VERIFY_PANE_LINES);
3704
+ } catch (err) {
3705
+ return {
3706
+ atCapacity: false,
3707
+ reason: `capture-pane failed: ${err instanceof Error ? err.message : String(err)}`
3708
+ };
3709
+ }
3710
+ const { isAtCapacity: isAtCapacity2 } = await Promise.resolve().then(() => (init_capacity_monitor(), capacity_monitor_exports));
3711
+ if (!isAtCapacity2(pane)) {
3712
+ return {
3713
+ atCapacity: false,
3714
+ reason: `last ${VERIFY_PANE_LINES} lines show normal work, no capacity banner`
3715
+ };
3716
+ }
3717
+ return {
3718
+ atCapacity: true,
3719
+ reason: "capacity banner matched in recent pane output"
3720
+ };
3721
+ }
3722
+ function readDebounceState() {
3723
+ try {
3724
+ if (!existsSync11(DEBOUNCE_FILE)) return {};
3725
+ return JSON.parse(readFileSync9(DEBOUNCE_FILE, "utf8"));
3726
+ } catch {
3727
+ return {};
3728
+ }
3729
+ }
3730
+ function writeDebounceState(state) {
3731
+ try {
3732
+ if (!existsSync11(SESSION_CACHE)) mkdirSync6(SESSION_CACHE, { recursive: true });
3733
+ writeFileSync5(DEBOUNCE_FILE, JSON.stringify(state));
3734
+ } catch {
3735
+ }
3736
+ }
3737
+ function isDebounced(targetSession) {
3738
+ const state = readDebounceState();
3739
+ const lastSent = state[targetSession] ?? 0;
3740
+ return Date.now() - lastSent < INTERCOM_DEBOUNCE_MS;
3741
+ }
3742
+ function recordDebounce(targetSession) {
3743
+ const state = readDebounceState();
3744
+ state[targetSession] = Date.now();
3745
+ const cutoff = Date.now() - DEBOUNCE_CLEANUP_AGE_MS;
3746
+ for (const key of Object.keys(state)) {
3747
+ if ((state[key] ?? 0) < cutoff) delete state[key];
3748
+ }
3749
+ writeDebounceState(state);
3750
+ }
3751
+ function logIntercom(msg) {
3752
+ const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${msg}
3753
+ `;
3754
+ process.stderr.write(`[intercom] ${msg}
3755
+ `);
3756
+ try {
3757
+ appendFileSync(INTERCOM_LOG2, line);
3758
+ } catch {
3759
+ }
3760
+ }
3761
+ function getSessionState(sessionName) {
3762
+ const transport = getTransport();
3763
+ if (!transport.isAlive(sessionName)) return "offline";
3764
+ try {
3765
+ const pane = transport.capturePane(sessionName, 5);
3766
+ if (!pane.includes("\u276F") && !pane.includes("Claude Code") && !BUSY_PATTERN.test(pane) && !/Running…/.test(pane)) {
3767
+ if (/\$\s*$/.test(pane) || /% $/.test(pane.trimEnd())) {
3768
+ return "no_claude";
3769
+ }
3770
+ }
3771
+ if (/Running…/.test(pane)) return "tool";
3772
+ if (BUSY_PATTERN.test(pane)) return "thinking";
3773
+ return "idle";
3774
+ } catch {
3775
+ return "offline";
3776
+ }
3777
+ }
3778
+ function isSessionBusy(sessionName) {
3779
+ const state = getSessionState(sessionName);
3780
+ return state === "thinking" || state === "tool";
3781
+ }
3782
+ function isExeSession(sessionName) {
3783
+ return /^exe\d*$/.test(sessionName);
3784
+ }
3785
+ function sendIntercom(targetSession) {
3786
+ const transport = getTransport();
3787
+ if (isExeSession(targetSession)) {
3788
+ logIntercom(`SKIP_EXE \u2192 ${targetSession} (exe sessions use prompt-submit hook)`);
3789
+ return "skipped_exe";
3790
+ }
3791
+ if (isDebounced(targetSession)) {
3792
+ logIntercom(`DEBOUNCE \u2192 ${targetSession} (cross-process file debounce)`);
3793
+ return "debounced";
3794
+ }
3795
+ try {
3796
+ const sessions = transport.listSessions();
3797
+ if (!sessions.includes(targetSession)) {
3798
+ logIntercom(`SKIP \u2192 ${targetSession} (session not found)`);
3799
+ return "failed";
3800
+ }
3801
+ const sessionState = getSessionState(targetSession);
3802
+ if (sessionState === "no_claude") {
3803
+ queueIntercom(targetSession, "claude not running in session");
3804
+ recordDebounce(targetSession);
3805
+ logIntercom(`QUEUED \u2192 ${targetSession} (no claude process \u2014 raw shell detected)`);
3806
+ return "queued";
3807
+ }
3808
+ if (sessionState === "thinking" || sessionState === "tool") {
3809
+ queueIntercom(targetSession, "session busy at send time");
3810
+ recordDebounce(targetSession);
3811
+ logIntercom(`QUEUED \u2192 ${targetSession} (session busy, will retry from queue)`);
3812
+ return "queued";
3813
+ }
3814
+ if (transport.isPaneInCopyMode(targetSession)) {
3815
+ logIntercom(`COPY_MODE \u2192 ${targetSession} (exiting copy mode first)`);
3816
+ transport.sendKeys(targetSession, "q");
3817
+ }
3818
+ transport.sendKeys(targetSession, "/exe-intercom");
3819
+ recordDebounce(targetSession);
3820
+ logIntercom(`DELIVERED \u2192 ${targetSession} (fire-and-forget)`);
3821
+ return "delivered";
3822
+ } catch {
3823
+ logIntercom(`FAIL \u2192 ${targetSession}`);
3824
+ return "failed";
3825
+ }
3826
+ }
3827
+ function notifyParentExe(sessionKey) {
3828
+ const target = getDispatchedBy(sessionKey);
3829
+ if (!target) {
3830
+ process.stderr.write(`[intercom] notifyParentExe: no dispatcher found for key ${sessionKey}
3831
+ `);
3832
+ return false;
3833
+ }
3834
+ process.stderr.write(`[intercom] notifyParentExe \u2192 ${target}
3835
+ `);
3836
+ const result = sendIntercom(target);
3837
+ if (result === "failed") {
3838
+ const rootExe = resolveExeSession();
3839
+ if (rootExe && rootExe !== target) {
3840
+ process.stderr.write(`[intercom] notifyParentExe: dispatcher ${target} dead, falling back to root exe ${rootExe}
3841
+ `);
3842
+ const fallback = sendIntercom(rootExe);
3843
+ return fallback !== "failed";
3844
+ }
3845
+ return false;
3846
+ }
3847
+ return true;
3848
+ }
3849
+ function ensureEmployee(employeeName, exeSession2, projectDir, opts) {
3850
+ if (employeeName === "exe") {
3851
+ return { status: "failed", sessionName: "", error: "exe is the COO, not a dispatchable employee" };
3852
+ }
3853
+ try {
3854
+ assertEmployeeLimitSync();
3855
+ } catch (err) {
3856
+ if (err instanceof PlanLimitError) {
3857
+ return { status: "failed", sessionName: "", error: err.message };
3858
+ }
3859
+ }
3860
+ if (/-exe\d*$/.test(employeeName)) {
3861
+ const bare = employeeName.replace(/-exe\d*$/, "").replace(/\d+$/, "");
3862
+ return {
3863
+ status: "failed",
3864
+ sessionName: "",
3865
+ error: `Error: pass employee name ('${bare}'), not session name ('${employeeName}')`
3866
+ };
3867
+ }
3868
+ if (!/^exe\d+$/.test(exeSession2)) {
3869
+ const root = extractRootExe(exeSession2);
3870
+ if (root) {
3871
+ process.stderr.write(
3872
+ `[ensureEmployee] WARN: caller passed exeSession="${exeSession2}" (not a root exe). Auto-correcting to "${root}".
3873
+ `
3874
+ );
3875
+ exeSession2 = root;
3876
+ } else {
3877
+ return {
3878
+ status: "failed",
3879
+ sessionName: "",
3880
+ error: `Invalid exeSession "${exeSession2}" \u2014 must be a root exe session (e.g., "exe1")`
3881
+ };
3882
+ }
3883
+ }
3884
+ let effectiveInstance = opts?.instance;
3885
+ if (effectiveInstance === void 0 && opts?.autoInstance) {
3886
+ const free = findFreeInstance(
3887
+ employeeName,
3888
+ exeSession2,
3889
+ opts.maxAutoInstances ?? 10
3890
+ );
3891
+ if (free === null) {
3892
+ return {
3893
+ status: "failed",
3894
+ sessionName: employeeSessionName(employeeName, exeSession2),
3895
+ error: `All ${opts.maxAutoInstances ?? 10} instances of ${employeeName} are alive \u2014 cap reached`
3896
+ };
3897
+ }
3898
+ effectiveInstance = free === 0 ? void 0 : free;
3899
+ }
3900
+ const sessionName = employeeSessionName(employeeName, exeSession2, effectiveInstance);
3901
+ if (isEmployeeAlive(sessionName)) {
3902
+ const result2 = sendIntercom(sessionName);
3903
+ if (result2 === "acknowledged" || result2 === "skipped_exe" || result2 === "debounced" || result2 === "queued") {
3904
+ return { status: "intercom_sent", sessionName };
3905
+ }
3906
+ if (result2 === "delivered") {
3907
+ return { status: "intercom_unprocessed", sessionName };
3908
+ }
3909
+ return { status: "failed", sessionName, error: "intercom delivery failed" };
3910
+ }
3911
+ const spawnOpts = { ...opts, instance: effectiveInstance };
3912
+ const result = spawnEmployee(employeeName, exeSession2, projectDir, spawnOpts);
3913
+ if (result.error) {
3914
+ return { status: "failed", sessionName, error: result.error };
3915
+ }
3916
+ return { status: "spawned", sessionName };
3917
+ }
3918
+ function spawnEmployee(employeeName, exeSession2, projectDir, opts) {
3919
+ const transport = getTransport();
3920
+ const sessionName = employeeSessionName(employeeName, exeSession2, opts?.instance);
3921
+ const instanceLabel2 = opts?.instance != null && opts.instance > 0 ? `${employeeName}${opts.instance}` : employeeName;
3922
+ const logDir = path14.join(os6.homedir(), ".exe-os", "session-logs");
3923
+ const logFile = path14.join(logDir, `${instanceLabel2}-${Date.now()}.log`);
3924
+ if (!existsSync11(logDir)) {
3925
+ mkdirSync6(logDir, { recursive: true });
3926
+ }
3927
+ transport.kill(sessionName);
3928
+ let cleanupSuffix = "";
3929
+ try {
3930
+ const thisFile = fileURLToPath2(import.meta.url);
3931
+ const cleanupScript = path14.join(path14.dirname(thisFile), "..", "bin", "exe-session-cleanup.js");
3932
+ if (existsSync11(cleanupScript)) {
3933
+ cleanupSuffix = `; ${process.execPath} "${cleanupScript}" "${employeeName}" "${exeSession2}"`;
3934
+ }
3935
+ } catch {
3936
+ }
3937
+ try {
3938
+ const claudeJsonPath = path14.join(os6.homedir(), ".claude.json");
3939
+ let claudeJson = {};
3940
+ try {
3941
+ claudeJson = JSON.parse(readFileSync9(claudeJsonPath, "utf8"));
3942
+ } catch {
3943
+ }
3944
+ if (!claudeJson.projects) claudeJson.projects = {};
3945
+ const projects = claudeJson.projects;
3946
+ const trustDir = opts?.cwd ?? projectDir;
3947
+ if (!projects[trustDir]) projects[trustDir] = {};
3948
+ projects[trustDir].hasTrustDialogAccepted = true;
3949
+ writeFileSync5(claudeJsonPath, JSON.stringify(claudeJson, null, 2) + "\n");
3950
+ } catch {
3951
+ }
3952
+ try {
3953
+ const settingsDir = path14.join(os6.homedir(), ".claude", "projects");
3954
+ const normalizedKey = (opts?.cwd ?? projectDir).replace(/\//g, "-").replace(/^-/, "");
3955
+ const projSettingsDir = path14.join(settingsDir, normalizedKey);
3956
+ const settingsPath = path14.join(projSettingsDir, "settings.json");
3957
+ let settings = {};
3958
+ try {
3959
+ settings = JSON.parse(readFileSync9(settingsPath, "utf8"));
3960
+ } catch {
3961
+ }
3962
+ const perms = settings.permissions ?? {};
3963
+ const allow = perms.allow ?? [];
3964
+ const toolNames = [
3965
+ "recall_my_memory",
3966
+ "store_memory",
3967
+ "create_task",
3968
+ "update_task",
3969
+ "list_tasks",
3970
+ "get_task",
3971
+ "ask_team_memory",
3972
+ "store_behavior",
3973
+ "get_identity",
3974
+ "send_message"
3975
+ ];
3976
+ const requiredTools = expandDualPrefixTools(toolNames);
3977
+ let changed = false;
3978
+ for (const tool of requiredTools) {
3979
+ if (!allow.includes(tool)) {
3980
+ allow.push(tool);
3981
+ changed = true;
3982
+ }
3983
+ }
3984
+ if (changed) {
3985
+ perms.allow = allow;
3986
+ settings.permissions = perms;
3987
+ mkdirSync6(projSettingsDir, { recursive: true });
3988
+ writeFileSync5(settingsPath, JSON.stringify(settings, null, 2) + "\n");
3989
+ }
3990
+ } catch {
3991
+ }
3992
+ const spawnCwd = opts?.cwd ?? projectDir;
3993
+ const useExeAgent = !!(opts?.model && opts?.provider);
3994
+ const ccProvider = useExeAgent ? DEFAULT_PROVIDER : detectActiveProvider();
3995
+ const useBinSymlink = ccProvider !== DEFAULT_PROVIDER;
3996
+ let identityFlag = "";
3997
+ let behaviorsFlag = "";
3998
+ let legacyFallbackWarned = false;
3999
+ if (!useExeAgent && !useBinSymlink) {
4000
+ const identityPath = path14.join(
4001
+ os6.homedir(),
4002
+ ".exe-os",
4003
+ "identity",
4004
+ `${employeeName}.md`
4005
+ );
4006
+ _resetCcAgentSupportCache();
4007
+ const hasAgentFlag = claudeSupportsAgentFlag();
4008
+ if (hasAgentFlag) {
4009
+ identityFlag = ` --agent ${employeeName}`;
4010
+ } else if (existsSync11(identityPath)) {
4011
+ identityFlag = ` --append-system-prompt-file ${identityPath}`;
4012
+ legacyFallbackWarned = true;
4013
+ }
4014
+ const behaviorsFile = exportBehaviorsSync(
4015
+ employeeName,
4016
+ path14.basename(spawnCwd),
4017
+ sessionName
4018
+ );
4019
+ if (behaviorsFile) {
4020
+ behaviorsFlag = ` --append-system-prompt-file ${behaviorsFile}`;
4021
+ }
4022
+ }
4023
+ if (legacyFallbackWarned) {
4024
+ process.stderr.write(
4025
+ `[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.
4026
+ `
4027
+ );
4028
+ }
4029
+ let sessionContextFlag = "";
4030
+ try {
4031
+ const ctxDir = path14.join(os6.homedir(), ".exe-os", "session-cache");
4032
+ mkdirSync6(ctxDir, { recursive: true });
4033
+ const ctxFile = path14.join(ctxDir, `session-context-${sessionName}.md`);
4034
+ const ctxContent = [
4035
+ `## Session Context`,
4036
+ `You are running in tmux session: ${sessionName}.`,
4037
+ `Your parent exe session is ${exeSession2}.`,
4038
+ `Your employees (if any) use the -${exeSession2} suffix (e.g., tom-${exeSession2}).`
4039
+ ].join("\n");
4040
+ writeFileSync5(ctxFile, ctxContent);
4041
+ sessionContextFlag = ` --append-system-prompt-file ${ctxFile}`;
4042
+ } catch {
4043
+ }
4044
+ let envPrefix = `EXE_SESSION=${exeSession2} EXE_SESSION_NAME=${sessionName}`;
4045
+ if (ccProvider !== DEFAULT_PROVIDER) {
4046
+ const cfg = PROVIDER_TABLE[ccProvider];
4047
+ if (cfg?.apiKeyEnv) {
4048
+ const keyVal = process.env[cfg.apiKeyEnv];
4049
+ if (keyVal) {
4050
+ envPrefix = `${envPrefix} ${cfg.apiKeyEnv}=${keyVal}`;
4051
+ }
4052
+ }
4053
+ }
4054
+ let spawnCommand;
4055
+ if (useExeAgent) {
4056
+ spawnCommand = `${envPrefix} exe-agent --employee ${employeeName} --model ${opts.model} --provider ${opts.provider}${cleanupSuffix}`;
4057
+ } else if (useBinSymlink) {
4058
+ const binName = `${employeeName}-${ccProvider}`;
4059
+ process.stderr.write(
4060
+ `[tmux-routing] provider cascade: ${ccProvider} \u2192 spawning ${binName}
4061
+ `
4062
+ );
4063
+ spawnCommand = `${envPrefix} ${binName}${cleanupSuffix}`;
4064
+ } else {
4065
+ spawnCommand = `${envPrefix} claude --dangerously-skip-permissions${identityFlag}${behaviorsFlag}${sessionContextFlag}${cleanupSuffix}`;
4066
+ }
4067
+ const spawnResult = transport.spawn(sessionName, {
4068
+ cwd: spawnCwd,
4069
+ command: spawnCommand
4070
+ });
4071
+ if (spawnResult.error) {
4072
+ releaseSpawnLock2(sessionName);
4073
+ return { sessionName, error: `tmux new-session failed: ${spawnResult.error}` };
4074
+ }
4075
+ transport.pipeLog(sessionName, logFile);
4076
+ try {
4077
+ const mySession = getMySession();
4078
+ const dispatchInfo = path14.join(SESSION_CACHE, `dispatch-info-${sessionName}.json`);
4079
+ writeFileSync5(dispatchInfo, JSON.stringify({
4080
+ dispatchedBy: mySession,
4081
+ rootExe: exeSession2,
4082
+ provider: useBinSymlink ? ccProvider : useExeAgent ? opts.provider : "anthropic",
4083
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
4084
+ }));
4085
+ } catch {
4086
+ }
4087
+ let booted = false;
4088
+ for (let i = 0; i < 30; i++) {
4089
+ try {
4090
+ execSync5("sleep 0.5");
4091
+ } catch {
4092
+ }
4093
+ try {
4094
+ const pane = transport.capturePane(sessionName);
4095
+ if (useExeAgent) {
4096
+ if (pane.includes("[exe-agent]") || pane.includes("online")) {
4097
+ booted = true;
4098
+ break;
4099
+ }
4100
+ } else {
4101
+ if (pane.includes("Claude Code") || pane.includes("\u276F")) {
4102
+ booted = true;
4103
+ break;
4104
+ }
4105
+ }
4106
+ } catch {
4107
+ }
4108
+ }
4109
+ if (!booted) {
4110
+ releaseSpawnLock2(sessionName);
4111
+ return { sessionName, error: `${useExeAgent ? "exe-agent" : "claude"} did not boot within 15s` };
4112
+ }
4113
+ if (!useExeAgent) {
4114
+ try {
4115
+ transport.sendKeys(sessionName, `/exe-call ${employeeName}`);
4116
+ } catch {
4117
+ }
4118
+ }
4119
+ registerSession({
4120
+ windowName: sessionName,
4121
+ agentId: employeeName,
4122
+ projectDir: spawnCwd,
4123
+ parentExe: exeSession2,
4124
+ pid: 0,
4125
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString()
4126
+ });
4127
+ releaseSpawnLock2(sessionName);
4128
+ return { sessionName };
4129
+ }
4130
+ 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;
4131
+ var init_tmux_routing = __esm({
4132
+ "src/lib/tmux-routing.ts"() {
4133
+ "use strict";
4134
+ init_session_registry();
4135
+ init_session_key();
4136
+ init_transport();
4137
+ init_cc_agent_support();
4138
+ init_mcp_prefix();
4139
+ init_provider_table();
4140
+ init_intercom_queue();
4141
+ init_plan_limits();
4142
+ SPAWN_LOCK_DIR = path14.join(os6.homedir(), ".exe-os", "spawn-locks");
4143
+ SESSION_CACHE = path14.join(os6.homedir(), ".exe-os", "session-cache");
4144
+ BEHAVIORS_EXPORT_TIMEOUT_MS = 1e4;
4145
+ VALID_SESSION_NAME = /^[a-z]+-exe\d+$|^[a-z]+\d+-exe\d+$/;
4146
+ VERIFY_PANE_LINES = 200;
4147
+ INTERCOM_DEBOUNCE_MS = 3e4;
4148
+ INTERCOM_LOG2 = path14.join(os6.homedir(), ".exe-os", "intercom.log");
4149
+ DEBOUNCE_FILE = path14.join(SESSION_CACHE, "intercom-debounce.json");
4150
+ DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
4151
+ BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
4152
+ }
4153
+ });
4154
+
4155
+ // src/lib/tasks-crud.ts
4156
+ import crypto6 from "crypto";
4157
+ import path15 from "path";
4158
+ import { execSync as execSync6 } from "child_process";
4159
+ import { mkdir as mkdir4, writeFile as writeFile5, appendFile } from "fs/promises";
4160
+ import { existsSync as existsSync12, readFileSync as readFileSync10 } from "fs";
4161
+ async function writeCheckpoint(input) {
4162
+ const client = getClient();
4163
+ const row = await resolveTask(client, input.taskId);
4164
+ const taskId = String(row.id);
4165
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4166
+ const blockedByIds = [];
4167
+ if (row.blocked_by) {
4168
+ blockedByIds.push(String(row.blocked_by));
4169
+ }
4170
+ const checkpoint = {
4171
+ step: input.step,
4172
+ context_summary: input.contextSummary,
4173
+ files_touched: input.filesTouched ?? [],
4174
+ blocked_by_ids: blockedByIds,
4175
+ last_checkpoint_at: now
4176
+ };
4177
+ const result = await client.execute({
4178
+ sql: `UPDATE tasks SET checkpoint = ?, checkpoint_count = checkpoint_count + 1, updated_at = ? WHERE id = ?`,
4179
+ args: [JSON.stringify(checkpoint), now, taskId]
4180
+ });
4181
+ if (result.rowsAffected === 0) {
4182
+ throw new Error(`Checkpoint write failed: task ${taskId} not found`);
4183
+ }
4184
+ const countResult = await client.execute({
4185
+ sql: "SELECT checkpoint_count FROM tasks WHERE id = ?",
4186
+ args: [taskId]
4187
+ });
4188
+ const checkpointCount = Number(countResult.rows[0]?.checkpoint_count ?? 1);
4189
+ return { checkpointCount };
4190
+ }
4191
+ function extractParentFromContext(contextBody) {
4192
+ if (!contextBody) return null;
4193
+ const match = contextBody.match(
4194
+ /Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
4195
+ );
4196
+ return match ? match[1].toLowerCase() : null;
4197
+ }
4198
+ function slugify(title) {
4199
+ return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
4200
+ }
4201
+ async function resolveTask(client, identifier) {
4202
+ let result = await client.execute({
4203
+ sql: "SELECT * FROM tasks WHERE id = ?",
4204
+ args: [identifier]
4205
+ });
4206
+ if (result.rows.length === 1) return result.rows[0];
4207
+ result = await client.execute({
4208
+ sql: "SELECT * FROM tasks WHERE task_file LIKE ?",
4209
+ args: [`%${identifier}%`]
4210
+ });
4211
+ if (result.rows.length === 1) return result.rows[0];
4212
+ if (result.rows.length > 1) {
4213
+ const exact = result.rows.filter(
4214
+ (r) => String(r.task_file).endsWith(`/${identifier}.md`)
4215
+ );
4216
+ if (exact.length === 1) return exact[0];
4217
+ const candidates = exact.length > 1 ? exact : result.rows;
4218
+ const active = candidates.filter(
4219
+ (r) => !["done", "cancelled"].includes(String(r.status))
4220
+ );
4221
+ if (active.length === 1) return active[0];
4222
+ const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
4223
+ throw new Error(
4224
+ `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
4225
+ );
4226
+ }
4227
+ result = await client.execute({
4228
+ sql: "SELECT * FROM tasks WHERE title LIKE ?",
4229
+ args: [`%${identifier}%`]
4230
+ });
4231
+ if (result.rows.length === 1) return result.rows[0];
4232
+ if (result.rows.length > 1) {
4233
+ const active = result.rows.filter(
4234
+ (r) => !["done", "cancelled"].includes(String(r.status))
4235
+ );
4236
+ if (active.length === 1) return active[0];
4237
+ const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
4238
+ throw new Error(
4239
+ `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
4240
+ );
4241
+ }
4242
+ throw new Error(`Task not found: ${identifier}`);
4243
+ }
4244
+ async function createTaskCore(input) {
4245
+ const client = getClient();
4246
+ const id = crypto6.randomUUID();
4247
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4248
+ const slug = slugify(input.title);
4249
+ const taskFile = input.taskFile ?? `exe/${input.assignedTo}/${slug}.md`;
4250
+ let blockedById = null;
4251
+ const initialStatus = input.blockedBy ? "blocked" : "open";
4252
+ if (input.blockedBy) {
4253
+ const blocker = await resolveTask(client, input.blockedBy);
4254
+ blockedById = String(blocker.id);
4255
+ }
4256
+ let parentTaskId = null;
4257
+ let parentRef = input.parentTaskId;
4258
+ if (!parentRef) {
4259
+ const extracted = extractParentFromContext(input.context);
4260
+ if (extracted) {
4261
+ parentRef = extracted;
4262
+ process.stderr.write(
4263
+ "[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
4264
+ );
4265
+ }
4266
+ }
4267
+ if (parentRef) {
4268
+ try {
4269
+ const parent = await resolveTask(client, parentRef);
4270
+ parentTaskId = String(parent.id);
4271
+ } catch (err) {
4272
+ if (!input.parentTaskId) {
4273
+ throw new Error(
4274
+ `create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
4275
+ );
4276
+ }
4277
+ throw err;
4278
+ }
2385
4279
  }
2386
- });
2387
-
2388
- // src/lib/plan-limits.ts
2389
- import { readFileSync as readFileSync8, existsSync as existsSync10 } from "fs";
2390
- import path12 from "path";
2391
- var CACHE_PATH2;
2392
- var init_plan_limits = __esm({
2393
- "src/lib/plan-limits.ts"() {
2394
- "use strict";
2395
- init_database();
2396
- init_employees();
2397
- init_license();
2398
- init_config();
2399
- CACHE_PATH2 = path12.join(EXE_AI_DIR, "license-cache.json");
4280
+ let warning;
4281
+ const dupCheck = await client.execute({
4282
+ sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
4283
+ args: [input.title, input.assignedTo]
4284
+ });
4285
+ if (dupCheck.rows.length > 0) {
4286
+ warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
2400
4287
  }
2401
- });
2402
-
2403
- // src/lib/tmux-routing.ts
2404
- import { readFileSync as readFileSync9, writeFileSync as writeFileSync3, mkdirSync as mkdirSync4, existsSync as existsSync11, appendFileSync } from "fs";
2405
- import path13 from "path";
2406
- import os6 from "os";
2407
- import { fileURLToPath as fileURLToPath2 } from "url";
2408
- function getParentExe(sessionKey) {
4288
+ if (input.baseDir) {
4289
+ try {
4290
+ await mkdir4(path15.join(input.baseDir, "exe", "output"), { recursive: true });
4291
+ await mkdir4(path15.join(input.baseDir, "exe", "research"), { recursive: true });
4292
+ await ensureArchitectureDoc(input.baseDir, input.projectName);
4293
+ await ensureGitignoreExe(input.baseDir);
4294
+ } catch {
4295
+ }
4296
+ }
4297
+ const complexity = input.complexity ?? "standard";
4298
+ let sessionScope = null;
2409
4299
  try {
2410
- const data = JSON.parse(readFileSync9(path13.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
2411
- return data.parentExe || null;
4300
+ const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
4301
+ sessionScope = resolveExeSession2();
2412
4302
  } catch {
2413
- return null;
2414
4303
  }
4304
+ await client.execute({
4305
+ 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)
4306
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
4307
+ args: [
4308
+ id,
4309
+ input.title,
4310
+ input.assignedTo,
4311
+ input.assignedBy,
4312
+ input.projectName,
4313
+ input.priority,
4314
+ initialStatus,
4315
+ taskFile,
4316
+ blockedById,
4317
+ parentTaskId,
4318
+ input.reviewer ?? null,
4319
+ input.context,
4320
+ complexity,
4321
+ input.budgetTokens ?? null,
4322
+ input.budgetFallbackModel ?? null,
4323
+ 0,
4324
+ null,
4325
+ sessionScope,
4326
+ now,
4327
+ now
4328
+ ]
4329
+ });
4330
+ return {
4331
+ id,
4332
+ title: input.title,
4333
+ assignedTo: input.assignedTo,
4334
+ assignedBy: input.assignedBy,
4335
+ projectName: input.projectName,
4336
+ priority: input.priority,
4337
+ status: initialStatus,
4338
+ taskFile,
4339
+ createdAt: now,
4340
+ updatedAt: now,
4341
+ warning,
4342
+ budgetTokens: input.budgetTokens ?? null,
4343
+ budgetFallbackModel: input.budgetFallbackModel ?? null,
4344
+ tokensUsed: 0,
4345
+ tokensWarnedAt: null
4346
+ };
2415
4347
  }
2416
- function readDebounceState() {
4348
+ async function listTasks(input) {
4349
+ const client = getClient();
4350
+ const conditions = [];
4351
+ const args = [];
4352
+ if (input.assignedTo) {
4353
+ conditions.push("assigned_to = ?");
4354
+ args.push(input.assignedTo);
4355
+ }
4356
+ if (input.status) {
4357
+ conditions.push("status = ?");
4358
+ args.push(input.status);
4359
+ } else {
4360
+ conditions.push("status IN ('open', 'in_progress', 'blocked')");
4361
+ }
4362
+ if (input.projectName) {
4363
+ conditions.push("project_name = ?");
4364
+ args.push(input.projectName);
4365
+ }
4366
+ if (input.priority) {
4367
+ conditions.push("priority = ?");
4368
+ args.push(input.priority);
4369
+ }
2417
4370
  try {
2418
- if (!existsSync11(DEBOUNCE_FILE)) return {};
2419
- return JSON.parse(readFileSync9(DEBOUNCE_FILE, "utf8"));
4371
+ const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
4372
+ const session = resolveExeSession2();
4373
+ if (session) {
4374
+ conditions.push("(session_scope IS NULL OR session_scope = ?)");
4375
+ args.push(session);
4376
+ }
2420
4377
  } catch {
2421
- return {};
2422
4378
  }
4379
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
4380
+ const result = await client.execute({
4381
+ 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`,
4382
+ args
4383
+ });
4384
+ return result.rows.map((r) => ({
4385
+ id: String(r.id),
4386
+ title: String(r.title),
4387
+ assignedTo: String(r.assigned_to),
4388
+ assignedBy: String(r.assigned_by),
4389
+ projectName: String(r.project_name),
4390
+ priority: String(r.priority),
4391
+ status: String(r.status),
4392
+ taskFile: String(r.task_file),
4393
+ createdAt: String(r.created_at),
4394
+ updatedAt: String(r.updated_at),
4395
+ checkpointCount: Number(r.checkpoint_count ?? 0),
4396
+ budgetTokens: r.budget_tokens !== null ? Number(r.budget_tokens) : null,
4397
+ budgetFallbackModel: r.budget_fallback_model !== null ? String(r.budget_fallback_model) : null,
4398
+ tokensUsed: Number(r.tokens_used ?? 0),
4399
+ tokensWarnedAt: r.tokens_warned_at !== null ? Number(r.tokens_warned_at) : null
4400
+ }));
2423
4401
  }
2424
- function writeDebounceState(state) {
4402
+ function checkStaleCompletion(taskContext, taskCreatedAt) {
4403
+ if (!taskContext) return null;
4404
+ if (!DELEGATION_KEYWORDS.test(taskContext)) return null;
2425
4405
  try {
2426
- if (!existsSync11(SESSION_CACHE)) mkdirSync4(SESSION_CACHE, { recursive: true });
2427
- writeFileSync3(DEBOUNCE_FILE, JSON.stringify(state));
4406
+ const since = new Date(taskCreatedAt).toISOString();
4407
+ const branch = execSync6(
4408
+ "git rev-parse --abbrev-ref HEAD 2>/dev/null",
4409
+ { encoding: "utf8", timeout: 3e3 }
4410
+ ).trim();
4411
+ const branchArg = branch && branch !== "HEAD" ? branch : "";
4412
+ const commitCount = execSync6(
4413
+ `git log --oneline --since="${since}" ${branchArg} 2>/dev/null | wc -l`,
4414
+ { encoding: "utf8", timeout: 5e3 }
4415
+ ).trim();
4416
+ const count = parseInt(commitCount, 10);
4417
+ if (count === 0) {
4418
+ return "WARNING: task closed with no new commits since creation. Verify work was actually produced.";
4419
+ }
4420
+ return null;
2428
4421
  } catch {
4422
+ return null;
2429
4423
  }
2430
4424
  }
2431
- function isDebounced(targetSession) {
2432
- const state = readDebounceState();
2433
- const lastSent = state[targetSession] ?? 0;
2434
- return Date.now() - lastSent < INTERCOM_DEBOUNCE_MS;
2435
- }
2436
- function recordDebounce(targetSession) {
2437
- const state = readDebounceState();
2438
- state[targetSession] = Date.now();
2439
- const cutoff = Date.now() - DEBOUNCE_CLEANUP_AGE_MS;
2440
- for (const key of Object.keys(state)) {
2441
- if ((state[key] ?? 0) < cutoff) delete state[key];
4425
+ async function updateTaskStatus(input) {
4426
+ const client = getClient();
4427
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4428
+ const row = await resolveTask(client, input.taskId);
4429
+ const taskId = String(row.id);
4430
+ const taskFile = String(row.task_file);
4431
+ if (input.status === "done" && String(row.assigned_by) === "system" && taskFile.includes("review-")) {
4432
+ process.stderr.write(
4433
+ `[updateTask] Review task "${String(row.title)}" being marked done (assigned to ${String(row.assigned_to)})
4434
+ `
4435
+ );
2442
4436
  }
2443
- writeDebounceState(state);
2444
- }
2445
- function logIntercom(msg) {
2446
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${msg}
2447
- `;
2448
- process.stderr.write(`[intercom] ${msg}
4437
+ if (input.status === "done") {
4438
+ const existingRow = await client.execute({
4439
+ sql: "SELECT context, created_at FROM tasks WHERE id = ?",
4440
+ args: [taskId]
4441
+ });
4442
+ if (existingRow.rows.length > 0) {
4443
+ const ctx = existingRow.rows[0];
4444
+ const warning = checkStaleCompletion(ctx.context, ctx.created_at);
4445
+ if (warning) {
4446
+ input.result = input.result ? `\u26A0\uFE0F ${warning}
4447
+
4448
+ ${input.result}` : `\u26A0\uFE0F ${warning}`;
4449
+ process.stderr.write(`[tasks] ${warning} (task: ${taskId})
2449
4450
  `);
4451
+ }
4452
+ }
4453
+ }
4454
+ if (input.status === "in_progress") {
4455
+ const tmuxSession = process.env.TMUX_PANE ?? process.env.MY_TMUX_SESSION ?? "unknown";
4456
+ const claim = await client.execute({
4457
+ sql: `UPDATE tasks
4458
+ SET status = 'in_progress', assigned_tmux = ?, updated_at = ?
4459
+ WHERE id = ? AND status = 'open'`,
4460
+ args: [tmuxSession, now, taskId]
4461
+ });
4462
+ if (claim.rowsAffected === 0) {
4463
+ const current = await client.execute({
4464
+ sql: "SELECT status, assigned_tmux FROM tasks WHERE id = ?",
4465
+ args: [taskId]
4466
+ });
4467
+ const cur = current.rows[0];
4468
+ const status = cur?.status ?? "unknown";
4469
+ const claimedBy = cur?.assigned_tmux ? ` (claimed by ${cur.assigned_tmux})` : "";
4470
+ throw new Error(`${TASK_ALREADY_CLAIMED_PREFIX}: task ${taskId} is ${status}${claimedBy}`);
4471
+ }
4472
+ try {
4473
+ await writeCheckpoint({
4474
+ taskId,
4475
+ step: "claimed",
4476
+ contextSummary: `Task claimed by session. Transitioning open \u2192 in_progress.`
4477
+ });
4478
+ } catch {
4479
+ }
4480
+ return { row, taskFile, now, taskId };
4481
+ }
4482
+ if (input.result) {
4483
+ await client.execute({
4484
+ sql: "UPDATE tasks SET status = ?, result = ?, updated_at = ? WHERE id = ?",
4485
+ args: [input.status, input.result, now, taskId]
4486
+ });
4487
+ } else {
4488
+ await client.execute({
4489
+ sql: "UPDATE tasks SET status = ?, updated_at = ? WHERE id = ?",
4490
+ args: [input.status, now, taskId]
4491
+ });
4492
+ }
2450
4493
  try {
2451
- appendFileSync(INTERCOM_LOG2, line);
4494
+ await writeCheckpoint({
4495
+ taskId,
4496
+ step: `status_transition:${input.status}`,
4497
+ contextSummary: input.result ? `Transitioned to ${input.status}. Result: ${input.result.slice(0, 500)}` : `Transitioned to ${input.status}.`
4498
+ });
2452
4499
  } catch {
2453
4500
  }
4501
+ return { row, taskFile, now, taskId };
2454
4502
  }
2455
- function getSessionState(sessionName) {
2456
- const transport = getTransport();
2457
- if (!transport.isAlive(sessionName)) return "offline";
4503
+ async function deleteTaskCore(taskId, _baseDir) {
4504
+ const client = getClient();
4505
+ const row = await resolveTask(client, taskId);
4506
+ const id = String(row.id);
4507
+ const taskFile = String(row.task_file);
4508
+ const assignedTo = String(row.assigned_to);
4509
+ const assignedBy = String(row.assigned_by);
4510
+ await client.execute({ sql: "DELETE FROM tasks WHERE id = ?", args: [id] });
4511
+ const taskSlug = taskFile.split("/").pop()?.replace(".md", "") ?? "";
4512
+ return { taskFile, assignedTo, assignedBy, taskSlug };
4513
+ }
4514
+ async function ensureArchitectureDoc(baseDir, projectName) {
4515
+ const archPath = path15.join(baseDir, "exe", "ARCHITECTURE.md");
2458
4516
  try {
2459
- const pane = transport.capturePane(sessionName, 5);
2460
- if (!pane.includes("\u276F") && !pane.includes("Claude Code") && !BUSY_PATTERN.test(pane) && !/Running…/.test(pane)) {
2461
- if (/\$\s*$/.test(pane) || /% $/.test(pane.trimEnd())) {
2462
- return "no_claude";
2463
- }
2464
- }
2465
- if (/Running…/.test(pane)) return "tool";
2466
- if (BUSY_PATTERN.test(pane)) return "thinking";
2467
- return "idle";
4517
+ if (existsSync12(archPath)) return;
4518
+ const template = [
4519
+ `# ${projectName} \u2014 System Architecture`,
4520
+ "",
4521
+ "> Employees: read this before every task. Update it when you change system structure.",
4522
+ `> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
4523
+ "",
4524
+ "## Overview",
4525
+ "",
4526
+ "<!-- Describe what this system does, its main components, and how they connect. -->",
4527
+ "",
4528
+ "## Key Components",
4529
+ "",
4530
+ "<!-- List the major modules, services, or subsystems. -->",
4531
+ "",
4532
+ "## Data Flow",
4533
+ "",
4534
+ "<!-- How does data move through the system? What writes where? -->",
4535
+ "",
4536
+ "## Invariants",
4537
+ "",
4538
+ "<!-- Rules that must never be violated. What breaks if these are wrong? -->",
4539
+ "",
4540
+ "## Dependencies",
4541
+ "",
4542
+ "<!-- What depends on what? If I change X, what else is affected? -->",
4543
+ ""
4544
+ ].join("\n");
4545
+ await writeFile5(archPath, template, "utf-8");
2468
4546
  } catch {
2469
- return "offline";
2470
4547
  }
2471
4548
  }
2472
- function isExeSession(sessionName) {
2473
- return /^exe\d*$/.test(sessionName);
2474
- }
2475
- function sendIntercom(targetSession) {
2476
- const transport = getTransport();
2477
- if (isExeSession(targetSession)) {
2478
- logIntercom(`SKIP_EXE \u2192 ${targetSession} (exe sessions use prompt-submit hook)`);
2479
- return "skipped_exe";
2480
- }
2481
- if (isDebounced(targetSession)) {
2482
- logIntercom(`DEBOUNCE \u2192 ${targetSession} (cross-process file debounce)`);
2483
- return "debounced";
2484
- }
4549
+ async function ensureGitignoreExe(baseDir) {
4550
+ const gitignorePath = path15.join(baseDir, ".gitignore");
2485
4551
  try {
2486
- const sessions = transport.listSessions();
2487
- if (!sessions.includes(targetSession)) {
2488
- logIntercom(`SKIP \u2192 ${targetSession} (session not found)`);
2489
- return "failed";
2490
- }
2491
- const sessionState = getSessionState(targetSession);
2492
- if (sessionState === "no_claude") {
2493
- queueIntercom(targetSession, "claude not running in session");
2494
- recordDebounce(targetSession);
2495
- logIntercom(`QUEUED \u2192 ${targetSession} (no claude process \u2014 raw shell detected)`);
2496
- return "queued";
2497
- }
2498
- if (sessionState === "thinking" || sessionState === "tool") {
2499
- queueIntercom(targetSession, "session busy at send time");
2500
- recordDebounce(targetSession);
2501
- logIntercom(`QUEUED \u2192 ${targetSession} (session busy, will retry from queue)`);
2502
- return "queued";
2503
- }
2504
- if (transport.isPaneInCopyMode(targetSession)) {
2505
- logIntercom(`COPY_MODE \u2192 ${targetSession} (exiting copy mode first)`);
2506
- transport.sendKeys(targetSession, "q");
4552
+ if (existsSync12(gitignorePath)) {
4553
+ const content = readFileSync10(gitignorePath, "utf-8");
4554
+ if (/^\/?exe\/?$/m.test(content)) return;
4555
+ await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
4556
+ } else {
4557
+ await writeFile5(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
2507
4558
  }
2508
- transport.sendKeys(targetSession, "/exe-intercom");
2509
- recordDebounce(targetSession);
2510
- logIntercom(`DELIVERED \u2192 ${targetSession} (fire-and-forget)`);
2511
- return "delivered";
2512
4559
  } catch {
2513
- logIntercom(`FAIL \u2192 ${targetSession}`);
2514
- return "failed";
2515
4560
  }
2516
4561
  }
2517
- var SPAWN_LOCK_DIR, SESSION_CACHE, INTERCOM_DEBOUNCE_MS, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS, BUSY_PATTERN;
2518
- var init_tmux_routing = __esm({
2519
- "src/lib/tmux-routing.ts"() {
4562
+ var DELEGATION_KEYWORDS, TASK_ALREADY_CLAIMED_PREFIX;
4563
+ var init_tasks_crud = __esm({
4564
+ "src/lib/tasks-crud.ts"() {
2520
4565
  "use strict";
2521
- init_session_registry();
2522
- init_session_key();
2523
- init_transport();
2524
- init_cc_agent_support();
2525
- init_mcp_prefix();
2526
- init_provider_table();
2527
- init_intercom_queue();
2528
- init_plan_limits();
2529
- SPAWN_LOCK_DIR = path13.join(os6.homedir(), ".exe-os", "spawn-locks");
2530
- SESSION_CACHE = path13.join(os6.homedir(), ".exe-os", "session-cache");
2531
- INTERCOM_DEBOUNCE_MS = 3e4;
2532
- INTERCOM_LOG2 = path13.join(os6.homedir(), ".exe-os", "intercom.log");
2533
- DEBOUNCE_FILE = path13.join(SESSION_CACHE, "intercom-debounce.json");
2534
- DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
2535
- BUSY_PATTERN = /[✻✽✶✳·].*…|Running…/;
4566
+ init_database();
4567
+ DELEGATION_KEYWORDS = /parallel|delegate|wave|tom\d*-exe/i;
4568
+ TASK_ALREADY_CLAIMED_PREFIX = "TASK_ALREADY_CLAIMED";
2536
4569
  }
2537
4570
  });
2538
4571
 
@@ -2547,8 +4580,8 @@ __export(tasks_review_exports, {
2547
4580
  getReviewChecklist: () => getReviewChecklist,
2548
4581
  listPendingReviews: () => listPendingReviews
2549
4582
  });
2550
- import path14 from "path";
2551
- import { existsSync as existsSync12, readdirSync as readdirSync3, unlinkSync as unlinkSync3 } from "fs";
4583
+ import path16 from "path";
4584
+ import { existsSync as existsSync13, readdirSync as readdirSync3, unlinkSync as unlinkSync5 } from "fs";
2552
4585
  async function countPendingReviews() {
2553
4586
  const client = getClient();
2554
4587
  const result = await client.execute({
@@ -2711,6 +4744,13 @@ async function createReviewForCompletedTask(row, result, _baseDir, now) {
2711
4744
  skipDispatch: true
2712
4745
  });
2713
4746
  const reviewId = reviewTask.id;
4747
+ orgBus.emit({
4748
+ type: "review_created",
4749
+ reviewId,
4750
+ employee: agent,
4751
+ reviewer,
4752
+ timestamp: now
4753
+ });
2714
4754
  await writeNotification({
2715
4755
  agentId: agent,
2716
4756
  agentRole: String(row.assigned_to),
@@ -2786,11 +4826,11 @@ async function cleanupReviewFile(row, taskFile, _baseDir) {
2786
4826
  );
2787
4827
  }
2788
4828
  try {
2789
- const cacheDir = path14.join(EXE_AI_DIR, "session-cache");
2790
- if (existsSync12(cacheDir)) {
4829
+ const cacheDir = path16.join(EXE_AI_DIR, "session-cache");
4830
+ if (existsSync13(cacheDir)) {
2791
4831
  for (const f of readdirSync3(cacheDir)) {
2792
4832
  if (f.startsWith("review-notified-")) {
2793
- unlinkSync3(path14.join(cacheDir, f));
4833
+ unlinkSync5(path16.join(cacheDir, f));
2794
4834
  }
2795
4835
  }
2796
4836
  }
@@ -2807,6 +4847,7 @@ var init_tasks_review = __esm({
2807
4847
  init_tasks_crud();
2808
4848
  init_tmux_routing();
2809
4849
  init_session_key();
4850
+ init_state_bus();
2810
4851
  }
2811
4852
  });
2812
4853
 
@@ -2821,12 +4862,12 @@ __export(worktree_exports, {
2821
4862
  worktreeBranch: () => worktreeBranch,
2822
4863
  worktreePath: () => worktreePath
2823
4864
  });
2824
- import { execSync as execSync6 } from "child_process";
2825
- import { existsSync as existsSync13, readFileSync as readFileSync10, appendFileSync as appendFileSync2, mkdirSync as mkdirSync5, realpathSync } from "fs";
2826
- import path15 from "path";
4865
+ import { execSync as execSync7 } from "child_process";
4866
+ import { existsSync as existsSync14, readFileSync as readFileSync11, appendFileSync as appendFileSync2, mkdirSync as mkdirSync7, realpathSync } from "fs";
4867
+ import path17 from "path";
2827
4868
  function getGitRoot(dir) {
2828
4869
  try {
2829
- const root = execSync6("git rev-parse --show-toplevel", {
4870
+ const root = execSync7("git rev-parse --show-toplevel", {
2830
4871
  cwd: dir,
2831
4872
  encoding: "utf-8",
2832
4873
  timeout: GIT_TIMEOUT_MS,
@@ -2839,18 +4880,18 @@ function getGitRoot(dir) {
2839
4880
  }
2840
4881
  function getMainRepoRoot(dir) {
2841
4882
  try {
2842
- const commonDir = execSync6(
4883
+ const commonDir = execSync7(
2843
4884
  "git rev-parse --path-format=absolute --git-common-dir",
2844
4885
  { cwd: dir, encoding: "utf-8", timeout: GIT_TIMEOUT_MS, stdio: ["pipe", "pipe", "pipe"] }
2845
4886
  ).trim();
2846
- return realpath(path15.dirname(commonDir));
4887
+ return realpath(path17.dirname(commonDir));
2847
4888
  } catch {
2848
4889
  return null;
2849
4890
  }
2850
4891
  }
2851
4892
  function worktreePath(repoRoot, employeeName, instance) {
2852
4893
  const label = instanceLabel(employeeName, instance);
2853
- return path15.join(repoRoot, ".worktrees", label);
4894
+ return path17.join(repoRoot, ".worktrees", label);
2854
4895
  }
2855
4896
  function worktreeBranch(employeeName, instance) {
2856
4897
  return `${instanceLabel(employeeName, instance)}-work`;
@@ -2863,14 +4904,14 @@ function ensureWorktree(projectDir, employeeName, instance) {
2863
4904
  if (!repoRoot) return null;
2864
4905
  const wtPath = worktreePath(repoRoot, employeeName, instance);
2865
4906
  const branch = worktreeBranch(employeeName, instance);
2866
- if (existsSync13(path15.join(wtPath, ".git"))) {
4907
+ if (existsSync14(path17.join(wtPath, ".git"))) {
2867
4908
  return wtPath;
2868
4909
  }
2869
- const worktreesDir = path15.join(repoRoot, ".worktrees");
2870
- mkdirSync5(worktreesDir, { recursive: true });
4910
+ const worktreesDir = path17.join(repoRoot, ".worktrees");
4911
+ mkdirSync7(worktreesDir, { recursive: true });
2871
4912
  ensureGitignoreEntry(repoRoot, "/.worktrees/");
2872
4913
  try {
2873
- execSync6("git worktree prune", {
4914
+ execSync7("git worktree prune", {
2874
4915
  cwd: repoRoot,
2875
4916
  encoding: "utf-8",
2876
4917
  timeout: GIT_TIMEOUT_MS,
@@ -2881,14 +4922,14 @@ function ensureWorktree(projectDir, employeeName, instance) {
2881
4922
  const branchExists = branchExistsLocally(repoRoot, branch);
2882
4923
  try {
2883
4924
  if (branchExists) {
2884
- execSync6(`git worktree add "${wtPath}" "${branch}"`, {
4925
+ execSync7(`git worktree add "${wtPath}" "${branch}"`, {
2885
4926
  cwd: repoRoot,
2886
4927
  encoding: "utf-8",
2887
4928
  timeout: GIT_TIMEOUT_MS,
2888
4929
  stdio: ["pipe", "pipe", "pipe"]
2889
4930
  });
2890
4931
  } else {
2891
- execSync6(`git worktree add "${wtPath}" -b "${branch}" HEAD`, {
4932
+ execSync7(`git worktree add "${wtPath}" -b "${branch}" HEAD`, {
2892
4933
  cwd: repoRoot,
2893
4934
  encoding: "utf-8",
2894
4935
  timeout: GIT_TIMEOUT_MS,
@@ -2906,7 +4947,7 @@ function ensureWorktree(projectDir, employeeName, instance) {
2906
4947
  }
2907
4948
  function isWorktreeDirty(wtPath) {
2908
4949
  try {
2909
- const status = execSync6("git status --porcelain", {
4950
+ const status = execSync7("git status --porcelain", {
2910
4951
  cwd: wtPath,
2911
4952
  encoding: "utf-8",
2912
4953
  timeout: GIT_TIMEOUT_MS,
@@ -2922,7 +4963,7 @@ function cleanupWorktree(projectDir, employeeName, instance) {
2922
4963
  if (!repoRoot) return { cleaned: false, reason: "not a git repo" };
2923
4964
  const wtPath = worktreePath(repoRoot, employeeName, instance);
2924
4965
  const branch = worktreeBranch(employeeName, instance);
2925
- if (!existsSync13(wtPath)) {
4966
+ if (!existsSync14(wtPath)) {
2926
4967
  return { cleaned: false, reason: "worktree does not exist" };
2927
4968
  }
2928
4969
  if (isWorktreeDirty(wtPath)) {
@@ -2936,7 +4977,7 @@ function cleanupWorktree(projectDir, employeeName, instance) {
2936
4977
  return { cleaned: false, reason: `branch ${branch} not merged into ${mainBranch}` };
2937
4978
  }
2938
4979
  try {
2939
- execSync6(`git worktree remove "${wtPath}"`, {
4980
+ execSync7(`git worktree remove "${wtPath}"`, {
2940
4981
  cwd: repoRoot,
2941
4982
  encoding: "utf-8",
2942
4983
  timeout: GIT_TIMEOUT_MS,
@@ -2949,7 +4990,7 @@ function cleanupWorktree(projectDir, employeeName, instance) {
2949
4990
  };
2950
4991
  }
2951
4992
  try {
2952
- execSync6(`git branch -d "${branch}"`, {
4993
+ execSync7(`git branch -d "${branch}"`, {
2953
4994
  cwd: repoRoot,
2954
4995
  encoding: "utf-8",
2955
4996
  timeout: GIT_TIMEOUT_MS,
@@ -2961,7 +5002,7 @@ function cleanupWorktree(projectDir, employeeName, instance) {
2961
5002
  }
2962
5003
  function branchExistsLocally(repoRoot, branch) {
2963
5004
  try {
2964
- execSync6(`git rev-parse --verify "refs/heads/${branch}"`, {
5005
+ execSync7(`git rev-parse --verify "refs/heads/${branch}"`, {
2965
5006
  cwd: repoRoot,
2966
5007
  encoding: "utf-8",
2967
5008
  timeout: GIT_TIMEOUT_MS,
@@ -2980,7 +5021,7 @@ function detectMainBranch(repoRoot) {
2980
5021
  }
2981
5022
  function isBranchMerged(repoRoot, branch, into) {
2982
5023
  try {
2983
- const merged = execSync6(`git branch --merged "${into}"`, {
5024
+ const merged = execSync7(`git branch --merged "${into}"`, {
2984
5025
  cwd: repoRoot,
2985
5026
  encoding: "utf-8",
2986
5027
  timeout: GIT_TIMEOUT_MS,
@@ -3000,9 +5041,9 @@ function realpath(p) {
3000
5041
  }
3001
5042
  function ensureGitignoreEntry(repoRoot, entry) {
3002
5043
  try {
3003
- const gitignorePath = path15.join(repoRoot, ".gitignore");
3004
- if (existsSync13(gitignorePath)) {
3005
- const content = readFileSync10(gitignorePath, "utf-8");
5044
+ const gitignorePath = path17.join(repoRoot, ".gitignore");
5045
+ if (existsSync14(gitignorePath)) {
5046
+ const content = readFileSync11(gitignorePath, "utf-8");
3006
5047
  if (content.includes(entry)) return;
3007
5048
  appendFileSync2(gitignorePath, `
3008
5049
  # Agent worktrees (exe-os)
@@ -3022,8 +5063,8 @@ var init_worktree = __esm({
3022
5063
  });
3023
5064
 
3024
5065
  // src/bin/exe-session-cleanup.ts
3025
- import crypto4 from "crypto";
3026
- import { execSync as execSync7 } from "child_process";
5066
+ import crypto7 from "crypto";
5067
+ import { execSync as execSync8 } from "child_process";
3027
5068
 
3028
5069
  // src/lib/store.ts
3029
5070
  init_memory();
@@ -3075,6 +5116,7 @@ async function getMasterKey() {
3075
5116
 
3076
5117
  // src/lib/store.ts
3077
5118
  init_config();
5119
+ init_state_bus();
3078
5120
  var INIT_MAX_RETRIES = 3;
3079
5121
  var INIT_RETRY_DELAY_MS = 1e3;
3080
5122
  function isBusyError2(err) {
@@ -3145,6 +5187,11 @@ async function initStore(options) {
3145
5187
  "version-query"
3146
5188
  );
3147
5189
  _nextVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
5190
+ try {
5191
+ const { loadGlobalProcedures: loadGlobalProcedures2 } = await Promise.resolve().then(() => (init_global_procedures(), global_procedures_exports));
5192
+ await loadGlobalProcedures2();
5193
+ } catch {
5194
+ }
3148
5195
  }
3149
5196
  function classifyTier(record) {
3150
5197
  if (record.tool_name === "commit_to_long_term_memory" && (record.importance ?? 0) >= 8) return 1;
@@ -3186,6 +5233,12 @@ async function writeMemory(record) {
3186
5233
  supersedes_id: record.supersedes_id ?? null
3187
5234
  };
3188
5235
  _pendingRecords.push(dbRow);
5236
+ orgBus.emit({
5237
+ type: "memory_stored",
5238
+ agentId: record.agent_id,
5239
+ project: record.project_name,
5240
+ timestamp: record.timestamp
5241
+ });
3189
5242
  const MAX_PENDING = 1e3;
3190
5243
  if (_pendingRecords.length > MAX_PENDING) {
3191
5244
  const dropped = _pendingRecords.length - MAX_PENDING;
@@ -3395,7 +5448,7 @@ try {
3395
5448
  } catch {
3396
5449
  }
3397
5450
  await writeMemory({
3398
- id: crypto4.randomUUID(),
5451
+ id: crypto7.randomUUID(),
3399
5452
  agent_id: agentName,
3400
5453
  agent_role: "employee",
3401
5454
  session_id: `cleanup-${Date.now()}`,
@@ -3477,7 +5530,7 @@ try {
3477
5530
  const taskList = result.rows.map((r) => `"${String(r.title)}"`).join(", ");
3478
5531
  const msg = `session-ended: ${agentName} session terminated unexpectedly. ${count} task(s) marked blocked: ${taskList}`;
3479
5532
  try {
3480
- execSync7(`tmux send-keys -t ${JSON.stringify(exeSession)} ${JSON.stringify(msg)} Enter`, {
5533
+ execSync8(`tmux send-keys -t ${JSON.stringify(exeSession)} ${JSON.stringify(msg)} Enter`, {
3481
5534
  timeout: 3e3
3482
5535
  });
3483
5536
  } catch {