@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
@@ -15,6 +15,15 @@ var __export = (target, all) => {
15
15
  __defProp(target, name, { get: all[name], enumerable: true });
16
16
  };
17
17
 
18
+ // src/types/memory.ts
19
+ var EMBEDDING_DIM;
20
+ var init_memory = __esm({
21
+ "src/types/memory.ts"() {
22
+ "use strict";
23
+ EMBEDDING_DIM = 1024;
24
+ }
25
+ });
26
+
18
27
  // src/lib/db-retry.ts
19
28
  function isBusyError(err) {
20
29
  if (err instanceof Error) {
@@ -64,9 +73,9 @@ var MAX_RETRIES, BASE_DELAY_MS, MAX_JITTER_MS;
64
73
  var init_db_retry = __esm({
65
74
  "src/lib/db-retry.ts"() {
66
75
  "use strict";
67
- MAX_RETRIES = 3;
68
- BASE_DELAY_MS = 200;
69
- MAX_JITTER_MS = 300;
76
+ MAX_RETRIES = 5;
77
+ BASE_DELAY_MS = 250;
78
+ MAX_JITTER_MS = 400;
70
79
  }
71
80
  });
72
81
 
@@ -80,12 +89,25 @@ async function ensurePrivateDir(dirPath) {
80
89
  } catch {
81
90
  }
82
91
  }
92
+ function ensurePrivateDirSync(dirPath) {
93
+ mkdirSync(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
94
+ try {
95
+ chmodSync(dirPath, PRIVATE_DIR_MODE);
96
+ } catch {
97
+ }
98
+ }
83
99
  async function enforcePrivateFile(filePath) {
84
100
  try {
85
101
  await chmod(filePath, PRIVATE_FILE_MODE);
86
102
  } catch {
87
103
  }
88
104
  }
105
+ function enforcePrivateFileSync(filePath) {
106
+ try {
107
+ if (existsSync(filePath)) chmodSync(filePath, PRIVATE_FILE_MODE);
108
+ } catch {
109
+ }
110
+ }
89
111
  var PRIVATE_DIR_MODE, PRIVATE_FILE_MODE;
90
112
  var init_secure_files = __esm({
91
113
  "src/lib/secure-files.ts"() {
@@ -902,7 +924,538 @@ var init_database_adapter = __esm({
902
924
  }
903
925
  });
904
926
 
927
+ // src/lib/daemon-auth.ts
928
+ import crypto from "crypto";
929
+ import path4 from "path";
930
+ import { existsSync as existsSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
931
+ function normalizeToken(token) {
932
+ if (!token) return null;
933
+ const trimmed = token.trim();
934
+ return trimmed.length > 0 ? trimmed : null;
935
+ }
936
+ function readDaemonToken() {
937
+ try {
938
+ if (!existsSync4(DAEMON_TOKEN_PATH)) return null;
939
+ return normalizeToken(readFileSync3(DAEMON_TOKEN_PATH, "utf8"));
940
+ } catch {
941
+ return null;
942
+ }
943
+ }
944
+ function ensureDaemonToken(seed) {
945
+ const existing = readDaemonToken();
946
+ if (existing) return existing;
947
+ const token = normalizeToken(seed) ?? crypto.randomBytes(32).toString("hex");
948
+ ensurePrivateDirSync(EXE_AI_DIR);
949
+ writeFileSync2(DAEMON_TOKEN_PATH, `${token}
950
+ `, "utf8");
951
+ enforcePrivateFileSync(DAEMON_TOKEN_PATH);
952
+ return token;
953
+ }
954
+ var DAEMON_TOKEN_PATH;
955
+ var init_daemon_auth = __esm({
956
+ "src/lib/daemon-auth.ts"() {
957
+ "use strict";
958
+ init_config();
959
+ init_secure_files();
960
+ DAEMON_TOKEN_PATH = path4.join(EXE_AI_DIR, "exed.token");
961
+ }
962
+ });
963
+
964
+ // src/lib/exe-daemon-client.ts
965
+ import net from "net";
966
+ import os4 from "os";
967
+ import { spawn } from "child_process";
968
+ import { randomUUID } from "crypto";
969
+ import { existsSync as existsSync5, unlinkSync as unlinkSync2, readFileSync as readFileSync4, openSync, closeSync, statSync } from "fs";
970
+ import path5 from "path";
971
+ import { fileURLToPath } from "url";
972
+ function handleData(chunk) {
973
+ _buffer += chunk.toString();
974
+ if (_buffer.length > MAX_BUFFER) {
975
+ _buffer = "";
976
+ return;
977
+ }
978
+ let newlineIdx;
979
+ while ((newlineIdx = _buffer.indexOf("\n")) !== -1) {
980
+ const line = _buffer.slice(0, newlineIdx).trim();
981
+ _buffer = _buffer.slice(newlineIdx + 1);
982
+ if (!line) continue;
983
+ try {
984
+ const response = JSON.parse(line);
985
+ const id = response.id;
986
+ if (!id) continue;
987
+ const entry = _pending.get(id);
988
+ if (entry) {
989
+ clearTimeout(entry.timer);
990
+ _pending.delete(id);
991
+ entry.resolve(response);
992
+ }
993
+ } catch {
994
+ }
995
+ }
996
+ }
997
+ function cleanupStaleFiles() {
998
+ if (existsSync5(PID_PATH)) {
999
+ try {
1000
+ const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
1001
+ if (pid > 0) {
1002
+ try {
1003
+ process.kill(pid, 0);
1004
+ return;
1005
+ } catch {
1006
+ }
1007
+ }
1008
+ } catch {
1009
+ }
1010
+ try {
1011
+ unlinkSync2(PID_PATH);
1012
+ } catch {
1013
+ }
1014
+ try {
1015
+ unlinkSync2(SOCKET_PATH);
1016
+ } catch {
1017
+ }
1018
+ }
1019
+ }
1020
+ function findPackageRoot() {
1021
+ let dir = path5.dirname(fileURLToPath(import.meta.url));
1022
+ const { root } = path5.parse(dir);
1023
+ while (dir !== root) {
1024
+ if (existsSync5(path5.join(dir, "package.json"))) return dir;
1025
+ dir = path5.dirname(dir);
1026
+ }
1027
+ return null;
1028
+ }
1029
+ function getAvailableMemoryGB() {
1030
+ if (process.platform === "darwin") {
1031
+ try {
1032
+ const { execSync: execSync2 } = __require("child_process");
1033
+ const vmstat = execSync2("vm_stat", { encoding: "utf8" });
1034
+ const pageSize = 16384;
1035
+ const pageSizeMatch = vmstat.match(/page size of (\d+) bytes/);
1036
+ const actualPageSize = pageSizeMatch ? parseInt(pageSizeMatch[1], 10) : pageSize;
1037
+ const free = vmstat.match(/Pages free:\s+(\d+)/);
1038
+ const inactive = vmstat.match(/Pages inactive:\s+(\d+)/);
1039
+ const speculative = vmstat.match(/Pages speculative:\s+(\d+)/);
1040
+ const freePages = free ? parseInt(free[1], 10) : 0;
1041
+ const inactivePages = inactive ? parseInt(inactive[1], 10) : 0;
1042
+ const speculativePages = speculative ? parseInt(speculative[1], 10) : 0;
1043
+ return (freePages + inactivePages + speculativePages) * actualPageSize / (1024 * 1024 * 1024);
1044
+ } catch {
1045
+ return os4.freemem() / (1024 * 1024 * 1024);
1046
+ }
1047
+ }
1048
+ return os4.freemem() / (1024 * 1024 * 1024);
1049
+ }
1050
+ function spawnDaemon() {
1051
+ const freeGB = getAvailableMemoryGB();
1052
+ const totalGB = os4.totalmem() / (1024 * 1024 * 1024);
1053
+ if (totalGB <= 8) {
1054
+ process.stderr.write(
1055
+ `[exed-client] SKIP: ${totalGB.toFixed(0)}GB system \u2014 embedding daemon disabled. Using keyword search only. Minimum 16GB recommended for vector search.
1056
+ `
1057
+ );
1058
+ return;
1059
+ }
1060
+ if (totalGB <= 16 && freeGB < 2) {
1061
+ process.stderr.write(
1062
+ `[exed-client] SKIP: low memory (${freeGB.toFixed(1)}GB available / ${totalGB.toFixed(0)}GB total). Embedding daemon not started \u2014 using keyword search only.
1063
+ `
1064
+ );
1065
+ return;
1066
+ }
1067
+ const pkgRoot = findPackageRoot();
1068
+ if (!pkgRoot) {
1069
+ process.stderr.write("[exed-client] WARN: cannot find package root\n");
1070
+ return;
1071
+ }
1072
+ const daemonPath = path5.join(pkgRoot, "dist", "lib", "exe-daemon.js");
1073
+ if (!existsSync5(daemonPath)) {
1074
+ process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
1075
+ `);
1076
+ return;
1077
+ }
1078
+ const resolvedPath = daemonPath;
1079
+ const daemonToken = ensureDaemonToken(process.env[DAEMON_TOKEN_ENV] ?? null);
1080
+ process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
1081
+ `);
1082
+ const logPath = path5.join(path5.dirname(SOCKET_PATH), "exed.log");
1083
+ let stderrFd = "ignore";
1084
+ try {
1085
+ stderrFd = openSync(logPath, "a");
1086
+ } catch {
1087
+ }
1088
+ const heapCapMB = totalGB <= 8 ? 256 : 512;
1089
+ const nodeArgs = [`--max-old-space-size=${heapCapMB}`, resolvedPath];
1090
+ const child = spawn(process.execPath, nodeArgs, {
1091
+ detached: true,
1092
+ stdio: ["ignore", "ignore", stderrFd],
1093
+ env: {
1094
+ ...process.env,
1095
+ TMUX: void 0,
1096
+ // Daemon is global — must not inherit session scope
1097
+ TMUX_PANE: void 0,
1098
+ // Prevents resolveExeSession() from scoping to one session
1099
+ EXE_DAEMON_SOCK: SOCKET_PATH,
1100
+ EXE_DAEMON_PID: PID_PATH,
1101
+ [DAEMON_TOKEN_ENV]: daemonToken
1102
+ }
1103
+ });
1104
+ child.unref();
1105
+ if (typeof stderrFd === "number") {
1106
+ try {
1107
+ closeSync(stderrFd);
1108
+ } catch {
1109
+ }
1110
+ }
1111
+ }
1112
+ function acquireSpawnLock() {
1113
+ try {
1114
+ const fd = openSync(SPAWN_LOCK_PATH, "wx");
1115
+ closeSync(fd);
1116
+ return true;
1117
+ } catch {
1118
+ try {
1119
+ const stat = statSync(SPAWN_LOCK_PATH);
1120
+ if (Date.now() - stat.mtimeMs > SPAWN_LOCK_STALE_MS) {
1121
+ try {
1122
+ unlinkSync2(SPAWN_LOCK_PATH);
1123
+ } catch {
1124
+ }
1125
+ try {
1126
+ const fd = openSync(SPAWN_LOCK_PATH, "wx");
1127
+ closeSync(fd);
1128
+ return true;
1129
+ } catch {
1130
+ }
1131
+ }
1132
+ } catch {
1133
+ }
1134
+ return false;
1135
+ }
1136
+ }
1137
+ function releaseSpawnLock() {
1138
+ try {
1139
+ unlinkSync2(SPAWN_LOCK_PATH);
1140
+ } catch {
1141
+ }
1142
+ }
1143
+ function connectToSocket() {
1144
+ return new Promise((resolve) => {
1145
+ if (_socket && _connected) {
1146
+ resolve(true);
1147
+ return;
1148
+ }
1149
+ const socket = net.createConnection({ path: SOCKET_PATH });
1150
+ const connectTimeout = setTimeout(() => {
1151
+ socket.destroy();
1152
+ resolve(false);
1153
+ }, 2e3);
1154
+ socket.on("connect", () => {
1155
+ clearTimeout(connectTimeout);
1156
+ _socket = socket;
1157
+ _connected = true;
1158
+ _buffer = "";
1159
+ socket.on("data", handleData);
1160
+ socket.on("close", () => {
1161
+ _connected = false;
1162
+ _socket = null;
1163
+ for (const [id, entry] of _pending) {
1164
+ clearTimeout(entry.timer);
1165
+ _pending.delete(id);
1166
+ entry.resolve({ error: "Connection closed" });
1167
+ }
1168
+ });
1169
+ socket.on("error", () => {
1170
+ _connected = false;
1171
+ _socket = null;
1172
+ });
1173
+ resolve(true);
1174
+ });
1175
+ socket.on("error", () => {
1176
+ clearTimeout(connectTimeout);
1177
+ resolve(false);
1178
+ });
1179
+ });
1180
+ }
1181
+ async function connectEmbedDaemon() {
1182
+ if (_socket && _connected) return true;
1183
+ if (await connectToSocket()) return true;
1184
+ if (acquireSpawnLock()) {
1185
+ try {
1186
+ cleanupStaleFiles();
1187
+ spawnDaemon();
1188
+ } finally {
1189
+ releaseSpawnLock();
1190
+ }
1191
+ }
1192
+ const start = Date.now();
1193
+ let delay2 = 100;
1194
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1195
+ await new Promise((r) => setTimeout(r, delay2));
1196
+ if (await connectToSocket()) return true;
1197
+ delay2 = Math.min(delay2 * 2, 3e3);
1198
+ }
1199
+ return false;
1200
+ }
1201
+ function sendDaemonRequest(payload, timeoutMs = REQUEST_TIMEOUT_MS) {
1202
+ return new Promise((resolve) => {
1203
+ if (!_socket || !_connected) {
1204
+ resolve({ error: "Not connected" });
1205
+ return;
1206
+ }
1207
+ const id = randomUUID();
1208
+ const token = process.env[DAEMON_TOKEN_ENV] ?? readDaemonToken();
1209
+ const timer = setTimeout(() => {
1210
+ _pending.delete(id);
1211
+ resolve({ error: "Request timeout" });
1212
+ }, timeoutMs);
1213
+ _pending.set(id, { resolve, timer });
1214
+ try {
1215
+ _socket.write(JSON.stringify({ id, token, ...payload }) + "\n");
1216
+ } catch {
1217
+ clearTimeout(timer);
1218
+ _pending.delete(id);
1219
+ resolve({ error: "Write failed" });
1220
+ }
1221
+ });
1222
+ }
1223
+ function isClientConnected() {
1224
+ return _connected;
1225
+ }
1226
+ 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;
1227
+ var init_exe_daemon_client = __esm({
1228
+ "src/lib/exe-daemon-client.ts"() {
1229
+ "use strict";
1230
+ init_config();
1231
+ init_daemon_auth();
1232
+ SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path5.join(EXE_AI_DIR, "exed.sock");
1233
+ PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path5.join(EXE_AI_DIR, "exed.pid");
1234
+ SPAWN_LOCK_PATH = path5.join(EXE_AI_DIR, "exed-spawn.lock");
1235
+ SPAWN_LOCK_STALE_MS = 3e4;
1236
+ CONNECT_TIMEOUT_MS = 15e3;
1237
+ REQUEST_TIMEOUT_MS = 3e4;
1238
+ DAEMON_TOKEN_ENV = "EXE_DAEMON_TOKEN";
1239
+ _socket = null;
1240
+ _connected = false;
1241
+ _buffer = "";
1242
+ _pending = /* @__PURE__ */ new Map();
1243
+ MAX_BUFFER = 1e7;
1244
+ }
1245
+ });
1246
+
1247
+ // src/lib/daemon-protocol.ts
1248
+ function serializeValue(v) {
1249
+ if (v === null || v === void 0) return null;
1250
+ if (typeof v === "bigint") return Number(v);
1251
+ if (typeof v === "boolean") return v ? 1 : 0;
1252
+ if (v instanceof Uint8Array) {
1253
+ return { __blob: Buffer.from(v).toString("base64") };
1254
+ }
1255
+ if (ArrayBuffer.isView(v)) {
1256
+ return { __blob: Buffer.from(v.buffer, v.byteOffset, v.byteLength).toString("base64") };
1257
+ }
1258
+ if (v instanceof ArrayBuffer) {
1259
+ return { __blob: Buffer.from(v).toString("base64") };
1260
+ }
1261
+ if (typeof v === "string" || typeof v === "number") return v;
1262
+ return String(v);
1263
+ }
1264
+ function deserializeValue(v) {
1265
+ if (v === null) return null;
1266
+ if (typeof v === "object" && v !== null && "__blob" in v) {
1267
+ const buf = Buffer.from(v.__blob, "base64");
1268
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
1269
+ }
1270
+ return v;
1271
+ }
1272
+ function deserializeResultSet(srs) {
1273
+ const rows = srs.rows.map((obj) => {
1274
+ const values = srs.columns.map(
1275
+ (col) => deserializeValue(obj[col] ?? null)
1276
+ );
1277
+ const row = values;
1278
+ for (let i = 0; i < srs.columns.length; i++) {
1279
+ const col = srs.columns[i];
1280
+ if (col !== void 0) {
1281
+ row[col] = values[i] ?? null;
1282
+ }
1283
+ }
1284
+ Object.defineProperty(row, "length", {
1285
+ value: values.length,
1286
+ enumerable: false
1287
+ });
1288
+ return row;
1289
+ });
1290
+ return {
1291
+ columns: srs.columns,
1292
+ columnTypes: srs.columnTypes ?? [],
1293
+ rows,
1294
+ rowsAffected: srs.rowsAffected,
1295
+ lastInsertRowid: srs.lastInsertRowid != null ? BigInt(srs.lastInsertRowid) : void 0,
1296
+ toJSON: () => ({
1297
+ columns: srs.columns,
1298
+ columnTypes: srs.columnTypes ?? [],
1299
+ rows: srs.rows,
1300
+ rowsAffected: srs.rowsAffected,
1301
+ lastInsertRowid: srs.lastInsertRowid
1302
+ })
1303
+ };
1304
+ }
1305
+ var init_daemon_protocol = __esm({
1306
+ "src/lib/daemon-protocol.ts"() {
1307
+ "use strict";
1308
+ }
1309
+ });
1310
+
1311
+ // src/lib/db-daemon-client.ts
1312
+ var db_daemon_client_exports = {};
1313
+ __export(db_daemon_client_exports, {
1314
+ createDaemonDbClient: () => createDaemonDbClient,
1315
+ initDaemonDbClient: () => initDaemonDbClient
1316
+ });
1317
+ function normalizeStatement2(stmt) {
1318
+ if (typeof stmt === "string") {
1319
+ return { sql: stmt, args: [] };
1320
+ }
1321
+ const sql = stmt.sql;
1322
+ let args = [];
1323
+ if (Array.isArray(stmt.args)) {
1324
+ args = stmt.args.map((v) => serializeValue(v));
1325
+ } else if (stmt.args && typeof stmt.args === "object") {
1326
+ const named = {};
1327
+ for (const [key, val] of Object.entries(stmt.args)) {
1328
+ named[key] = serializeValue(val);
1329
+ }
1330
+ return { sql, args: named };
1331
+ }
1332
+ return { sql, args };
1333
+ }
1334
+ function createDaemonDbClient(fallbackClient) {
1335
+ let _useDaemon = false;
1336
+ const client = {
1337
+ async execute(stmt) {
1338
+ if (!_useDaemon || !isClientConnected()) {
1339
+ return fallbackClient.execute(stmt);
1340
+ }
1341
+ const { sql, args } = normalizeStatement2(stmt);
1342
+ const response = await sendDaemonRequest({
1343
+ type: "db-execute",
1344
+ sql,
1345
+ args
1346
+ });
1347
+ if (response.error) {
1348
+ const errMsg = String(response.error);
1349
+ if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
1350
+ process.stderr.write(`[db-daemon] Transport error (${errMsg}), falling back to direct
1351
+ `);
1352
+ return fallbackClient.execute(stmt);
1353
+ }
1354
+ throw new Error(errMsg);
1355
+ }
1356
+ if (response.db) {
1357
+ return deserializeResultSet(response.db);
1358
+ }
1359
+ process.stderr.write("[db-daemon] Unexpected response shape, falling back to direct\n");
1360
+ return fallbackClient.execute(stmt);
1361
+ },
1362
+ async batch(stmts, mode) {
1363
+ if (!_useDaemon || !isClientConnected()) {
1364
+ return fallbackClient.batch(stmts, mode);
1365
+ }
1366
+ const statements = stmts.map(normalizeStatement2);
1367
+ const response = await sendDaemonRequest({
1368
+ type: "db-batch",
1369
+ statements,
1370
+ mode: mode ?? "deferred"
1371
+ });
1372
+ if (response.error) {
1373
+ const errMsg = String(response.error);
1374
+ if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
1375
+ process.stderr.write(`[db-daemon] Batch transport error (${errMsg}), falling back to direct
1376
+ `);
1377
+ return fallbackClient.batch(stmts, mode);
1378
+ }
1379
+ throw new Error(errMsg);
1380
+ }
1381
+ const batchResults = response["db-batch"];
1382
+ if (batchResults) {
1383
+ return batchResults.map(deserializeResultSet);
1384
+ }
1385
+ process.stderr.write("[db-daemon] Unexpected batch response shape, falling back to direct\n");
1386
+ return fallbackClient.batch(stmts, mode);
1387
+ },
1388
+ // Transaction support — delegate to fallback (transactions need direct connection)
1389
+ async transaction(mode) {
1390
+ return fallbackClient.transaction(mode);
1391
+ },
1392
+ // executeMultiple — delegate to fallback (used only for schema migrations)
1393
+ async executeMultiple(sql) {
1394
+ return fallbackClient.executeMultiple(sql);
1395
+ },
1396
+ // migrate — delegate to fallback
1397
+ async migrate(stmts) {
1398
+ return fallbackClient.migrate(stmts);
1399
+ },
1400
+ // Sync mode — delegate to fallback
1401
+ sync() {
1402
+ return fallbackClient.sync();
1403
+ },
1404
+ close() {
1405
+ _useDaemon = false;
1406
+ },
1407
+ get closed() {
1408
+ return fallbackClient.closed;
1409
+ },
1410
+ get protocol() {
1411
+ return fallbackClient.protocol;
1412
+ }
1413
+ };
1414
+ return {
1415
+ ...client,
1416
+ /** Enable daemon routing (call after confirming daemon is connected) */
1417
+ _enableDaemon() {
1418
+ _useDaemon = true;
1419
+ },
1420
+ /** Check if daemon routing is active */
1421
+ _isDaemonActive() {
1422
+ return _useDaemon && isClientConnected();
1423
+ }
1424
+ };
1425
+ }
1426
+ async function initDaemonDbClient(fallbackClient) {
1427
+ if (process.env.EXE_IS_DAEMON === "1") return null;
1428
+ const connected = await connectEmbedDaemon();
1429
+ if (!connected) {
1430
+ process.stderr.write("[db-daemon] Daemon unavailable \u2014 using direct SQLite\n");
1431
+ return null;
1432
+ }
1433
+ const client = createDaemonDbClient(fallbackClient);
1434
+ client._enableDaemon();
1435
+ process.stderr.write("[db-daemon] DB routing through daemon (single-writer)\n");
1436
+ return client;
1437
+ }
1438
+ var init_db_daemon_client = __esm({
1439
+ "src/lib/db-daemon-client.ts"() {
1440
+ "use strict";
1441
+ init_exe_daemon_client();
1442
+ init_daemon_protocol();
1443
+ }
1444
+ });
1445
+
905
1446
  // src/lib/database.ts
1447
+ var database_exports = {};
1448
+ __export(database_exports, {
1449
+ disposeDatabase: () => disposeDatabase,
1450
+ disposeTurso: () => disposeTurso,
1451
+ ensureSchema: () => ensureSchema,
1452
+ getClient: () => getClient,
1453
+ getRawClient: () => getRawClient,
1454
+ initDaemonClient: () => initDaemonClient,
1455
+ initDatabase: () => initDatabase,
1456
+ initTurso: () => initTurso,
1457
+ isInitialized: () => isInitialized
1458
+ });
906
1459
  import { createClient } from "@libsql/client";
907
1460
  async function initDatabase(config) {
908
1461
  if (_walCheckpointTimer) {
@@ -941,15 +1494,18 @@ async function initDatabase(config) {
941
1494
  });
942
1495
  }, 3e4);
943
1496
  _walCheckpointTimer.unref();
944
- if (process.env.DATABASE_URL) {
1497
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
945
1498
  _adapterClient = await createPrismaDbAdapter(_resilientClient);
946
1499
  }
947
1500
  }
