@askexenow/exe-os 0.9.16 → 0.9.18

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 (97) hide show
  1. package/dist/bin/backfill-conversations.js +1242 -909
  2. package/dist/bin/backfill-responses.js +1245 -912
  3. package/dist/bin/backfill-vectors.js +1244 -906
  4. package/dist/bin/cleanup-stale-review-tasks.js +1870 -417
  5. package/dist/bin/cli.js +217 -107
  6. package/dist/bin/exe-agent-config.js +2 -2
  7. package/dist/bin/exe-agent.js +62 -0
  8. package/dist/bin/exe-assign.js +346 -10
  9. package/dist/bin/exe-boot.js +387 -32
  10. package/dist/bin/exe-call.js +72 -2
  11. package/dist/bin/exe-cloud.js +8 -0
  12. package/dist/bin/exe-dispatch.js +1821 -225
  13. package/dist/bin/exe-doctor.js +720 -52
  14. package/dist/bin/exe-export-behaviors.js +1429 -148
  15. package/dist/bin/exe-forget.js +1408 -34
  16. package/dist/bin/exe-gateway.js +1629 -1295
  17. package/dist/bin/exe-heartbeat.js +1899 -448
  18. package/dist/bin/exe-kill.js +1624 -346
  19. package/dist/bin/exe-launch-agent.js +726 -90
  20. package/dist/bin/exe-link.js +27 -8
  21. package/dist/bin/exe-new-employee.js +75 -9
  22. package/dist/bin/exe-pending-messages.js +2769 -1316
  23. package/dist/bin/exe-pending-notifications.js +2829 -1376
  24. package/dist/bin/exe-pending-reviews.js +2847 -1392
  25. package/dist/bin/exe-rename.js +89 -8
  26. package/dist/bin/exe-review.js +1494 -312
  27. package/dist/bin/exe-search.js +1608 -1300
  28. package/dist/bin/exe-session-cleanup.js +194 -91
  29. package/dist/bin/exe-settings.js +10 -2
  30. package/dist/bin/exe-start-codex.js +769 -120
  31. package/dist/bin/exe-start-opencode.js +763 -108
  32. package/dist/bin/exe-status.js +1887 -434
  33. package/dist/bin/exe-team.js +1782 -324
  34. package/dist/bin/git-sweep.js +408 -33
  35. package/dist/bin/graph-backfill.js +681 -27
  36. package/dist/bin/graph-export.js +1419 -141
  37. package/dist/bin/install.js +4 -8
  38. package/dist/bin/intercom-check.js +8641 -0
  39. package/dist/bin/scan-tasks.js +553 -38
  40. package/dist/bin/setup.js +82 -10
  41. package/dist/bin/shard-migrate.js +682 -28
  42. package/dist/gateway/index.js +1629 -1295
  43. package/dist/hooks/bug-report-worker.js +1136 -183
  44. package/dist/hooks/codex-stop-task-finalizer.js +1060 -107
  45. package/dist/hooks/commit-complete.js +408 -33
  46. package/dist/hooks/error-recall.js +1608 -1300
  47. package/dist/hooks/ingest-worker.js +250 -7966
  48. package/dist/hooks/ingest.js +707 -119
  49. package/dist/hooks/instructions-loaded.js +383 -20
  50. package/dist/hooks/notification.js +383 -20
  51. package/dist/hooks/post-compact.js +384 -21
  52. package/dist/hooks/{response-ingest-worker.js → post-tool-combined.js} +4157 -1716
  53. package/dist/hooks/pre-compact.js +486 -45
  54. package/dist/hooks/pre-tool-use.js +385 -22
  55. package/dist/hooks/prompt-submit.js +291 -96
  56. package/dist/hooks/session-end.js +490 -48
  57. package/dist/hooks/session-start.js +236 -22
  58. package/dist/hooks/stop.js +192 -50
  59. package/dist/hooks/subagent-stop.js +95 -18
  60. package/dist/hooks/summary-worker.js +205 -361
  61. package/dist/index.js +221 -105
  62. package/dist/lib/agent-config.js +2 -2
  63. package/dist/lib/cloud-sync.js +27 -8
  64. package/dist/lib/consolidation.js +437 -41
  65. package/dist/lib/database.js +20 -8
  66. package/dist/lib/db-daemon-client.js +2 -2
  67. package/dist/lib/db.js +20 -8
  68. package/dist/lib/device-registry.js +27 -8
  69. package/dist/lib/employee-templates.js +62 -0
  70. package/dist/lib/employees.js +2 -2
  71. package/dist/lib/exe-daemon.js +6703 -6259
  72. package/dist/lib/hybrid-search.js +1608 -1300
  73. package/dist/lib/identity.js +1 -1
  74. package/dist/lib/messaging.js +11 -3
  75. package/dist/lib/reminders.js +1 -1
  76. package/dist/lib/schedules.js +718 -26
  77. package/dist/lib/session-registry.js +11 -0
  78. package/dist/lib/skill-learning.js +639 -9
  79. package/dist/lib/store.js +676 -27
  80. package/dist/lib/tasks.js +665 -27
  81. package/dist/lib/tmux-routing.js +732 -94
  82. package/dist/lib/token-spend.js +1 -1
  83. package/dist/mcp/server.js +856 -383
  84. package/dist/mcp/tools/complete-reminder.js +1 -1
  85. package/dist/mcp/tools/create-reminder.js +1 -1
  86. package/dist/mcp/tools/create-task.js +616 -46
  87. package/dist/mcp/tools/deactivate-behavior.js +9 -1
  88. package/dist/mcp/tools/list-reminders.js +1 -1
  89. package/dist/mcp/tools/list-tasks.js +10 -2
  90. package/dist/mcp/tools/send-message.js +11 -3
  91. package/dist/mcp/tools/update-task.js +677 -39
  92. package/dist/runtime/index.js +425 -37
  93. package/dist/tui/App.js +365 -34
  94. package/package.json +5 -2
  95. package/src/commands/exe/intercom.md +6 -17
  96. package/dist/bin/wiki-sync.js +0 -2991
  97. package/dist/hooks/prompt-ingest-worker.js +0 -3979
