@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
@@ -357,6 +357,21 @@ var init_secure_files = __esm({
357
357
  });
358
358
 
359
359
  // src/lib/config.ts
360
+ var config_exports = {};
361
+ __export(config_exports, {
362
+ CONFIG_MIGRATIONS: () => CONFIG_MIGRATIONS,
363
+ CONFIG_PATH: () => CONFIG_PATH,
364
+ CURRENT_CONFIG_VERSION: () => CURRENT_CONFIG_VERSION,
365
+ DB_PATH: () => DB_PATH,
366
+ EXE_AI_DIR: () => EXE_AI_DIR,
367
+ LEGACY_LANCE_PATH: () => LEGACY_LANCE_PATH,
368
+ MODELS_DIR: () => MODELS_DIR,
369
+ loadConfig: () => loadConfig,
370
+ loadConfigFrom: () => loadConfigFrom,
371
+ loadConfigSync: () => loadConfigSync,
372
+ migrateConfig: () => migrateConfig,
373
+ saveConfig: () => saveConfig
374
+ });
360
375
  import { readFile, writeFile } from "fs/promises";
361
376
  import { readFileSync as readFileSync2, existsSync as existsSync3, renameSync } from "fs";
362
377
  import path2 from "path";
@@ -460,6 +475,46 @@ async function loadConfig() {
460
475
  return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
461
476
  }
462
477
  }
478
+ function loadConfigSync() {
479
+ const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
480
+ const configPath = path2.join(dir, "config.json");
481
+ if (!existsSync3(configPath)) {
482
+ return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
483
+ }
484
+ try {
485
+ const raw = readFileSync2(configPath, "utf-8");
486
+ let parsed = JSON.parse(raw);
487
+ parsed = migrateLegacyConfig(parsed);
488
+ const { config: migratedCfg } = migrateConfig(parsed);
489
+ normalizeScalingRoadmap(migratedCfg);
490
+ normalizeSessionLifecycle(migratedCfg);
491
+ normalizeAutoUpdate(migratedCfg);
492
+ return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db"), ...migratedCfg };
493
+ } catch {
494
+ return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
495
+ }
496
+ }
497
+ async function saveConfig(config) {
498
+ const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
499
+ await ensurePrivateDir(dir);
500
+ const configPath = path2.join(dir, "config.json");
501
+ await writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
502
+ await enforcePrivateFile(configPath);
503
+ }
504
+ async function loadConfigFrom(configPath) {
505
+ const raw = await readFile(configPath, "utf-8");
506
+ try {
507
+ let parsed = JSON.parse(raw);
508
+ parsed = migrateLegacyConfig(parsed);
509
+ const { config: migratedCfg } = migrateConfig(parsed);
510
+ normalizeScalingRoadmap(migratedCfg);
511
+ normalizeSessionLifecycle(migratedCfg);
512
+ normalizeAutoUpdate(migratedCfg);
513
+ return { ...DEFAULT_CONFIG, ...migratedCfg };
514
+ } catch {
515
+ return { ...DEFAULT_CONFIG };
516
+ }
517
+ }
463
518
  var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