1501
+ function isInitialized() {
1502
+ return _adapterClient !== null || _client !== null;
1503
+ }
948
1504
  function getClient() {
949
1505
  if (!_adapterClient) {
950
1506
  throw new Error("Database client not initialized. Call initDatabase() first.");
951
1507
  }
952
- if (process.env.DATABASE_URL) {
1508
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
953
1509
  return _adapterClient;
954
1510
  }
955
1511
  if (process.env.EXE_IS_DAEMON === "1") {
@@ -960,6 +1516,22 @@ function getClient() {
960
1516
  }
961
1517
  return _resilientClient;
962
1518
  }
1519
+ async function initDaemonClient() {
1520
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") return;
1521
+ if (process.env.EXE_IS_DAEMON === "1") return;
1522
+ if (process.env.VITEST) return;
1523
+ if (!_resilientClient) return;
1524
+ if (_daemonClient) return;
1525
+ try {
1526
+ const { initDaemonDbClient: initDaemonDbClient2 } = await Promise.resolve().then(() => (init_db_daemon_client(), db_daemon_client_exports));
1527
+ _daemonClient = await initDaemonDbClient2(_resilientClient);
1528
+ } catch (err) {
1529
+ process.stderr.write(
1530
+ `[database] Daemon client init failed (non-fatal): ${err instanceof Error ? err.message : String(err)}
1531
+ `
1532
+ );
1533
+ }
1534
+ }
963
1535
  function getRawClient() {
964
1536
  if (!_client) {
965
1537
  throw new Error("Database client not initialized. Call initDatabase() first.");
@@ -1098,6 +1670,13 @@ async function ensureSchema() {
1098
1670
  });
1099
1671
  } catch {
1100
1672
  }
1673
+ try {
1674
+ await client.execute({
1675
+ sql: `ALTER TABLE behaviors ADD COLUMN vector F32_BLOB(${EMBEDDING_DIM})`,
1676
+ args: []
1677
+ });
1678
+ } catch {
1679
+ }
1101
1680
  try {
1102
1681
  await client.execute({
1103
1682
  sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
@@ -1942,19 +2521,40 @@ async function ensureSchema() {
1942
2521
  } catch {
1943
2522
  }
1944
2523
  }
1945
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
2524
+ async function disposeDatabase() {
2525
+ if (_walCheckpointTimer) {
2526
+ clearInterval(_walCheckpointTimer);
2527
+ _walCheckpointTimer = null;
2528
+ }
2529
+ if (_daemonClient) {
2530
+ _daemonClient.close();
2531
+ _daemonClient = null;
2532
+ }
2533
+ if (_adapterClient && _adapterClient !== _resilientClient) {
2534
+ _adapterClient.close();
2535
+ }
2536
+ _adapterClient = null;
2537
+ if (_client) {
2538
+ _client.close();
2539
+ _client = null;
2540
+ _resilientClient = null;
2541
+ }
2542
+ }
2543
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso, disposeTurso;
1946
2544
  var init_database = __esm({
1947
2545
  "src/lib/database.ts"() {
1948
2546
  "use strict";
1949
2547
  init_db_retry();
1950
2548
  init_employees();
1951
2549
  init_database_adapter();
2550
+ init_memory();
1952
2551
  _client = null;
1953
2552
  _resilientClient = null;
1954
2553
  _walCheckpointTimer = null;
1955
2554
  _daemonClient = null;
1956
2555
  _adapterClient = null;
1957
2556
  initTurso = initDatabase;
2557
+ disposeTurso = disposeDatabase;
1958
2558
  }
1959
2559
  });
1960
2560
 
@@ -1972,12 +2572,12 @@ __export(shard_manager_exports, {
1972
2572
  listShards: () => listShards,
1973
2573
  shardExists: () => shardExists
1974
2574
  });
1975
- import path5 from "path";
1976
- import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync } from "fs";
2575
+ import path7 from "path";
2576
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, readdirSync } from "fs";
1977
2577
  import { createClient as createClient2 } from "@libsql/client";
1978
2578
  function initShardManager(encryptionKey) {
1979
2579
  _encryptionKey = encryptionKey;
1980
- if (!existsSync5(SHARDS_DIR)) {
2580
+ if (!existsSync7(SHARDS_DIR)) {
1981
2581
  mkdirSync2(SHARDS_DIR, { recursive: true });
1982
2582
  }
1983
2583
  _shardingEnabled = true;
@@ -2007,7 +2607,7 @@ function getShardClient(projectName) {
2007
2607
  while (_shards.size >= MAX_OPEN_SHARDS) {
2008
2608
  evictLRU();
2009
2609
  }
2010
- const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
2610
+ const dbPath = path7.join(SHARDS_DIR, `${safeName}.db`);
2011
2611
  const client = createClient2({
2012
2612
  url: `file:${dbPath}`,
2013
2613
  encryptionKey: _encryptionKey
@@ -2018,10 +2618,10 @@ function getShardClient(projectName) {
2018
2618
  }
2019
2619
  function shardExists(projectName) {
2020
2620
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
2021
- return existsSync5(path5.join(SHARDS_DIR, `${safeName}.db`));
2621
+ return existsSync7(path7.join(SHARDS_DIR, `${safeName}.db`));
2022
2622
  }
2023
2623
  function listShards() {
2024
- if (!existsSync5(SHARDS_DIR)) return [];
2624
+ if (!existsSync7(SHARDS_DIR)) return [];
2025
2625
  return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
2026
2626
  }
2027
2627
  async function ensureShardSchema(client) {
@@ -2268,7 +2868,7 @@ var init_shard_manager = __esm({
2268
2868
  "src/lib/shard-manager.ts"() {
2269
2869
  "use strict";
2270
2870
  init_config();
2271
- SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
2871
+ SHARDS_DIR = path7.join(EXE_AI_DIR, "shards");
2272
2872
  SHARD_IDLE_MS = 5 * 60 * 1e3;
2273
2873
  MAX_OPEN_SHARDS = 10;
2274
2874
  EVICTION_INTERVAL_MS = 60 * 1e3;
@@ -2388,6 +2988,68 @@ var init_platform_procedures = __esm({
2388
2988
  domain: "architecture",
2389
2989
  priority: "p0",
2390
2990
  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."
2991
+ },
2992
+ // --- MCP is the ONLY data interface ---
2993
+ {
2994
+ title: "MCP disconnect \u2014 ask the user, never work around it",
2995
+ domain: "workflow",
2996
+ priority: "p0",
2997
+ 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."
2998
+ },
2999
+ // --- MCP Tool Catalog (Layer 0 — every agent knows what tools exist) ---
3000
+ {
3001
+ title: "MCP tools \u2014 memory and search",
3002
+ domain: "tool-use",
3003
+ priority: "p1",
3004
+ 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)."
3005
+ },
3006
+ {
3007
+ title: "MCP tools \u2014 task orchestration",
3008
+ domain: "tool-use",
3009
+ priority: "p1",
3010
+ 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."
3011
+ },
3012
+ {
3013
+ title: "MCP tools \u2014 knowledge graph (GraphRAG)",
3014
+ domain: "tool-use",
3015
+ priority: "p1",
3016
+ 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."
3017
+ },
3018
+ {
3019
+ title: "MCP tools \u2014 identity, behavior, and decisions",
3020
+ domain: "tool-use",
3021
+ priority: "p1",
3022
+ 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."
3023
+ },
3024
+ {
3025
+ title: "MCP tools \u2014 communication and messaging",
3026
+ domain: "tool-use",
3027
+ priority: "p1",
3028
+ 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.)."
3029
+ },
3030
+ {
3031
+ title: "MCP tools \u2014 wiki, documents, and content",
3032
+ domain: "tool-use",
3033
+ priority: "p1",
3034
+ 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."
3035
+ },
3036
+ {
3037
+ title: "MCP tools \u2014 system, operations, and admin",
3038
+ domain: "tool-use",
3039
+ priority: "p1",
3040
+ 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."
3041
+ },
3042
+ {
3043
+ title: "MCP tools \u2014 config, licensing, and team",
3044
+ domain: "tool-use",
3045
+ priority: "p1",
3046
+ 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."
3047
+ },
3048
+ {
3049
+ title: "MCP tools \u2014 advanced (triggers, skills, orchestration)",
3050
+ domain: "tool-use",
3051
+ priority: "p1",
3052
+ 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."
2391
3053
  }
2392
3054
  ];
2393
3055
  PLATFORM_PROCEDURE_TITLES = new Set(
@@ -2404,7 +3066,7 @@ __export(global_procedures_exports, {
2404
3066
  loadGlobalProcedures: () => loadGlobalProcedures,
2405
3067
  storeGlobalProcedure: () => storeGlobalProcedure
2406
3068
  });
2407
- import { randomUUID } from "crypto";
3069
+ import { randomUUID as randomUUID2 } from "crypto";
2408
3070
  async function loadGlobalProcedures() {
2409
3071
  const client = getClient();
2410
3072
  const result = await client.execute({
@@ -2433,7 +3095,7 @@ ${sections.join("\n\n")}
2433
3095
  `;
2434
3096
  }
2435
3097
  async function storeGlobalProcedure(input) {
2436
- const id = randomUUID();
3098
+ const id = randomUUID2();
2437
3099
  const now = (/* @__PURE__ */ new Date()).toISOString();
2438
3100
  const client = getClient();
2439
3101
  await client.execute({
@@ -2477,14 +3139,14 @@ __export(worker_gate_exports, {
2477
3139
  tryAcquireBackfillLock: () => tryAcquireBackfillLock,
2478
3140
  tryAcquireWorkerSlot: () => tryAcquireWorkerSlot
2479
3141
  });
2480
- import { readdirSync as readdirSync2, writeFileSync as writeFileSync2, unlinkSync as unlinkSync2, mkdirSync as mkdirSync3, existsSync as existsSync6 } from "fs";
2481
- import path6 from "path";
3142
+ import { readdirSync as readdirSync2, writeFileSync as writeFileSync3, unlinkSync as unlinkSync3, mkdirSync as mkdirSync3, existsSync as existsSync8 } from "fs";
3143
+ import path8 from "path";
2482
3144
  function tryAcquireWorkerSlot() {
2483
3145
  try {
2484
3146
  mkdirSync3(WORKER_PID_DIR, { recursive: true });
2485
3147
  const reservationId = `res-${process.pid}-${Date.now()}`;
2486
- const reservationPath = path6.join(WORKER_PID_DIR, `${reservationId}.pid`);
2487
- writeFileSync2(reservationPath, String(process.pid));
3148
+ const reservationPath = path8.join(WORKER_PID_DIR, `${reservationId}.pid`);
3149
+ writeFileSync3(reservationPath, String(process.pid));
2488
3150
  const files = readdirSync2(WORKER_PID_DIR);
2489
3151
  let alive = 0;
2490
3152
  for (const f of files) {
@@ -2501,20 +3163,20 @@ function tryAcquireWorkerSlot() {
2501
3163
  alive++;
2502
3164
  } catch {
2503
3165
  try {
2504
- unlinkSync2(path6.join(WORKER_PID_DIR, f));
3166
+ unlinkSync3(path8.join(WORKER_PID_DIR, f));
2505
3167
  } catch {
2506
3168
  }
2507
3169
  }
2508
3170
  }
2509
3171
  if (alive > MAX_CONCURRENT_WORKERS) {
2510
3172
  try {
2511
- unlinkSync2(reservationPath);
3173
+ unlinkSync3(reservationPath);
2512
3174
  } catch {
2513
3175
  }
2514
3176
  return false;
2515
3177
  }
2516
3178
  try {
2517
- unlinkSync2(reservationPath);
3179
+ unlinkSync3(reservationPath);
2518
3180
  } catch {
2519
3181
  }
2520
3182
  return true;
@@ -2525,20 +3187,20 @@ function tryAcquireWorkerSlot() {
2525
3187
  function registerWorkerPid(pid) {
2526
3188
  try {
2527
3189
  mkdirSync3(WORKER_PID_DIR, { recursive: true });
2528
- writeFileSync2(path6.join(WORKER_PID_DIR, `worker-${pid}.pid`), String(pid));
3190
+ writeFileSync3(path8.join(WORKER_PID_DIR, `worker-${pid}.pid`), String(pid));
2529
3191
  } catch {
2530
3192
  }
2531
3193
  }
2532
3194
  function cleanupWorkerPid() {
2533
3195
  try {
2534
- unlinkSync2(path6.join(WORKER_PID_DIR, `worker-${process.pid}.pid`));
3196
+ unlinkSync3(path8.join(WORKER_PID_DIR, `worker-${process.pid}.pid`));
2535
3197
  } catch {
2536
3198
  }
2537
3199
  }
2538
3200
  function tryAcquireBackfillLock() {
2539
3201
  try {
2540
3202
  mkdirSync3(WORKER_PID_DIR, { recursive: true });
2541
- if (existsSync6(BACKFILL_LOCK)) {
3203
+ if (existsSync8(BACKFILL_LOCK)) {
2542
3204
  try {
2543
3205
  const pid = parseInt(
2544
3206
  __require("fs").readFileSync(BACKFILL_LOCK, "utf8").trim(),
@@ -2554,7 +3216,7 @@ function tryAcquireBackfillLock() {
2554
3216
  } catch {
2555
3217
  }
2556
3218
  }
2557
- writeFileSync2(BACKFILL_LOCK, String(process.pid));
3219
+ writeFileSync3(BACKFILL_LOCK, String(process.pid));
2558
3220
  return true;
2559
3221
  } catch {
2560
3222
  return true;
@@ -2562,7 +3224,7 @@ function tryAcquireBackfillLock() {
2562
3224
  }
2563
3225
  function releaseBackfillLock() {
2564
3226
  try {
2565
- unlinkSync2(BACKFILL_LOCK);
3227
+ unlinkSync3(BACKFILL_LOCK);
2566
3228
  } catch {
2567
3229
  }
2568
3230
  }
@@ -2571,31 +3233,32 @@ var init_worker_gate = __esm({
2571
3233
  "src/lib/worker-gate.ts"() {
2572
3234
  "use strict";
2573
3235
  init_config();
2574
- WORKER_PID_DIR = path6.join(EXE_AI_DIR, "worker-pids");
3236
+ WORKER_PID_DIR = path8.join(EXE_AI_DIR, "worker-pids");
2575
3237
  MAX_CONCURRENT_WORKERS = 3;
2576
- BACKFILL_LOCK = path6.join(WORKER_PID_DIR, "backfill.lock");
3238
+ BACKFILL_LOCK = path8.join(WORKER_PID_DIR, "backfill.lock");
2577
3239
  }
2578
3240
  });
2579
3241
 
2580
3242
  // src/bin/exe-doctor.ts
2581
- import os5 from "os";
3243
+ import os6 from "os";
2582
3244
 
2583
3245
  // src/lib/store.ts
2584
- import { createHash } from "crypto";
3246
+ init_memory();
2585
3247
  init_database();
3248
+ import { createHash } from "crypto";
2586
3249
 
2587
3250
  // src/lib/keychain.ts
2588
3251
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
2589
- import { existsSync as existsSync4 } from "fs";
2590
- import path4 from "path";
2591
- import os4 from "os";
3252
+ import { existsSync as existsSync6 } from "fs";
3253
+ import path6 from "path";
3254
+ import os5 from "os";
2592
3255
  var SERVICE = "exe-mem";
2593
3256
  var ACCOUNT = "master-key";
2594
3257
  function getKeyDir() {
2595
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
3258
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path6.join(os5.homedir(), ".exe-os");
2596
3259
  }
2597
3260
  function getKeyPath() {
2598
- return path4.join(getKeyDir(), "master.key");
3261
+ return path6.join(getKeyDir(), "master.key");
2599
3262
  }
2600
3263
  async function tryKeytar() {
2601
3264
  try {
@@ -2616,9 +3279,9 @@ async function getMasterKey() {
2616
3279
  }
2617
3280
  }
2618
3281
  const keyPath = getKeyPath();
2619
- if (!existsSync4(keyPath)) {
3282
+ if (!existsSync6(keyPath)) {
2620
3283
  process.stderr.write(
2621
- `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
3284
+ `[keychain] Key not found at ${keyPath} (HOME=${os5.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2622
3285
  `
2623
3286
  );
2624
3287
  return null;
@@ -2747,6 +3410,11 @@ async function initStore(options) {
2747
3410
  encryptionKey: hexKey
2748
3411
  });
2749
3412
  await retryOnBusy2(() => ensureSchema(), "ensureSchema");
3413
+ try {
3414
+ const { initDaemonClient: initDaemonClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
3415
+ await initDaemonClient2();
3416
+ } catch {
3417
+ }
2750
3418
  if (!options?.lightweight) {
2751
3419
  try {
2752
3420
  const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
@@ -2772,13 +3440,13 @@ init_database();
2772
3440
 
2773
3441
  // src/lib/is-main.ts
2774
3442
  import { realpathSync } from "fs";
2775
- import { fileURLToPath } from "url";
3443
+ import { fileURLToPath as fileURLToPath2 } from "url";
2776
3444
  function isMainModule(importMetaUrl) {
2777
3445
  if (process.argv[1] == null) return false;
2778
3446
  if (process.argv[1].includes("mcp/server")) return false;
2779
3447
  try {
2780
3448
  const scriptPath = realpathSync(process.argv[1]);
2781
- const modulePath = realpathSync(fileURLToPath(importMetaUrl));
3449
+ const modulePath = realpathSync(fileURLToPath2(importMetaUrl));
2782
3450
  return scriptPath === modulePath;
2783
3451
  } catch {
2784
3452
  return importMetaUrl === `file://${process.argv[1]}` || importMetaUrl === new URL(process.argv[1], "file://").href;
@@ -2786,10 +3454,10 @@ function isMainModule(importMetaUrl) {
2786
3454
  }
2787
3455
 
2788
3456
  // src/bin/exe-doctor.ts
2789
- import { existsSync as existsSync7, readFileSync as readFileSync3 } from "fs";
2790
- import { spawn } from "child_process";
2791
- import path7 from "path";
2792
- import { randomUUID as randomUUID2 } from "crypto";
3457
+ import { existsSync as existsSync9, readFileSync as readFileSync5 } from "fs";
3458
+ import { spawn as spawn2 } from "child_process";
3459
+ import path9 from "path";
3460
+ import { randomUUID as randomUUID3 } from "crypto";
2793
3461
 
2794
3462
  // src/lib/conflict-detector.ts
2795
3463
  var DEFAULT_MAX_PAIRS = 100;
@@ -3191,7 +3859,7 @@ async function auditOrphanedProjects(client) {
3191
3859
  for (const row of result.rows) {
3192
3860
  const name = row.project_name;
3193
3861
  const count = Number(row.cnt);
3194
- const exists = existsSync7(path7.join(home, name)) || existsSync7(path7.join(home, "..", name)) || existsSync7(path7.join(process.cwd(), "..", name));
3862
+ const exists = existsSync9(path9.join(home, name)) || existsSync9(path9.join(home, "..", name)) || existsSync9(path9.join(process.cwd(), "..", name));
3195
3863
  if (!exists) {
3196
3864
  orphans.push({ project_name: name, count });
3197
3865
  }
@@ -3199,18 +3867,18 @@ async function auditOrphanedProjects(client) {
3199
3867
  return orphans;
3200
3868
  }
3201
3869
  function auditHookHealth() {
3202
- const logPath = path7.join(
3870
+ const logPath = path9.join(
3203
3871
  process.env.HOME ?? process.env.USERPROFILE ?? "",
3204
3872
  ".exe-os",
3205
3873
  "logs",
3206
3874
  "hooks.log"
3207
3875
  );
3208
- if (!existsSync7(logPath)) {
3876
+ if (!existsSync9(logPath)) {
3209
3877
  return { logExists: false, totalLines: 0, errorsLastHour: 0, topPatterns: [] };
3210
3878
  }
3211
3879
  let content;
3212
3880
  try {
3213
- content = readFileSync3(logPath, "utf-8");
3881
+ content = readFileSync5(logPath, "utf-8");
3214
3882
  } catch {
3215
3883
  return { logExists: false, totalLines: 0, errorsLastHour: 0, topPatterns: [] };
3216
3884
  }
@@ -3285,7 +3953,7 @@ function formatReport(report, flags) {
3285
3953
  }
3286
3954
  lines.push("");
3287
3955
  }
3288
- const totalMemGB = os5.totalmem() / (1024 * 1024 * 1024);
3956
+ const totalMemGB = os6.totalmem() / (1024 * 1024 * 1024);
3289
3957
  const isLowMemSystem = totalMemGB <= 8;
3290
3958
  if (isLowMemSystem && report.nullVectors > 0) {
3291
3959
  lines.push(`\u{1F7E2} Null vectors: ${fmtNum(report.nullVectors)} / ${fmtNum(s.total)} (expected \u2014 8GB system, keyword search mode)`);
@@ -3407,9 +4075,9 @@ async function fixNullVectors() {
3407
4075
  }
3408
4076
  }
3409
4077
  const npmRoot = (await import("child_process")).execSync("npm root -g", { encoding: "utf8" }).trim();
3410
- const backfillPath = path7.join(npmRoot, "exe-os", "dist", "bin", "backfill-vectors.js");
4078
+ const backfillPath = path9.join(npmRoot, "exe-os", "dist", "bin", "backfill-vectors.js");
3411
4079
  return new Promise((resolve, reject) => {
3412
- const child = spawn("node", [backfillPath], { stdio: "inherit" });
4080
+ const child = spawn2("node", [backfillPath], { stdio: "inherit" });
3413
4081
  if (child.pid) registerWorkerPid2(child.pid);
3414
4082
  child.on("close", (code) => {
3415
4083
  if (code === 0) resolve();
@@ -3463,7 +4131,7 @@ async function fixBloated(client, bloated, dryRun) {
3463
4131
  tool_name, project_name, has_error, raw_text, vector, version, consolidated)
3464
4132
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, 0, 0)`,
3465
4133
  args: [
3466
- randomUUID2(),
4134
+ randomUUID3(),
3467
4135
  row.agent_id,
3468
4136
  row.agent_role,
3469
4137
  row.session_id,