@@ -356,6 +356,21 @@ var init_secure_files = __esm({
356
356
  });
357
357
 
358
358
  // src/lib/config.ts
359
+ var config_exports = {};
360
+ __export(config_exports, {
361
+ CONFIG_MIGRATIONS: () => CONFIG_MIGRATIONS,
362
+ CONFIG_PATH: () => CONFIG_PATH,
363
+ CURRENT_CONFIG_VERSION: () => CURRENT_CONFIG_VERSION,
364
+ DB_PATH: () => DB_PATH,
365
+ EXE_AI_DIR: () => EXE_AI_DIR,
366
+ LEGACY_LANCE_PATH: () => LEGACY_LANCE_PATH,
367
+ MODELS_DIR: () => MODELS_DIR,
368
+ loadConfig: () => loadConfig,
369
+ loadConfigFrom: () => loadConfigFrom,
370
+ loadConfigSync: () => loadConfigSync,
371
+ migrateConfig: () => migrateConfig,
372
+ saveConfig: () => saveConfig
373
+ });
359
374
  import { readFile, writeFile } from "fs/promises";
360
375
  import { readFileSync as readFileSync2, existsSync as existsSync3, renameSync } from "fs";
361
376
  import path2 from "path";
@@ -459,6 +474,46 @@ async function loadConfig() {
459
474
  return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
460
475
  }
461
476
  }
477
+ function loadConfigSync() {
478
+ const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
479
+ const configPath = path2.join(dir, "config.json");
480
+ if (!existsSync3(configPath)) {
481
+ return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
482
+ }
483
+ try {
484
+ const raw = readFileSync2(configPath, "utf-8");
485
+ let parsed = JSON.parse(raw);
486
+ parsed = migrateLegacyConfig(parsed);
487
+ const { config: migratedCfg } = migrateConfig(parsed);
488
+ normalizeScalingRoadmap(migratedCfg);
489
+ normalizeSessionLifecycle(migratedCfg);
490
+ normalizeAutoUpdate(migratedCfg);
491
+ return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db"), ...migratedCfg };
492
+ } catch {
493
+ return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
494
+ }
495
+ }
496
+ async function saveConfig(config) {
497
+ const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
498
+ await ensurePrivateDir(dir);
499
+ const configPath = path2.join(dir, "config.json");
500
+ await writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
501
+ await enforcePrivateFile(configPath);
502
+ }
503
+ async function loadConfigFrom(configPath) {
504
+ const raw = await readFile(configPath, "utf-8");
505
+ try {
506
+ let parsed = JSON.parse(raw);
507
+ parsed = migrateLegacyConfig(parsed);
508
+ const { config: migratedCfg } = migrateConfig(parsed);
509
+ normalizeScalingRoadmap(migratedCfg);
510
+ normalizeSessionLifecycle(migratedCfg);
511
+ normalizeAutoUpdate(migratedCfg);
512
+ return { ...DEFAULT_CONFIG, ...migratedCfg };
513
+ } catch {
514
+ return { ...DEFAULT_CONFIG };
515
+ }
516
+ }
462
517
  var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