464
519
  var init_config = __esm({
465
520
  "src/lib/config.ts"() {
@@ -596,7 +651,7 @@ var init_agent_config = __esm({
596
651
  init_secure_files();
597
652
  AGENT_CONFIG_PATH = path3.join(EXE_AI_DIR, "agent-config.json");
598
653
  DEFAULT_MODELS = {
599
- claude: "claude-opus-4",
654
+ claude: "claude-opus-4.6",
600
655
  codex: RUNTIME_TABLE.codex?.defaultModel ?? "gpt-5.4",
601
656
  opencode: RUNTIME_TABLE.opencode?.defaultModel ?? "anthropic/claude-sonnet-4-6"
602
657
  };
@@ -778,9 +833,9 @@ var MAX_RETRIES2, BASE_DELAY_MS, MAX_JITTER_MS;
778
833
  var init_db_retry = __esm({
779
834
  "src/lib/db-retry.ts"() {
780
835
  "use strict";
781
- MAX_RETRIES2 = 3;
782
- BASE_DELAY_MS = 200;
783
- MAX_JITTER_MS = 300;
836
+ MAX_RETRIES2 = 5;
837
+ BASE_DELAY_MS = 250;
838
+ MAX_JITTER_MS = 400;
784
839
  }
785
840
  });
786
841
 
@@ -1439,6 +1494,15 @@ var init_database_adapter = __esm({
1439
1494
  }
1440
1495
  });
1441
1496
 
1497
+ // src/types/memory.ts
1498
+ var EMBEDDING_DIM;
1499
+ var init_memory = __esm({
1500
+ "src/types/memory.ts"() {
1501
+ "use strict";
1502
+ EMBEDDING_DIM = 1024;
1503
+ }
1504
+ });
1505
+
1442
1506
  // src/lib/daemon-auth.ts
1443
1507
  import crypto from "crypto";
1444
1508
  import path7 from "path";
@@ -1713,6 +1777,9 @@ async function connectEmbedDaemon() {
1713
1777
  }
1714
1778
  return false;
1715
1779
  }
1780
+ function sendRequest(texts, priority) {
1781
+ return sendDaemonRequest({ texts, priority });
1782
+ }
1716
1783
  function sendDaemonRequest(payload, timeoutMs = REQUEST_TIMEOUT_MS) {
1717
1784
  return new Promise((resolve) => {
1718
1785
  if (!_socket || !_connected) {
@@ -1735,10 +1802,150 @@ function sendDaemonRequest(payload, timeoutMs = REQUEST_TIMEOUT_MS) {
1735
1802
  }
1736
1803
  });
1737
1804
  }
1805
+ async function pingDaemon() {
1806
+ if (!_socket || !_connected) return null;
1807
+ const response = await sendDaemonRequest({ type: "health" }, 5e3);
1808
+ if (response.health) {
1809
+ return response.health;
1810
+ }
1811
+ return null;
1812
+ }
1813
+ function killAndRespawnDaemon() {
1814
+ if (!acquireSpawnLock()) {
1815
+ process.stderr.write("[exed-client] Another process is already restarting daemon \u2014 skipping\n");
1816
+ if (_socket) {
1817
+ _socket.destroy();
1818
+ _socket = null;
1819
+ }
1820
+ _connected = false;
1821
+ _buffer = "";
1822
+ return;
1823
+ }
1824
+ try {
1825
+ process.stderr.write("[exed-client] Killing daemon for restart...\n");
1826
+ if (existsSync8(PID_PATH)) {
1827
+ try {
1828
+ const pid = parseInt(readFileSync7(PID_PATH, "utf8").trim(), 10);
1829
+ if (pid > 0) {
1830
+ try {
1831
+ process.kill(pid, "SIGKILL");
1832
+ } catch {
1833
+ }
1834
+ }
1835
+ } catch {
1836
+ }
1837
+ }
1838
+ if (_socket) {
1839
+ _socket.destroy();
1840
+ _socket = null;
1841
+ }
1842
+ _connected = false;
1843
+ _buffer = "";
1844
+ try {
1845
+ unlinkSync2(PID_PATH);
1846
+ } catch {
1847
+ }
1848
+ try {
1849
+ unlinkSync2(SOCKET_PATH);
1850
+ } catch {
1851
+ }
1852
+ spawnDaemon();
1853
+ } finally {
1854
+ releaseSpawnLock();
1855
+ }
1856
+ }
1857
+ function isDaemonTooYoung() {
1858
+ try {
1859
+ const stat = statSync(PID_PATH);
1860
+ return Date.now() - stat.mtimeMs < MIN_DAEMON_AGE_MS;
1861
+ } catch {
1862
+ return false;
1863
+ }
1864
+ }
1865
+ async function retryThenRestart(doRequest, label) {
1866
+ const result = await doRequest();
1867
+ if (!result.error) {
1868
+ _consecutiveFailures = 0;
1869
+ return result;
1870
+ }
1871
+ _consecutiveFailures++;
1872
+ for (let i = 0; i < MAX_RETRIES_BEFORE_RESTART; i++) {
1873
+ const delayMs = RETRY_DELAYS_MS[i] ?? 5e3;
1874
+ process.stderr.write(`[exed-client] ${label} failed (${result.error}), retry ${i + 1}/${MAX_RETRIES_BEFORE_RESTART} in ${delayMs}ms
1875
+ `);
1876
+ await new Promise((r) => setTimeout(r, delayMs));
1877
+ if (!_connected) {
1878
+ if (!await connectToSocket()) continue;
1879
+ }
1880
+ const retry = await doRequest();
1881
+ if (!retry.error) {
1882
+ _consecutiveFailures = 0;
1883
+ return retry;
1884
+ }
1885
+ _consecutiveFailures++;
1886
+ }
1887
+ if (isDaemonTooYoung()) {
1888
+ process.stderr.write(`[exed-client] ${label}: daemon too young (< ${MIN_DAEMON_AGE_MS / 1e3}s) \u2014 skipping restart
1889
+ `);
1890
+ return { error: result.error };
1891
+ }
1892
+ process.stderr.write(`[exed-client] ${label}: ${_consecutiveFailures} consecutive failures \u2014 restarting daemon
1893
+ `);
1894
+ killAndRespawnDaemon();
1895
+ const start = Date.now();
1896
+ let delay2 = 200;
1897
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1898
+ await new Promise((r) => setTimeout(r, delay2));
1899
+ if (await connectToSocket()) break;
1900
+ delay2 = Math.min(delay2 * 2, 3e3);
1901
+ }
1902
+ if (!_connected) return { error: "Daemon restart failed" };
1903
+ const final = await doRequest();
1904
+ if (!final.error) _consecutiveFailures = 0;
1905
+ return final;
1906
+ }
1907
+ async function embedViaClient(text, priority = "high") {
1908
+ if (!_connected && !await connectEmbedDaemon()) return null;
1909
+ _requestCount++;
1910
+ if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
1911
+ const health = await pingDaemon();
1912
+ if (!health && !isDaemonTooYoung()) {
1913
+ process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
1914
+ `);
1915
+ killAndRespawnDaemon();
1916
+ const start = Date.now();
1917
+ let d = 200;
1918
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1919
+ await new Promise((r) => setTimeout(r, d));
1920
+ if (await connectToSocket()) break;
1921
+ d = Math.min(d * 2, 3e3);
1922
+ }
1923
+ if (!_connected) return null;
1924
+ }
1925
+ }
1926
+ const result = await retryThenRestart(
1927
+ () => sendRequest([text], priority),
1928
+ "Embed"
1929
+ );
1930
+ return !result.error && result.vectors?.[0] ? result.vectors[0] : null;
1931
+ }
1932
+ function disconnectClient() {
1933
+ if (_socket) {
1934
+ _socket.destroy();
1935
+ _socket = null;
1936
+ }
1937
+ _connected = false;
1938
+ _buffer = "";
1939
+ for (const [id, entry] of _pending) {
1940
+ clearTimeout(entry.timer);
1941
+ _pending.delete(id);
1942
+ entry.resolve({ error: "Client disconnected" });
1943
+ }
1944
+ }
1738
1945
  function isClientConnected() {
1739
1946
  return _connected;
1740
1947
  }
1741
- 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;
1948
+ 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;
1742
1949
  var init_exe_daemon_client = __esm({
1743
1950
  "src/lib/exe-daemon-client.ts"() {
1744
1951
  "use strict";
@@ -1754,6 +1961,12 @@ var init_exe_daemon_client = __esm({
1754
1961
  _socket = null;
1755
1962
  _connected = false;
1756
1963
  _buffer = "";
1964
+ _requestCount = 0;
1965
+ _consecutiveFailures = 0;
1966
+ HEALTH_CHECK_INTERVAL = 100;
1967
+ MAX_RETRIES_BEFORE_RESTART = 3;
1968
+ RETRY_DELAYS_MS = [1e3, 3e3, 5e3];
1969
+ MIN_DAEMON_AGE_MS = 3e4;
1757
1970
  _pending = /* @__PURE__ */ new Map();
1758
1971
  MAX_BUFFER = 1e7;
1759
1972
  }
@@ -1861,7 +2074,7 @@ function createDaemonDbClient(fallbackClient) {
1861
2074
  });
1862
2075
  if (response.error) {
1863
2076
  const errMsg = String(response.error);
1864
- if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed") {
2077
+ if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
1865
2078
  process.stderr.write(`[db-daemon] Transport error (${errMsg}), falling back to direct
1866
2079
  `);
1867
2080
  return fallbackClient.execute(stmt);
@@ -1886,7 +2099,7 @@ function createDaemonDbClient(fallbackClient) {
1886
2099
  });
1887
2100
  if (response.error) {
1888
2101
  const errMsg = String(response.error);
1889
- if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed") {
2102
+ if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
1890
2103
  process.stderr.write(`[db-daemon] Batch transport error (${errMsg}), falling back to direct
1891
2104
  `);
1892
2105
  return fallbackClient.batch(stmts, mode);
@@ -2009,7 +2222,7 @@ async function initDatabase(config) {
2009
2222
  });
2010
2223
  }, 3e4);
2011
2224
  _walCheckpointTimer.unref();
2012
- if (process.env.DATABASE_URL) {
2225
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
2013
2226
  _adapterClient = await createPrismaDbAdapter(_resilientClient);
2014
2227
  }
2015
2228
  }
@@ -2020,7 +2233,7 @@ function getClient() {
2020
2233
  if (!_adapterClient) {
2021
2234
  throw new Error("Database client not initialized. Call initDatabase() first.");
2022
2235
  }
2023
- if (process.env.DATABASE_URL) {
2236
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
2024
2237
  return _adapterClient;
2025
2238
  }
2026
2239
  if (process.env.EXE_IS_DAEMON === "1") {
@@ -2032,9 +2245,11 @@ function getClient() {
2032
2245
  return _resilientClient;
2033
2246
  }
2034
2247
  async function initDaemonClient() {
2035
- if (process.env.DATABASE_URL) return;
2248
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") return;
2036
2249
  if (process.env.EXE_IS_DAEMON === "1") return;
2250
+ if (process.env.VITEST) return;
2037
2251
  if (!_resilientClient) return;
2252
+ if (_daemonClient) return;
2038
2253
  try {
2039
2254
  const { initDaemonDbClient: initDaemonDbClient2 } = await Promise.resolve().then(() => (init_db_daemon_client(), db_daemon_client_exports));
2040
2255
  _daemonClient = await initDaemonDbClient2(_resilientClient);
@@ -2183,6 +2398,13 @@ async function ensureSchema() {
2183
2398
  });
2184
2399
  } catch {
2185
2400
  }
2401
+ try {
2402
+ await client.execute({
2403
+ sql: `ALTER TABLE behaviors ADD COLUMN vector F32_BLOB(${EMBEDDING_DIM})`,
2404
+ args: []
2405
+ });
2406
+ } catch {
2407
+ }
2186
2408
  try {
2187
2409
  await client.execute({
2188
2410
  sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
@@ -3053,6 +3275,7 @@ var init_database = __esm({
3053
3275
  init_db_retry();
3054
3276
  init_employees();
3055
3277
  init_database_adapter();
3278
+ init_memory();
3056
3279
  _client = null;
3057
3280
  _resilientClient = null;
3058
3281
  _walCheckpointTimer = null;
@@ -3564,15 +3787,20 @@ async function createTaskCore(input) {
3564
3787
  const { resolveExeSession: resolveExeSession2 } = await Promise.resolve().then(() => (init_tmux_routing(), tmux_routing_exports));
3565
3788
  const resolved = resolveExeSession2();
3566
3789
  if (resolved && input.projectName) {
3567
- const { getSessionProject: getSessionProject2 } = await Promise.resolve().then(() => (init_session_scope(), session_scope_exports));
3568
- const sessionProject = getSessionProject2(resolved);
3569
- if (sessionProject && sessionProject !== input.projectName) {
3570
- scopeMismatchWarning = `session/project mismatch: session "${resolved}" owns "${sessionProject}" but task targets "${input.projectName}". Routed to default scope.`;
3571
- process.stderr.write(`[create_task] ${scopeMismatchWarning}
3572
- `);
3573
- earlySessionScope = null;
3574
- } else {
3790
+ const isCoordinatorSession = !resolved.includes("-");
3791
+ if (isCoordinatorSession) {
3575
3792
  earlySessionScope = resolved;
3793
+ } else {
3794
+ const { getSessionProject: getSessionProject2 } = await Promise.resolve().then(() => (init_session_scope(), session_scope_exports));
3795
+ const sessionProject = getSessionProject2(resolved);
3796
+ if (sessionProject && sessionProject !== input.projectName) {
3797
+ scopeMismatchWarning = `session/project mismatch: session "${resolved}" owns "${sessionProject}" but task targets "${input.projectName}". Routed to default scope.`;
3798
+ process.stderr.write(`[create_task] ${scopeMismatchWarning}
3799
+ `);
3800
+ earlySessionScope = null;
3801
+ } else {
3802
+ earlySessionScope = resolved;
3803
+ }
3576
3804
  }
3577
3805
  } else {
3578
3806
  earlySessionScope = resolved;
@@ -4457,6 +4685,10 @@ async function dispatchTaskToEmployee(input) {
4457
4685
  if (transport.isAlive(sessionName)) {
4458
4686
  const result = sendIntercom(sessionName);
4459
4687
  const dispatched = result === "acknowledged" || result === "debounced" || result === "queued" ? "verified" : result === "delivered" ? "sent_unverified" : "session_dead";
4688
+ process.stderr.write(
4689
+ `[dispatch-audit] intercom \u2192 ${sessionName} | task="${input.title}" [${input.priority}] | result=${dispatched} (sendIntercom=${result})
4690
+ `
4691
+ );
4460
4692
  return { dispatched, session: sessionName, crossProject };
4461
4693
  } else {
4462
4694
  const projectDir = input.projectDir ?? process.cwd();
@@ -4465,11 +4697,15 @@ async function dispatchTaskToEmployee(input) {
4465
4697
  });
4466
4698
  if (result.status === "failed") {
4467
4699
  process.stderr.write(
4468
- `[dispatch] Failed to spawn ${input.assignedTo}: ${result.error}
4700
+ `[dispatch-audit] SPAWN FAILED \u2192 ${input.assignedTo} | task="${input.title}" [${input.priority}] | error=${result.error}
4469
4701
  `
4470
4702
  );
4471
4703
  return { dispatched: "session_missing" };
4472
4704
  }
4705
+ process.stderr.write(
4706
+ `[dispatch-audit] SPAWNED \u2192 ${result.sessionName} | task="${input.title}" [${input.priority}]
4707
+ `
4708
+ );
4473
4709
  return { dispatched: "spawned", session: result.sessionName, crossProject };
4474
4710
  }
4475
4711
  } catch {
@@ -4479,7 +4715,13 @@ async function dispatchTaskToEmployee(input) {
4479
4715
  function notifyTaskDone() {
4480
4716
  try {
4481
4717
  const key = getSessionKey();
4482
- if (key && !process.env.VITEST) notifyParentExe(key);
4718
+ if (key && !process.env.VITEST) {
4719
+ notifyParentExe(key);
4720
+ process.stderr.write(
4721
+ `[dispatch-audit] notifyTaskDone \u2192 parent coordinator (session=${key})
4722
+ `
4723
+ );
4724
+ }
4483
4725
  } catch {
4484
4726
  }
4485
4727
  }
@@ -4500,16 +4742,91 @@ var init_tasks_notify = __esm({
4500
4742
  }
4501
4743
  });
4502
4744
 
4745
+ // src/lib/embedder.ts
4746
+ var embedder_exports = {};
4747
+ __export(embedder_exports, {
4748
+ disposeEmbedder: () => disposeEmbedder,
4749
+ embed: () => embed,
4750
+ embedDirect: () => embedDirect,
4751
+ getEmbedder: () => getEmbedder
4752
+ });
4753
+ async function getEmbedder() {
4754
+ const ok = await connectEmbedDaemon();
4755
+ if (!ok) {
4756
+ throw new Error(
4757
+ "Could not connect to embedding daemon. Ensure the model is installed (run /exe-setup)."
4758
+ );
4759
+ }
4760
+ }
4761
+ async function embed(text) {
4762
+ const priority = process.env.EXE_EMBED_PRIORITY === "low" ? "low" : "high";
4763
+ const vector = await embedViaClient(text, priority);
4764
+ if (!vector) {
4765
+ throw new Error(
4766
+ "Embedding failed: daemon unavailable. Run /exe-setup to verify model installation."
4767
+ );
4768
+ }
4769
+ if (vector.length !== EMBEDDING_DIM) {
4770
+ throw new Error(
4771
+ `Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}. Ensure the correct Jina v5-small Q4_K_M GGUF model is installed.`
4772
+ );
4773
+ }
4774
+ return vector;
4775
+ }
4776
+ async function disposeEmbedder() {
4777
+ disconnectClient();
4778
+ }
4779
+ async function embedDirect(text) {
4780
+ const llamaCpp = await import("node-llama-cpp");
4781
+ const { MODELS_DIR: MODELS_DIR2 } = await Promise.resolve().then(() => (init_config(), config_exports));
4782
+ const { existsSync: existsSync17 } = await import("fs");
4783
+ const path21 = await import("path");
4784
+ const modelPath = path21.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
4785
+ if (!existsSync17(modelPath)) {
4786
+ throw new Error(`Embedding model not found at ${modelPath}. Run '/exe-setup' to download it.`);
4787
+ }
4788
+ const llama = await llamaCpp.getLlama();
4789
+ const model = await llama.loadModel({ modelPath });
4790
+ const context = await model.createEmbeddingContext();
4791
+ try {
4792
+ const embedding = await context.getEmbeddingFor(text);
4793
+ const vector = Array.from(embedding.vector);
4794
+ if (vector.length !== EMBEDDING_DIM) {
4795
+ throw new Error(
4796
+ `Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}.`
4797
+ );
4798
+ }
4799
+ return vector;
4800
+ } finally {
4801
+ await context.dispose();
4802
+ await model.dispose();
4803
+ }
4804
+ }
4805
+ var init_embedder = __esm({
4806
+ "src/lib/embedder.ts"() {
4807
+ "use strict";
4808
+ init_memory();
4809
+ init_exe_daemon_client();
4810
+ }
4811
+ });
4812
+
4503
4813
  // src/lib/behaviors.ts
4504
4814
  import crypto5 from "crypto";
4505
4815
  async function storeBehavior(opts) {
4506
4816
  const client = getClient();
4507
4817
  const id = crypto5.randomUUID();
4508
4818
  const now = (/* @__PURE__ */ new Date()).toISOString();
4819
+ let vector = null;
4820
+ try {
4821
+ const { embed: embed2 } = await Promise.resolve().then(() => (init_embedder(), embedder_exports));
4822
+ const vec = await embed2(opts.content);
4823
+ vector = new Float32Array(vec);
4824
+ } catch {
4825
+ }
4509
4826
  await client.execute({
4510
- sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, priority, content, active, created_at, updated_at)
4511
- VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)`,
4512
- args: [id, opts.agentId, opts.projectName ?? null, opts.domain ?? null, opts.priority ?? "p1", opts.content, now, now]
4827
+ sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, priority, content, active, created_at, updated_at, vector)
4828
+ VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?, ?)`,
4829
+ args: [id, opts.agentId, opts.projectName ?? null, opts.domain ?? null, opts.priority ?? "p1", opts.content, now, now, vector ? vector.buffer : null]
4513
4830
  });
4514
4831
  return id;
4515
4832
  }
@@ -5612,7 +5929,7 @@ function isSessionBusy(sessionName) {
5612
5929
  function isExeSession(sessionName) {
5613
5930
  const matchesBaseWithInstance = (baseName) => sessionName === baseName || sessionName.startsWith(baseName) && /^\d+$/.test(sessionName.slice(baseName.length));
5614
5931
  const coordinatorName = getCoordinatorName();
5615
- return matchesBaseWithInstance(coordinatorName) || matchesBaseWithInstance("exe");
5932
+ return matchesBaseWithInstance(coordinatorName);
5616
5933
  }
5617
5934
  function sendIntercom(targetSession) {
5618
5935
  const transport = getTransport();
@@ -6149,15 +6466,6 @@ var init_task_scope = __esm({
6149
6466
  }
6150
6467
  });
6151
6468
 
6152
- // src/types/memory.ts
6153
- var EMBEDDING_DIM;
6154
- var init_memory = __esm({
6155
- "src/types/memory.ts"() {
6156
- "use strict";
6157
- EMBEDDING_DIM = 1024;
6158
- }
6159
- });
6160
-
6161
6469
  // src/lib/keychain.ts
6162
6470
  import { readFile as readFile4, writeFile as writeFile5, unlink, mkdir as mkdir4, chmod as chmod2 } from "fs/promises";
6163
6471
  import { existsSync as existsSync15 } from "fs";
@@ -6645,6 +6953,68 @@ var init_platform_procedures = __esm({
6645
6953
  domain: "architecture",
6646
6954
  priority: "p0",
6647
6955
  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."
6956
+ },
6957
+ // --- MCP is the ONLY data interface ---
6958
+ {
6959
+ title: "MCP disconnect \u2014 ask the user, never work around it",
6960
+ domain: "workflow",
6961
+ priority: "p0",
6962
+ 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."
6963
+ },
6964
+ // --- MCP Tool Catalog (Layer 0 — every agent knows what tools exist) ---
6965
+ {
6966
+ title: "MCP tools \u2014 memory and search",
6967
+ domain: "tool-use",
6968
+ priority: "p1",
6969
+ 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)."
6970
+ },
6971
+ {
6972
+ title: "MCP tools \u2014 task orchestration",
6973
+ domain: "tool-use",
6974
+ priority: "p1",
6975
+ 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."
6976
+ },
6977
+ {
6978
+ title: "MCP tools \u2014 knowledge graph (GraphRAG)",
6979
+ domain: "tool-use",
6980
+ priority: "p1",
6981
+ 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."
6982
+ },
6983
+ {
6984
+ title: "MCP tools \u2014 identity, behavior, and decisions",
6985
+ domain: "tool-use",
6986
+ priority: "p1",
6987
+ 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."
6988
+ },
6989
+ {
6990
+ title: "MCP tools \u2014 communication and messaging",
6991
+ domain: "tool-use",
6992
+ priority: "p1",
6993
+ 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.)."
6994
+ },
6995
+ {
6996
+ title: "MCP tools \u2014 wiki, documents, and content",
6997
+ domain: "tool-use",
6998
+ priority: "p1",
6999
+ 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."
7000
+ },
7001
+ {
7002
+ title: "MCP tools \u2014 system, operations, and admin",
7003
+ domain: "tool-use",
7004
+ priority: "p1",
7005
+ 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."
7006
+ },
7007
+ {
7008
+ title: "MCP tools \u2014 config, licensing, and team",
7009
+ domain: "tool-use",
7010
+ priority: "p1",
7011
+ 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."
7012
+ },
7013
+ {
7014
+ title: "MCP tools \u2014 advanced (triggers, skills, orchestration)",
7015
+ domain: "tool-use",
7016
+ priority: "p1",
7017
+ 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."
6648
7018
  }
6649
7019
  ];
6650
7020
  PLATFORM_PROCEDURE_TITLES = new Set(
@@ -6794,6 +7164,11 @@ async function initStore(options) {
6794
7164
  encryptionKey: hexKey
6795
7165
  });
6796
7166
  await retryOnBusy2(() => ensureSchema(), "ensureSchema");
7167
+ try {
7168
+ const { initDaemonClient: initDaemonClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
7169
+ await initDaemonClient2();
7170
+ } catch {
7171
+ }
6797
7172
  if (!options?.lightweight) {
6798
7173
  try {
6799
7174
  const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));