463
518
  var init_config = __esm({
464
519
  "src/lib/config.ts"() {
@@ -595,7 +650,7 @@ var init_agent_config = __esm({
595
650
  init_secure_files();
596
651
  AGENT_CONFIG_PATH = path3.join(EXE_AI_DIR, "agent-config.json");
597
652
  DEFAULT_MODELS = {
598
- claude: "claude-opus-4",
653
+ claude: "claude-opus-4.6",
599
654
  codex: RUNTIME_TABLE.codex?.defaultModel ?? "gpt-5.4",
600
655
  opencode: RUNTIME_TABLE.opencode?.defaultModel ?? "anthropic/claude-sonnet-4-6"
601
656
  };
@@ -777,9 +832,9 @@ var MAX_RETRIES2, BASE_DELAY_MS, MAX_JITTER_MS;
777
832
  var init_db_retry = __esm({
778
833
  "src/lib/db-retry.ts"() {
779
834
  "use strict";
780
- MAX_RETRIES2 = 3;
781
- BASE_DELAY_MS = 200;
782
- MAX_JITTER_MS = 300;
835
+ MAX_RETRIES2 = 5;
836
+ BASE_DELAY_MS = 250;
837
+ MAX_JITTER_MS = 400;
783
838
  }
784
839
  });
785
840
 
@@ -1438,6 +1493,15 @@ var init_database_adapter = __esm({
1438
1493
  }
1439
1494
  });
1440
1495
 
1496
+ // src/types/memory.ts
1497
+ var EMBEDDING_DIM;
1498
+ var init_memory = __esm({
1499
+ "src/types/memory.ts"() {
1500
+ "use strict";
1501
+ EMBEDDING_DIM = 1024;
1502
+ }
1503
+ });
1504
+
1441
1505
  // src/lib/daemon-auth.ts
1442
1506
  import crypto from "crypto";
1443
1507
  import path7 from "path";
@@ -1712,6 +1776,9 @@ async function connectEmbedDaemon() {
1712
1776
  }
1713
1777
  return false;
1714
1778
  }
1779
+ function sendRequest(texts, priority) {
1780
+ return sendDaemonRequest({ texts, priority });
1781
+ }
1715
1782
  function sendDaemonRequest(payload, timeoutMs = REQUEST_TIMEOUT_MS) {
1716
1783
  return new Promise((resolve) => {
1717
1784
  if (!_socket || !_connected) {
@@ -1734,10 +1801,150 @@ function sendDaemonRequest(payload, timeoutMs = REQUEST_TIMEOUT_MS) {
1734
1801
  }
1735
1802
  });
1736
1803
  }
1804
+ async function pingDaemon() {
1805
+ if (!_socket || !_connected) return null;
1806
+ const response = await sendDaemonRequest({ type: "health" }, 5e3);
1807
+ if (response.health) {
1808
+ return response.health;
1809
+ }
1810
+ return null;
1811
+ }
1812
+ function killAndRespawnDaemon() {
1813
+ if (!acquireSpawnLock()) {
1814
+ process.stderr.write("[exed-client] Another process is already restarting daemon \u2014 skipping\n");
1815
+ if (_socket) {
1816
+ _socket.destroy();
1817
+ _socket = null;
1818
+ }
1819
+ _connected = false;
1820
+ _buffer = "";
1821
+ return;
1822
+ }
1823
+ try {
1824
+ process.stderr.write("[exed-client] Killing daemon for restart...\n");
1825
+ if (existsSync8(PID_PATH)) {
1826
+ try {
1827
+ const pid = parseInt(readFileSync7(PID_PATH, "utf8").trim(), 10);
1828
+ if (pid > 0) {
1829
+ try {
1830
+ process.kill(pid, "SIGKILL");
1831
+ } catch {
1832
+ }
1833
+ }
1834
+ } catch {
1835
+ }
1836
+ }
1837
+ if (_socket) {
1838
+ _socket.destroy();
1839
+ _socket = null;
1840
+ }
1841
+ _connected = false;
1842
+ _buffer = "";
1843
+ try {
1844
+ unlinkSync2(PID_PATH);
1845
+ } catch {
1846
+ }
1847
+ try {
1848
+ unlinkSync2(SOCKET_PATH);
1849
+ } catch {
1850
+ }
1851
+ spawnDaemon();
1852
+ } finally {
1853
+ releaseSpawnLock();
1854
+ }
1855
+ }
1856
+ function isDaemonTooYoung() {
1857
+ try {
1858
+ const stat = statSync(PID_PATH);
1859
+ return Date.now() - stat.mtimeMs < MIN_DAEMON_AGE_MS;
1860
+ } catch {
1861
+ return false;
1862
+ }
1863
+ }
1864
+ async function retryThenRestart(doRequest, label) {
1865
+ const result = await doRequest();
1866
+ if (!result.error) {
1867
+ _consecutiveFailures = 0;
1868
+ return result;
1869
+ }
1870
+ _consecutiveFailures++;
1871
+ for (let i = 0; i < MAX_RETRIES_BEFORE_RESTART; i++) {
1872
+ const delayMs = RETRY_DELAYS_MS[i] ?? 5e3;
1873
+ process.stderr.write(`[exed-client] ${label} failed (${result.error}), retry ${i + 1}/${MAX_RETRIES_BEFORE_RESTART} in ${delayMs}ms
1874
+ `);
1875
+ await new Promise((r) => setTimeout(r, delayMs));
1876
+ if (!_connected) {
1877
+ if (!await connectToSocket()) continue;
1878
+ }
1879
+ const retry = await doRequest();
1880
+ if (!retry.error) {
1881
+ _consecutiveFailures = 0;
1882
+ return retry;
1883
+ }
1884
+ _consecutiveFailures++;
1885
+ }
1886
+ if (isDaemonTooYoung()) {
1887
+ process.stderr.write(`[exed-client] ${label}: daemon too young (< ${MIN_DAEMON_AGE_MS / 1e3}s) \u2014 skipping restart
1888
+ `);
1889
+ return { error: result.error };
1890
+ }
1891
+ process.stderr.write(`[exed-client] ${label}: ${_consecutiveFailures} consecutive failures \u2014 restarting daemon
1892
+ `);
1893
+ killAndRespawnDaemon();
1894
+ const start = Date.now();
1895
+ let delay2 = 200;
1896
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1897
+ await new Promise((r) => setTimeout(r, delay2));
1898
+ if (await connectToSocket()) break;
1899
+ delay2 = Math.min(delay2 * 2, 3e3);
1900
+ }
1901
+ if (!_connected) return { error: "Daemon restart failed" };
1902
+ const final = await doRequest();
1903
+ if (!final.error) _consecutiveFailures = 0;
1904
+ return final;
1905
+ }
1906
+ async function embedViaClient(text, priority = "high") {
1907
+ if (!_connected && !await connectEmbedDaemon()) return null;
1908
+ _requestCount++;
1909
+ if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
1910
+ const health = await pingDaemon();
1911
+ if (!health && !isDaemonTooYoung()) {
1912
+ process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
1913
+ `);
1914
+ killAndRespawnDaemon();
1915
+ const start = Date.now();
1916
+ let d = 200;
1917
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1918
+ await new Promise((r) => setTimeout(r, d));
1919
+ if (await connectToSocket()) break;
1920
+ d = Math.min(d * 2, 3e3);
1921
+ }
1922
+ if (!_connected) return null;
1923
+ }
1924
+ }
1925
+ const result = await retryThenRestart(
1926
+ () => sendRequest([text], priority),
1927
+ "Embed"
1928
+ );
1929
+ return !result.error && result.vectors?.[0] ? result.vectors[0] : null;
1930
+ }
1931
+ function disconnectClient() {
1932
+ if (_socket) {
1933
+ _socket.destroy();
1934
+ _socket = null;
1935
+ }
1936
+ _connected = false;
1937
+ _buffer = "";
1938
+ for (const [id, entry] of _pending) {
1939
+ clearTimeout(entry.timer);
1940
+ _pending.delete(id);
1941
+ entry.resolve({ error: "Client disconnected" });
1942
+ }
1943
+ }
1737
1944
  function isClientConnected() {
1738
1945
  return _connected;
1739
1946
  }
1740
- var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, DAEMON_TOKEN_ENV, _socket, _connected, _buffer, _pending, MAX_BUFFER;
1947
+ var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, DAEMON_TOKEN_ENV, _socket, _connected, _buffer, _requestCount, _consecutiveFailures, HEALTH_CHECK_INTERVAL, MAX_RETRIES_BEFORE_RESTART, RETRY_DELAYS_MS, MIN_DAEMON_AGE_MS, _pending, MAX_BUFFER;
1741
1948
  var init_exe_daemon_client = __esm({
1742
1949
  "src/lib/exe-daemon-client.ts"() {
1743
1950
  "use strict";
@@ -1753,6 +1960,12 @@ var init_exe_daemon_client = __esm({
1753
1960
  _socket = null;
1754
1961
  _connected = false;
1755
1962
  _buffer = "";
1963
+ _requestCount = 0;
1964
+ _consecutiveFailures = 0;
1965
+ HEALTH_CHECK_INTERVAL = 100;
1966
+ MAX_RETRIES_BEFORE_RESTART = 3;
1967
+ RETRY_DELAYS_MS = [1e3, 3e3, 5e3];
1968
+ MIN_DAEMON_AGE_MS = 3e4;
1756
1969
  _pending = /* @__PURE__ */ new Map();
1757
1970
  MAX_BUFFER = 1e7;
1758
1971
  }
@@ -1860,7 +2073,7 @@ function createDaemonDbClient(fallbackClient) {
1860
2073
  });
1861
2074
  if (response.error) {
1862
2075
  const errMsg = String(response.error);
1863
- if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed") {
2076
+ if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
1864
2077
  process.stderr.write(`[db-daemon] Transport error (${errMsg}), falling back to direct
1865
2078
  `);
1866
2079
  return fallbackClient.execute(stmt);
@@ -1885,7 +2098,7 @@ function createDaemonDbClient(fallbackClient) {
1885
2098
  });
1886
2099
  if (response.error) {
1887
2100
  const errMsg = String(response.error);
1888
- if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed") {
2101
+ if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
1889
2102
  process.stderr.write(`[db-daemon] Batch transport error (${errMsg}), falling back to direct
1890
2103
  `);
1891
2104
  return fallbackClient.batch(stmts, mode);
@@ -2008,7 +2221,7 @@ async function initDatabase(config) {
2008
2221
  });
2009
2222
  }, 3e4);
2010
2223
  _walCheckpointTimer.unref();
2011
- if (process.env.DATABASE_URL) {
2224
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
2012
2225
  _adapterClient = await createPrismaDbAdapter(_resilientClient);
2013
2226
  }
2014
2227
  }
@@ -2019,7 +2232,7 @@ function getClient() {
2019
2232
  if (!_adapterClient) {
2020
2233
  throw new Error("Database client not initialized. Call initDatabase() first.");
2021
2234
  }
2022
- if (process.env.DATABASE_URL) {
2235
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
2023
2236
  return _adapterClient;
2024
2237
  }
2025
2238
  if (process.env.EXE_IS_DAEMON === "1") {
@@ -2031,9 +2244,11 @@ function getClient() {
2031
2244
  return _resilientClient;
2032
2245
  }
2033
2246
  async function initDaemonClient() {
2034
- if (process.env.DATABASE_URL) return;
2247
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") return;
2035
2248
  if (process.env.EXE_IS_DAEMON === "1") return;
2249
+ if (process.env.VITEST) return;
2036
2250
  if (!_resilientClient) return;
2251
+ if (_daemonClient) return;
2037
2252
  try {
2038
2253
  const { initDaemonDbClient: initDaemonDbClient2 } = await Promise.resolve().then(() => (init_db_daemon_client(), db_daemon_client_exports));
2039
2254
  _daemonClient = await initDaemonDbClient2(_resilientClient);
@@ -2182,6 +2397,13 @@ async function ensureSchema() {
2182
2397
  });
2183
2398
  } catch {
2184
2399
  }
2400
+ try {
2401
+ await client.execute({
2402
+ sql: `ALTER TABLE behaviors ADD COLUMN vector F32_BLOB(${EMBEDDING_DIM})`,
2403
+ args: []
2404
+ });
2405
+ } catch {
2406
+ }
2185
2407
  try {
2186
2408
  await client.execute({
2187
2409
  sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
@@ -3052,6 +3274,7 @@ var init_database = __esm({
3052
3274
  init_db_retry();
3053
3275
  init_employees();
3054
3276
  init_database_adapter();
3277
+ init_memory();
3055
3278
  _client = null;
3056
3279
  _resilientClient = null;
3057
3280
  _walCheckpointTimer = null;
@@ -3563,15 +3786,20 @@ async function createTaskCore(input) {
3563
3786
  const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
3564
3787
  const resolved = resolveExeSession2();
3565
3788
  if (resolved && input.projectName) {
3566
- const { getSessionProject: getSessionProject2 } = await Promise.resolve().then(() => (init_session_scope(), session_scope_exports));
3567
- const sessionProject = getSessionProject2(resolved);
3568
- if (sessionProject && sessionProject !== input.projectName) {
3569
- scopeMismatchWarning = `session/project mismatch: session "${resolved}" owns "${sessionProject}" but task targets "${input.projectName}". Routed to default scope.`;
3570
- process.stderr.write(`[create_task] ${scopeMismatchWarning}
3571
- `);
3572
- earlySessionScope = null;
3573
- } else {
3789
+ const isCoordinatorSession = !resolved.includes("-");
3790
+ if (isCoordinatorSession) {
3574
3791
  earlySessionScope = resolved;
3792
+ } else {
3793
+ const { getSessionProject: getSessionProject2 } = await Promise.resolve().then(() => (init_session_scope(), session_scope_exports));
3794
+ const sessionProject = getSessionProject2(resolved);
3795
+ if (sessionProject && sessionProject !== input.projectName) {
3796
+ scopeMismatchWarning = `session/project mismatch: session "${resolved}" owns "${sessionProject}" but task targets "${input.projectName}". Routed to default scope.`;
3797
+ process.stderr.write(`[create_task] ${scopeMismatchWarning}
3798
+ `);
3799
+ earlySessionScope = null;
3800
+ } else {
3801
+ earlySessionScope = resolved;
3802
+ }
3575
3803
  }
3576
3804
  } else {
3577
3805
  earlySessionScope = resolved;
@@ -4456,6 +4684,10 @@ async function dispatchTaskToEmployee(input) {
4456
4684
  if (transport.isAlive(sessionName)) {
4457
4685
  const result = sendIntercom(sessionName);
4458
4686
  const dispatched = result === "acknowledged" || result === "debounced" || result === "queued" ? "verified" : result === "delivered" ? "sent_unverified" : "session_dead";
4687
+ process.stderr.write(
4688
+ `[dispatch-audit] intercom \u2192 ${sessionName} | task="${input.title}" [${input.priority}] | result=${dispatched} (sendIntercom=${result})
4689
+ `
4690
+ );
4459
4691
  return { dispatched, session: sessionName, crossProject };
4460
4692
  } else {
4461
4693
  const projectDir = input.projectDir ?? process.cwd();
@@ -4464,11 +4696,15 @@ async function dispatchTaskToEmployee(input) {
4464
4696
  });
4465
4697
  if (result.status === "failed") {
4466
4698
  process.stderr.write(
4467
- `[dispatch] Failed to spawn ${input.assignedTo}: ${result.error}
4699
+ `[dispatch-audit] SPAWN FAILED \u2192 ${input.assignedTo} | task="${input.title}" [${input.priority}] | error=${result.error}
4468
4700
  `
4469
4701
  );
4470
4702
  return { dispatched: "session_missing" };
4471
4703
  }
4704
+ process.stderr.write(
4705
+ `[dispatch-audit] SPAWNED \u2192 ${result.sessionName} | task="${input.title}" [${input.priority}]
4706
+ `
4707
+ );
4472
4708
  return { dispatched: "spawned", session: result.sessionName, crossProject };
4473
4709
  }
4474
4710
  } catch {
@@ -4478,7 +4714,13 @@ async function dispatchTaskToEmployee(input) {
4478
4714
  function notifyTaskDone() {
4479
4715
  try {
4480
4716
  const key = getSessionKey();
4481
- if (key && !process.env.VITEST) notifyParentExe(key);
4717
+ if (key && !process.env.VITEST) {
4718
+ notifyParentExe(key);
4719
+ process.stderr.write(
4720
+ `[dispatch-audit] notifyTaskDone \u2192 parent coordinator (session=${key})
4721
+ `
4722
+ );
4723
+ }
4482
4724
  } catch {
4483
4725
  }
4484
4726
  }
@@ -4499,16 +4741,91 @@ var init_tasks_notify = __esm({
4499
4741
  }
4500
4742
  });
4501
4743
 
4744
+ // src/lib/embedder.ts
4745
+ var embedder_exports = {};
4746
+ __export(embedder_exports, {
4747
+ disposeEmbedder: () => disposeEmbedder,
4748
+ embed: () => embed,
4749
+ embedDirect: () => embedDirect,
4750
+ getEmbedder: () => getEmbedder
4751
+ });
4752
+ async function getEmbedder() {
4753
+ const ok = await connectEmbedDaemon();
4754
+ if (!ok) {
4755
+ throw new Error(
4756
+ "Could not connect to embedding daemon. Ensure the model is installed (run /exe-setup)."
4757
+ );
4758
+ }
4759
+ }
4760
+ async function embed(text) {
4761
+ const priority = process.env.EXE_EMBED_PRIORITY === "low" ? "low" : "high";
4762
+ const vector = await embedViaClient(text, priority);
4763
+ if (!vector) {
4764
+ throw new Error(
4765
+ "Embedding failed: daemon unavailable. Run /exe-setup to verify model installation."
4766
+ );
4767
+ }
4768
+ if (vector.length !== EMBEDDING_DIM) {
4769
+ throw new Error(
4770
+ `Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}. Ensure the correct Jina v5-small Q4_K_M GGUF model is installed.`
4771
+ );
4772
+ }
4773
+ return vector;
4774
+ }
4775
+ async function disposeEmbedder() {
4776
+ disconnectClient();
4777
+ }
4778
+ async function embedDirect(text) {
4779
+ const llamaCpp = await import("node-llama-cpp");
4780
+ const { MODELS_DIR: MODELS_DIR2 } = await Promise.resolve().then(() => (init_config(), config_exports));
4781
+ const { existsSync: existsSync17 } = await import("fs");
4782
+ const path20 = await import("path");
4783
+ const modelPath = path20.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
4784
+ if (!existsSync17(modelPath)) {
4785
+ throw new Error(`Embedding model not found at ${modelPath}. Run '/exe-setup' to download it.`);
4786
+ }
4787
+ const llama = await llamaCpp.getLlama();
4788
+ const model = await llama.loadModel({ modelPath });
4789
+ const context = await model.createEmbeddingContext();
4790
+ try {
4791
+ const embedding = await context.getEmbeddingFor(text);
4792
+ const vector = Array.from(embedding.vector);
4793
+ if (vector.length !== EMBEDDING_DIM) {
4794
+ throw new Error(
4795
+ `Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}.`
4796
+ );
4797
+ }
4798
+ return vector;
4799
+ } finally {
4800
+ await context.dispose();
4801
+ await model.dispose();
4802
+ }
4803
+ }
4804
+ var init_embedder = __esm({
4805
+ "src/lib/embedder.ts"() {
4806
+ "use strict";
4807
+ init_memory();
4808
+ init_exe_daemon_client();
4809
+ }
4810
+ });
4811
+
4502
4812
  // src/lib/behaviors.ts
4503
4813
  import crypto5 from "crypto";
4504
4814
  async function storeBehavior(opts) {
4505
4815
  const client = getClient();
4506
4816
  const id = crypto5.randomUUID();
4507
4817
  const now = (/* @__PURE__ */ new Date()).toISOString();
4818
+ let vector = null;
4819
+ try {
4820
+ const { embed: embed2 } = await Promise.resolve().then(() => (init_embedder(), embedder_exports));
4821
+ const vec = await embed2(opts.content);
4822
+ vector = new Float32Array(vec);
4823
+ } catch {
4824
+ }
4508
4825
  await client.execute({
4509
- sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, priority, content, active, created_at, updated_at)
4510
- VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)`,
4511
- args: [id, opts.agentId, opts.projectName ?? null, opts.domain ?? null, opts.priority ?? "p1", opts.content, now, now]
4826
+ sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, priority, content, active, created_at, updated_at, vector)
4827
+ VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?, ?)`,
4828
+ args: [id, opts.agentId, opts.projectName ?? null, opts.domain ?? null, opts.priority ?? "p1", opts.content, now, now, vector ? vector.buffer : null]
4512
4829
  });
4513
4830
  return id;
4514
4831
  }
@@ -5611,7 +5928,7 @@ function isSessionBusy(sessionName) {
5611
5928
  function isExeSession(sessionName) {
5612
5929
  const matchesBaseWithInstance = (baseName) => sessionName === baseName || sessionName.startsWith(baseName) && /^\d+$/.test(sessionName.slice(baseName.length));
5613
5930
  const coordinatorName = getCoordinatorName();
5614
- return matchesBaseWithInstance(coordinatorName) || matchesBaseWithInstance("exe");
5931
+ return matchesBaseWithInstance(coordinatorName);
5615
5932
  }
5616
5933
  function sendIntercom(targetSession) {
5617
5934
  const transport = getTransport();
@@ -6148,15 +6465,6 @@ var init_task_scope = __esm({
6148
6465
  }
6149
6466
  });
6150
6467
 
6151
- // src/types/memory.ts
6152
- var EMBEDDING_DIM;
6153
- var init_memory = __esm({
6154
- "src/types/memory.ts"() {
6155
- "use strict";
6156
- EMBEDDING_DIM = 1024;
6157
- }
6158
- });
6159
-
6160
6468
  // src/lib/keychain.ts
6161
6469
  import { readFile as readFile4, writeFile as writeFile5, unlink, mkdir as mkdir4, chmod as chmod2 } from "fs/promises";
6162
6470
  import { existsSync as existsSync15 } from "fs";
@@ -6644,6 +6952,68 @@ var init_platform_procedures = __esm({
6644
6952
  domain: "architecture",
6645
6953
  priority: "p0",
6646
6954
  content: "Tasks live in the DB. Intercom (tmux send-keys) is fire-and-forget \u2014 it may fail, get garbled, or arrive mid-work. Never rely on intercom for task delivery. The UserPromptSubmit hook checks the DB for new tasks on every prompt. Your operating procedures step 7 says check for next work. The daemon nudges idle agents as a speedup. If you have no tasks, you found them all."
6955
+ },
6956
+ // --- MCP is the ONLY data interface ---
6957
+ {
6958
+ title: "MCP disconnect \u2014 ask the user, never work around it",
6959
+ domain: "workflow",
6960
+ priority: "p0",
6961
+ content: "If MCP tools are unavailable, disconnected, or returning connection errors: STOP. Tell the user clearly: 'MCP server is disconnected. Please run /mcp to reconnect.' Do NOT attempt workarounds \u2014 no raw Node imports, no direct DB access, no CLI hacks, no daemon socket calls. MCP is the ONLY data interface. Working around it wastes time, hits bundling issues, and bypasses the contract boundary. Ask once, wait, proceed when reconnected."
6962
+ },
6963
+ // --- MCP Tool Catalog (Layer 0 — every agent knows what tools exist) ---
6964
+ {
6965
+ title: "MCP tools \u2014 memory and search",
6966
+ domain: "tool-use",
6967
+ priority: "p1",
6968
+ content: "recall_my_memory: search your own memories (semantic + FTS). ask_team_memory: search a colleague's memories by agent name. store_memory: persist a memory (decisions, summaries, context). commit_memory: high-importance memory that survives consolidation. search_everything: unified search across memories, tasks, entities, conversations. get_session_context: temporal window of memories around a timestamp. consolidate_memories: merge duplicate/related memories into insights. get_memory_cardinality: count memories per agent (health check)."
6969
+ },
6970
+ {
6971
+ title: "MCP tools \u2014 task orchestration",
6972
+ domain: "tool-use",
6973
+ priority: "p1",
6974
+ content: "create_task: dispatch work to an employee (auto-spawns session). The ONLY dispatch path. list_tasks: query tasks by status, assignee, project. get_task: fetch full task details by ID. update_task: change status (in_progress, done, blocked, cancelled) + add result summary. close_task: finalize a reviewed task (COO only). checkpoint_task: save progress state for crash recovery. resume_employee: re-spawn an employee session for an existing task."
6975
+ },
6976
+ {
6977
+ title: "MCP tools \u2014 knowledge graph (GraphRAG)",
6978
+ domain: "tool-use",
6979
+ priority: "p1",
6980
+ content: "query_relationships: find connections between entities in the knowledge graph. get_entity_neighbors: explore an entity's direct connections. get_hot_entities: find most-referenced entities (trending topics). get_graph_stats: graph health \u2014 entity/relationship counts, density. export_graph: export graph data for visualization. merge_entities: deduplicate entities (alias resolution). find_similar_trajectories: match tool-call patterns to past task solutions."
6981
+ },
6982
+ {
6983
+ title: "MCP tools \u2014 identity, behavior, and decisions",
6984
+ domain: "tool-use",
6985
+ priority: "p1",
6986
+ content: "get_identity: read an agent's exe.md (Layer 1 identity). update_identity: write an agent's exe.md. Identity > behavior \u2014 use for permanent rules. store_behavior: record a correction or pattern for an agent (Layer 2 expertise). list_behaviors: view an agent's active behaviors. deactivate_behavior: soft-delete a stale or conflicting behavior. store_decision: record an ADR (architectural decision record). get_decision: retrieve a past decision by query."
6987
+ },
6988
+ {
6989
+ title: "MCP tools \u2014 communication and messaging",
6990
+ domain: "tool-use",
6991
+ priority: "p1",
6992
+ content: "send_message: send supplementary context to another agent (NOT for actionable work \u2014 use create_task). acknowledge_messages: mark messages as read. send_whatsapp: send WhatsApp message via gateway (customer-facing alerts). query_conversations: search ingested conversations across all channels (WhatsApp, email, etc.)."
6993
+ },
6994
+ {
6995
+ title: "MCP tools \u2014 wiki, documents, and content",
6996
+ domain: "tool-use",
6997
+ priority: "p1",
6998
+ content: "create_wiki_page: create a wiki page in exe-wiki. list_wiki_pages: browse wiki pages. get_wiki_page: read a wiki page. update_wiki_page: edit a wiki page. ingest_document: import a file (PDF, MD, etc.) into memory as chunks. list_documents: browse ingested documents by workspace. purge_document: remove a document and its memory chunks. set_document_importance: adjust chunk importance scores. rerank_documents: re-score document relevance for a query."
6999
+ },
7000
+ {
7001
+ title: "MCP tools \u2014 system, operations, and admin",
7002
+ domain: "tool-use",
7003
+ priority: "p1",
7004
+ content: "get_agent_spend: token usage per agent/session (cost tracking). list_agent_sessions: view agent session history. get_session_kills: audit log of killed sessions. get_daemon_health: check exed daemon status. get_auto_wake_status: daemon auto-wake configuration. get_worker_gate: check worker deployment gates. run_memory_audit: health check \u2014 duplicates, null vectors, orphaned rows. run_consolidation: trigger sleep-time memory consolidation. cloud_sync: force a cloud sync cycle. backup_vps: trigger VPS backup."
7005
+ },
7006
+ {
7007
+ title: "MCP tools \u2014 config, licensing, and team",
7008
+ domain: "tool-use",
7009
+ priority: "p1",
7010
+ content: "set_agent_config: view/change per-agent runtime and model settings. list_employees: view the employee roster. add_person: add a person to the CRM contacts roster. list_people: browse CRM contacts. get_person: fetch contact details. get_license_status: check license validity. create_license: generate a new license key (admin). list_licenses: view all issued licenses. activate_license: activate a license on a device."
7011
+ },
7012
+ {
7013
+ title: "MCP tools \u2014 advanced (triggers, skills, orchestration)",
7014
+ domain: "tool-use",
7015
+ priority: "p1",
7016
+ content: "create_trigger: set up a scheduled recurring agent job (cron). list_triggers: view active triggers. load_skill: load a slash-command skill dynamically. apply_starter_pack: import a pre-built behavior + identity pack for a role. export_orchestration: export full org state (tasks, behaviors, identities) as portable JSON. import_orchestration: import org state into a new instance. deploy_client: deploy a customer client instance. query_company_brain: unified RAG query across all company knowledge. create_reminder: set a text reminder (shown in boot brief). list_reminders: view pending reminders. complete_reminder: mark a reminder done. global_procedure: manage Layer 0 procedures (actions: store, list, deactivate). Legacy aliases: store_global_procedure, list_global_procedures, deactivate_global_procedure."
6647
7017
  }
6648
7018
  ];
6649
7019
  PLATFORM_PROCEDURE_TITLES = new Set(
@@ -6793,6 +7163,11 @@ async function initStore(options) {
6793
7163
  encryptionKey: hexKey
6794
7164
  });
6795
7165
  await retryOnBusy2(() => ensureSchema(), "ensureSchema");
7166
+ try {
7167
+ const { initDaemonClient: initDaemonClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
7168
+ await initDaemonClient2();
7169
+ } catch {
7170
+ }
6796
7171
  if (!options?.lightweight) {
6797
7172
  try {
6798
7173
  const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));