@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
@@ -1,6 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  var __defProp = Object.defineProperty;
3
3
  var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
5
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
6
+ }) : x)(function(x) {
7
+ if (typeof require !== "undefined") return require.apply(this, arguments);
8
+ throw Error('Dynamic require of "' + x + '" is not supported');
9
+ });
4
10
  var __esm = (fn, res) => function __init() {
5
11
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
12
  };
@@ -19,12 +25,25 @@ async function ensurePrivateDir(dirPath) {
19
25
  } catch {
20
26
  }
21
27
  }
28
+ function ensurePrivateDirSync(dirPath) {
29
+ mkdirSync(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
30
+ try {
31
+ chmodSync(dirPath, PRIVATE_DIR_MODE);
32
+ } catch {
33
+ }
34
+ }
22
35
  async function enforcePrivateFile(filePath) {
23
36
  try {
24
37
  await chmod(filePath, PRIVATE_FILE_MODE);
25
38
  } catch {
26
39
  }
27
40
  }
41
+ function enforcePrivateFileSync(filePath) {
42
+ try {
43
+ if (existsSync(filePath)) chmodSync(filePath, PRIVATE_FILE_MODE);
44
+ } catch {
45
+ }
46
+ }
28
47
  var PRIVATE_DIR_MODE, PRIVATE_FILE_MODE;
29
48
  var init_secure_files = __esm({
30
49
  "src/lib/secure-files.ts"() {
@@ -317,9 +336,9 @@ var MAX_RETRIES, BASE_DELAY_MS, MAX_JITTER_MS;
317
336
  var init_db_retry = __esm({
318
337
  "src/lib/db-retry.ts"() {
319
338
  "use strict";
320
- MAX_RETRIES = 3;
321
- BASE_DELAY_MS = 200;
322
- MAX_JITTER_MS = 300;
339
+ MAX_RETRIES = 5;
340
+ BASE_DELAY_MS = 250;
341
+ MAX_JITTER_MS = 400;
323
342
  }
324
343
  });
325
344
 
@@ -907,203 +926,984 @@ var init_database_adapter = __esm({
907
926
  }
908
927
  });
909
928
 
910
- // src/lib/database.ts
911
- import { createClient } from "@libsql/client";
912
- async function initDatabase(config) {
913
- if (_walCheckpointTimer) {
914
- clearInterval(_walCheckpointTimer);
915
- _walCheckpointTimer = null;
929
+ // src/types/memory.ts
930
+ var EMBEDDING_DIM;
931
+ var init_memory = __esm({
932
+ "src/types/memory.ts"() {
933
+ "use strict";
934
+ EMBEDDING_DIM = 1024;
916
935
  }
917
- if (_daemonClient) {
918
- _daemonClient.close();
919
- _daemonClient = null;
936
+ });
937
+
938
+ // src/lib/daemon-auth.ts
939
+ import crypto from "crypto";
940
+ import path4 from "path";
941
+ import { existsSync as existsSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
942
+ function normalizeToken(token) {
943
+ if (!token) return null;
944
+ const trimmed = token.trim();
945
+ return trimmed.length > 0 ? trimmed : null;
946
+ }
947
+ function readDaemonToken() {
948
+ try {
949
+ if (!existsSync4(DAEMON_TOKEN_PATH)) return null;
950
+ return normalizeToken(readFileSync3(DAEMON_TOKEN_PATH, "utf8"));
951
+ } catch {
952
+ return null;
920
953
  }
921
- if (_adapterClient && _adapterClient !== _resilientClient) {
922
- _adapterClient.close();
954
+ }
955
+ function ensureDaemonToken(seed) {
956
+ const existing = readDaemonToken();
957
+ if (existing) return existing;
958
+ const token = normalizeToken(seed) ?? crypto.randomBytes(32).toString("hex");
959
+ ensurePrivateDirSync(EXE_AI_DIR);
960
+ writeFileSync2(DAEMON_TOKEN_PATH, `${token}
961
+ `, "utf8");
962
+ enforcePrivateFileSync(DAEMON_TOKEN_PATH);
963
+ return token;
964
+ }
965
+ var DAEMON_TOKEN_PATH;
966
+ var init_daemon_auth = __esm({
967
+ "src/lib/daemon-auth.ts"() {
968
+ "use strict";
969
+ init_config();
970
+ init_secure_files();
971
+ DAEMON_TOKEN_PATH = path4.join(EXE_AI_DIR, "exed.token");
923
972
  }
924
- _adapterClient = null;
925
- if (_client) {
926
- _client.close();
927
- _client = null;
928
- _resilientClient = null;
973
+ });
974
+
975
+ // src/lib/exe-daemon-client.ts
976
+ var exe_daemon_client_exports = {};
977
+ __export(exe_daemon_client_exports, {
978
+ connectEmbedDaemon: () => connectEmbedDaemon,
979
+ disconnectClient: () => disconnectClient,
980
+ embedBatchViaClient: () => embedBatchViaClient,
981
+ embedViaClient: () => embedViaClient,
982
+ isClientConnected: () => isClientConnected,
983
+ pingDaemon: () => pingDaemon,
984
+ sendDaemonRequest: () => sendDaemonRequest,
985
+ sendIngestRequest: () => sendIngestRequest
986
+ });
987
+ import net from "net";
988
+ import os4 from "os";
989
+ import { spawn } from "child_process";
990
+ import { randomUUID } from "crypto";
991
+ import { existsSync as existsSync5, unlinkSync as unlinkSync2, readFileSync as readFileSync4, openSync, closeSync, statSync } from "fs";
992
+ import path5 from "path";
993
+ import { fileURLToPath } from "url";
994
+ function handleData(chunk) {
995
+ _buffer += chunk.toString();
996
+ if (_buffer.length > MAX_BUFFER) {
997
+ _buffer = "";
998
+ return;
929
999
  }
930
- const opts = {
931
- url: `file:${config.dbPath}`
932
- };
933
- if (config.encryptionKey) {
934
- opts.encryptionKey = config.encryptionKey;
1000
+ let newlineIdx;
1001
+ while ((newlineIdx = _buffer.indexOf("\n")) !== -1) {
1002
+ const line = _buffer.slice(0, newlineIdx).trim();
1003
+ _buffer = _buffer.slice(newlineIdx + 1);
1004
+ if (!line) continue;
1005
+ try {
1006
+ const response = JSON.parse(line);
1007
+ const id = response.id;
1008
+ if (!id) continue;
1009
+ const entry = _pending.get(id);
1010
+ if (entry) {
1011
+ clearTimeout(entry.timer);
1012
+ _pending.delete(id);
1013
+ entry.resolve(response);
1014
+ }
1015
+ } catch {
1016
+ }
935
1017
  }
936
- _client = createClient(opts);
937
- _resilientClient = wrapWithRetry(_client);
938
- _adapterClient = _resilientClient;
939
- _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
940
- });
941
- _client.execute("PRAGMA journal_mode = WAL").catch(() => {
942
- });
943
- if (_walCheckpointTimer) clearInterval(_walCheckpointTimer);
944
- _walCheckpointTimer = setInterval(() => {
945
- _client?.execute("PRAGMA wal_checkpoint(PASSIVE)").catch(() => {
946
- });
947
- }, 3e4);
948
- _walCheckpointTimer.unref();
949
- if (process.env.DATABASE_URL) {
950
- _adapterClient = await createPrismaDbAdapter(_resilientClient);
1018
+ }
1019
+ function cleanupStaleFiles() {
1020
+ if (existsSync5(PID_PATH)) {
1021
+ try {
1022
+ const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
1023
+ if (pid > 0) {
1024
+ try {
1025
+ process.kill(pid, 0);
1026
+ return;
1027
+ } catch {
1028
+ }
1029
+ }
1030
+ } catch {
1031
+ }
1032
+ try {
1033
+ unlinkSync2(PID_PATH);
1034
+ } catch {
1035
+ }
1036
+ try {
1037
+ unlinkSync2(SOCKET_PATH);
1038
+ } catch {
1039
+ }
951
1040
  }
952
1041
  }
953
- function getClient() {
954
- if (!_adapterClient) {
955
- throw new Error("Database client not initialized. Call initDatabase() first.");
1042
+ function findPackageRoot() {
1043
+ let dir = path5.dirname(fileURLToPath(import.meta.url));
1044
+ const { root } = path5.parse(dir);
1045
+ while (dir !== root) {
1046
+ if (existsSync5(path5.join(dir, "package.json"))) return dir;
1047
+ dir = path5.dirname(dir);
1048
+ }
1049
+ return null;
1050
+ }
1051
+ function getAvailableMemoryGB() {
1052
+ if (process.platform === "darwin") {
1053
+ try {
1054
+ const { execSync: execSync2 } = __require("child_process");
1055
+ const vmstat = execSync2("vm_stat", { encoding: "utf8" });
1056
+ const pageSize = 16384;
1057
+ const pageSizeMatch = vmstat.match(/page size of (\d+) bytes/);
1058
+ const actualPageSize = pageSizeMatch ? parseInt(pageSizeMatch[1], 10) : pageSize;
1059
+ const free = vmstat.match(/Pages free:\s+(\d+)/);
1060
+ const inactive = vmstat.match(/Pages inactive:\s+(\d+)/);
1061
+ const speculative = vmstat.match(/Pages speculative:\s+(\d+)/);
1062
+ const freePages = free ? parseInt(free[1], 10) : 0;
1063
+ const inactivePages = inactive ? parseInt(inactive[1], 10) : 0;
1064
+ const speculativePages = speculative ? parseInt(speculative[1], 10) : 0;
1065
+ return (freePages + inactivePages + speculativePages) * actualPageSize / (1024 * 1024 * 1024);
1066
+ } catch {
1067
+ return os4.freemem() / (1024 * 1024 * 1024);
1068
+ }
956
1069
  }
957
- if (process.env.DATABASE_URL) {
958
- return _adapterClient;
1070
+ return os4.freemem() / (1024 * 1024 * 1024);
1071
+ }
1072
+ function spawnDaemon() {
1073
+ const freeGB = getAvailableMemoryGB();
1074
+ const totalGB = os4.totalmem() / (1024 * 1024 * 1024);
1075
+ if (totalGB <= 8) {
1076
+ process.stderr.write(
1077
+ `[exed-client] SKIP: ${totalGB.toFixed(0)}GB system \u2014 embedding daemon disabled. Using keyword search only. Minimum 16GB recommended for vector search.
1078
+ `
1079
+ );
1080
+ return;
959
1081
  }
960
- if (process.env.EXE_IS_DAEMON === "1") {
961
- return _resilientClient;
1082
+ if (totalGB <= 16 && freeGB < 2) {
1083
+ process.stderr.write(
1084
+ `[exed-client] SKIP: low memory (${freeGB.toFixed(1)}GB available / ${totalGB.toFixed(0)}GB total). Embedding daemon not started \u2014 using keyword search only.
1085
+ `
1086
+ );
1087
+ return;
962
1088
  }
963
- if (_daemonClient && _daemonClient._isDaemonActive()) {
964
- return _daemonClient;
1089
+ const pkgRoot = findPackageRoot();
1090
+ if (!pkgRoot) {
1091
+ process.stderr.write("[exed-client] WARN: cannot find package root\n");
1092
+ return;
965
1093
  }
966
- return _resilientClient;
967
- }
968
- function getRawClient() {
969
- if (!_client) {
970
- throw new Error("Database client not initialized. Call initDatabase() first.");
1094
+ const daemonPath = path5.join(pkgRoot, "dist", "lib", "exe-daemon.js");
1095
+ if (!existsSync5(daemonPath)) {
1096
+ process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
1097
+ `);
1098
+ return;
971
1099
  }
972
- return _client;
973
- }
974
- async function ensureSchema() {
975
- const client = getRawClient();
976
- await client.execute("PRAGMA journal_mode = WAL");
977
- await client.execute("PRAGMA busy_timeout = 30000");
978
- await client.execute("PRAGMA wal_autocheckpoint = 1000");
1100
+ const resolvedPath = daemonPath;
1101
+ const daemonToken = ensureDaemonToken(process.env[DAEMON_TOKEN_ENV] ?? null);
1102
+ process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
1103
+ `);
1104
+ const logPath = path5.join(path5.dirname(SOCKET_PATH), "exed.log");
1105
+ let stderrFd = "ignore";
979
1106
  try {
980
- await client.execute("PRAGMA libsql_vector_search_ef = 128");
1107
+ stderrFd = openSync(logPath, "a");
981
1108
  } catch {
982
1109
  }
983
- await client.executeMultiple(`
984
- CREATE TABLE IF NOT EXISTS memories (
985
- id TEXT PRIMARY KEY,
986
- agent_id TEXT NOT NULL,
987
- agent_role TEXT NOT NULL,
988
- session_id TEXT NOT NULL,
989
- timestamp TEXT NOT NULL,
990
- tool_name TEXT NOT NULL,
991
- project_name TEXT NOT NULL,
992
- has_error INTEGER NOT NULL DEFAULT 0,
993
- raw_text TEXT NOT NULL,
994
- vector F32_BLOB(1024),
995
- version INTEGER NOT NULL DEFAULT 0
996
- );
997
-
998
- CREATE INDEX IF NOT EXISTS idx_memories_agent
999
- ON memories(agent_id);
1000
-
1001
- CREATE INDEX IF NOT EXISTS idx_memories_timestamp
1002
- ON memories(timestamp);
1003
-
1004
- CREATE INDEX IF NOT EXISTS idx_memories_session
1005
- ON memories(session_id);
1006
-
1007
- CREATE INDEX IF NOT EXISTS idx_memories_project
1008
- ON memories(project_name);
1009
-
1010
- CREATE INDEX IF NOT EXISTS idx_memories_tool
1011
- ON memories(tool_name);
1012
-
1013
- CREATE INDEX IF NOT EXISTS idx_memories_version
1014
- ON memories(version);
1015
-
1016
- CREATE INDEX IF NOT EXISTS idx_memories_agent_project
1017
- ON memories(agent_id, project_name);
1018
- `);
1019
- await client.executeMultiple(`
1020
- CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
1021
- raw_text,
1022
- content='memories',
1023
- content_rowid='rowid'
1024
- );
1025
-
1026
- CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
1027
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1028
- END;
1029
-
1030
- CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
1031
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1032
- END;
1033
-
1034
- CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
1035
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1036
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1037
- END;
1038
- `);
1039
- await client.executeMultiple(`
1040
- CREATE TABLE IF NOT EXISTS sync_meta (
1041
- key TEXT PRIMARY KEY,
1042
- value TEXT NOT NULL
1043
- );
1044
- `);
1045
- await client.executeMultiple(`
1046
- CREATE TABLE IF NOT EXISTS tasks (
1047
- id TEXT PRIMARY KEY,
1048
- title TEXT NOT NULL,
1049
- assigned_to TEXT NOT NULL,
1050
- assigned_by TEXT NOT NULL,
1051
- project_name TEXT NOT NULL,
1052
- priority TEXT NOT NULL DEFAULT 'p1',
1053
- status TEXT NOT NULL DEFAULT 'open',
1054
- task_file TEXT,
1055
- created_at TEXT NOT NULL,
1056
- updated_at TEXT NOT NULL
1057
- );
1058
-
1059
- CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
1060
- ON tasks(assigned_to, status);
1061
- `);
1062
- await client.executeMultiple(`
1063
- CREATE TABLE IF NOT EXISTS behaviors (
1064
- id TEXT PRIMARY KEY,
1065
- agent_id TEXT NOT NULL,
1066
- project_name TEXT,
1067
- domain TEXT,
1068
- content TEXT NOT NULL,
1069
- active INTEGER NOT NULL DEFAULT 1,
1070
- created_at TEXT NOT NULL,
1071
- updated_at TEXT NOT NULL
1072
- );
1073
-
1074
- CREATE INDEX IF NOT EXISTS idx_behaviors_agent
1075
- ON behaviors(agent_id, active);
1076
- `);
1110
+ const heapCapMB = totalGB <= 8 ? 256 : 512;
1111
+ const nodeArgs = [`--max-old-space-size=${heapCapMB}`, resolvedPath];
1112
+ const child = spawn(process.execPath, nodeArgs, {
1113
+ detached: true,
1114
+ stdio: ["ignore", "ignore", stderrFd],
1115
+ env: {
1116
+ ...process.env,
1117
+ TMUX: void 0,
1118
+ // Daemon is global — must not inherit session scope
1119
+ TMUX_PANE: void 0,
1120
+ // Prevents resolveExeSession() from scoping to one session
1121
+ EXE_DAEMON_SOCK: SOCKET_PATH,
1122
+ EXE_DAEMON_PID: PID_PATH,
1123
+ [DAEMON_TOKEN_ENV]: daemonToken
1124
+ }
1125
+ });
1126
+ child.unref();
1127
+ if (typeof stderrFd === "number") {
1128
+ try {
1129
+ closeSync(stderrFd);
1130
+ } catch {
1131
+ }
1132
+ }
1133
+ }
1134
+ function acquireSpawnLock() {
1077
1135
  try {
1078
- const coordinatorName = getCoordinatorName();
1079
- const existing = await client.execute({
1080
- sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = ?",
1081
- args: [coordinatorName]
1082
- });
1083
- if (Number(existing.rows[0]?.cnt) === 0) {
1084
- const seededAt = "2026-03-25T00:00:00Z";
1085
- for (const [domain, content] of [
1086
- ["workflow", `Don't ask "keep going?" \u2014 just keep executing phases/plans autonomously`],
1087
- ["tool-use", "Always use create_task MCP tool, never write .md files directly for task creation"],
1088
- ["workflow", "Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission"]
1089
- ]) {
1090
- await client.execute({
1091
- sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
1092
- VALUES (hex(randomblob(16)), ?, NULL, ?, ?, 1, ?, ?)`,
1093
- args: [coordinatorName, domain, content, seededAt, seededAt]
1094
- });
1136
+ const fd = openSync(SPAWN_LOCK_PATH, "wx");
1137
+ closeSync(fd);
1138
+ return true;
1139
+ } catch {
1140
+ try {
1141
+ const stat = statSync(SPAWN_LOCK_PATH);
1142
+ if (Date.now() - stat.mtimeMs > SPAWN_LOCK_STALE_MS) {
1143
+ try {
1144
+ unlinkSync2(SPAWN_LOCK_PATH);
1145
+ } catch {
1146
+ }
1147
+ try {
1148
+ const fd = openSync(SPAWN_LOCK_PATH, "wx");
1149
+ closeSync(fd);
1150
+ return true;
1151
+ } catch {
1152
+ }
1095
1153
  }
1154
+ } catch {
1096
1155
  }
1097
- } catch {
1156
+ return false;
1098
1157
  }
1158
+ }
1159
+ function releaseSpawnLock() {
1099
1160
  try {
1100
- await client.execute({
1101
- sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
1102
- args: []
1103
- });
1161
+ unlinkSync2(SPAWN_LOCK_PATH);
1104
1162
  } catch {
1105
1163
  }
1106
- try {
1164
+ }
1165
+ function connectToSocket() {
1166
+ return new Promise((resolve) => {
1167
+ if (_socket && _connected) {
1168
+ resolve(true);
1169
+ return;
1170
+ }
1171
+ const socket = net.createConnection({ path: SOCKET_PATH });
1172
+ const connectTimeout = setTimeout(() => {
1173
+ socket.destroy();
1174
+ resolve(false);
1175
+ }, 2e3);
1176
+ socket.on("connect", () => {
1177
+ clearTimeout(connectTimeout);
1178
+ _socket = socket;
1179
+ _connected = true;
1180
+ _buffer = "";
1181
+ socket.on("data", handleData);
1182
+ socket.on("close", () => {
1183
+ _connected = false;
1184
+ _socket = null;
1185
+ for (const [id, entry] of _pending) {
1186
+ clearTimeout(entry.timer);
1187
+ _pending.delete(id);
1188
+ entry.resolve({ error: "Connection closed" });
1189
+ }
1190
+ });
1191
+ socket.on("error", () => {
1192
+ _connected = false;
1193
+ _socket = null;
1194
+ });
1195
+ resolve(true);
1196
+ });
1197
+ socket.on("error", () => {
1198
+ clearTimeout(connectTimeout);
1199
+ resolve(false);
1200
+ });
1201
+ });
1202
+ }
1203
+ async function connectEmbedDaemon() {
1204
+ if (_socket && _connected) return true;
1205
+ if (await connectToSocket()) return true;
1206
+ if (acquireSpawnLock()) {
1207
+ try {
1208
+ cleanupStaleFiles();
1209
+ spawnDaemon();
1210
+ } finally {
1211
+ releaseSpawnLock();
1212
+ }
1213
+ }
1214
+ const start = Date.now();
1215
+ let delay2 = 100;
1216
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1217
+ await new Promise((r) => setTimeout(r, delay2));
1218
+ if (await connectToSocket()) return true;
1219
+ delay2 = Math.min(delay2 * 2, 3e3);
1220
+ }
1221
+ return false;
1222
+ }
1223
+ function sendRequest(texts, priority) {
1224
+ return sendDaemonRequest({ texts, priority });
1225
+ }
1226
+ function sendDaemonRequest(payload, timeoutMs = REQUEST_TIMEOUT_MS) {
1227
+ return new Promise((resolve) => {
1228
+ if (!_socket || !_connected) {
1229
+ resolve({ error: "Not connected" });
1230
+ return;
1231
+ }
1232
+ const id = randomUUID();
1233
+ const token = process.env[DAEMON_TOKEN_ENV] ?? readDaemonToken();
1234
+ const timer = setTimeout(() => {
1235
+ _pending.delete(id);
1236
+ resolve({ error: "Request timeout" });
1237
+ }, timeoutMs);
1238
+ _pending.set(id, { resolve, timer });
1239
+ try {
1240
+ _socket.write(JSON.stringify({ id, token, ...payload }) + "\n");
1241
+ } catch {
1242
+ clearTimeout(timer);
1243
+ _pending.delete(id);
1244
+ resolve({ error: "Write failed" });
1245
+ }
1246
+ });
1247
+ }
1248
+ async function pingDaemon() {
1249
+ if (!_socket || !_connected) return null;
1250
+ const response = await sendDaemonRequest({ type: "health" }, 5e3);
1251
+ if (response.health) {
1252
+ return response.health;
1253
+ }
1254
+ return null;
1255
+ }
1256
+ function killAndRespawnDaemon() {
1257
+ if (!acquireSpawnLock()) {
1258
+ process.stderr.write("[exed-client] Another process is already restarting daemon \u2014 skipping\n");
1259
+ if (_socket) {
1260
+ _socket.destroy();
1261
+ _socket = null;
1262
+ }
1263
+ _connected = false;
1264
+ _buffer = "";
1265
+ return;
1266
+ }
1267
+ try {
1268
+ process.stderr.write("[exed-client] Killing daemon for restart...\n");
1269
+ if (existsSync5(PID_PATH)) {
1270
+ try {
1271
+ const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
1272
+ if (pid > 0) {
1273
+ try {
1274
+ process.kill(pid, "SIGKILL");
1275
+ } catch {
1276
+ }
1277
+ }
1278
+ } catch {
1279
+ }
1280
+ }
1281
+ if (_socket) {
1282
+ _socket.destroy();
1283
+ _socket = null;
1284
+ }
1285
+ _connected = false;
1286
+ _buffer = "";
1287
+ try {
1288
+ unlinkSync2(PID_PATH);
1289
+ } catch {
1290
+ }
1291
+ try {
1292
+ unlinkSync2(SOCKET_PATH);
1293
+ } catch {
1294
+ }
1295
+ spawnDaemon();
1296
+ } finally {
1297
+ releaseSpawnLock();
1298
+ }
1299
+ }
1300
+ function isDaemonTooYoung() {
1301
+ try {
1302
+ const stat = statSync(PID_PATH);
1303
+ return Date.now() - stat.mtimeMs < MIN_DAEMON_AGE_MS;
1304
+ } catch {
1305
+ return false;
1306
+ }
1307
+ }
1308
+ async function retryThenRestart(doRequest, label) {
1309
+ const result = await doRequest();
1310
+ if (!result.error) {
1311
+ _consecutiveFailures = 0;
1312
+ return result;
1313
+ }
1314
+ _consecutiveFailures++;
1315
+ for (let i = 0; i < MAX_RETRIES_BEFORE_RESTART; i++) {
1316
+ const delayMs = RETRY_DELAYS_MS[i] ?? 5e3;
1317
+ process.stderr.write(`[exed-client] ${label} failed (${result.error}), retry ${i + 1}/${MAX_RETRIES_BEFORE_RESTART} in ${delayMs}ms
1318
+ `);
1319
+ await new Promise((r) => setTimeout(r, delayMs));
1320
+ if (!_connected) {
1321
+ if (!await connectToSocket()) continue;
1322
+ }
1323
+ const retry = await doRequest();
1324
+ if (!retry.error) {
1325
+ _consecutiveFailures = 0;
1326
+ return retry;
1327
+ }
1328
+ _consecutiveFailures++;
1329
+ }
1330
+ if (isDaemonTooYoung()) {
1331
+ process.stderr.write(`[exed-client] ${label}: daemon too young (< ${MIN_DAEMON_AGE_MS / 1e3}s) \u2014 skipping restart
1332
+ `);
1333
+ return { error: result.error };
1334
+ }
1335
+ process.stderr.write(`[exed-client] ${label}: ${_consecutiveFailures} consecutive failures \u2014 restarting daemon
1336
+ `);
1337
+ killAndRespawnDaemon();
1338
+ const start = Date.now();
1339
+ let delay2 = 200;
1340
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1341
+ await new Promise((r) => setTimeout(r, delay2));
1342
+ if (await connectToSocket()) break;
1343
+ delay2 = Math.min(delay2 * 2, 3e3);
1344
+ }
1345
+ if (!_connected) return { error: "Daemon restart failed" };
1346
+ const final = await doRequest();
1347
+ if (!final.error) _consecutiveFailures = 0;
1348
+ return final;
1349
+ }
1350
+ async function embedViaClient(text, priority = "high") {
1351
+ if (!_connected && !await connectEmbedDaemon()) return null;
1352
+ _requestCount++;
1353
+ if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
1354
+ const health = await pingDaemon();
1355
+ if (!health && !isDaemonTooYoung()) {
1356
+ process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
1357
+ `);
1358
+ killAndRespawnDaemon();
1359
+ const start = Date.now();
1360
+ let d = 200;
1361
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1362
+ await new Promise((r) => setTimeout(r, d));
1363
+ if (await connectToSocket()) break;
1364
+ d = Math.min(d * 2, 3e3);
1365
+ }
1366
+ if (!_connected) return null;
1367
+ }
1368
+ }
1369
+ const result = await retryThenRestart(
1370
+ () => sendRequest([text], priority),
1371
+ "Embed"
1372
+ );
1373
+ return !result.error && result.vectors?.[0] ? result.vectors[0] : null;
1374
+ }
1375
+ async function embedBatchViaClient(texts, priority = "high") {
1376
+ if (!_connected && !await connectEmbedDaemon()) return null;
1377
+ _requestCount++;
1378
+ const result = await retryThenRestart(
1379
+ () => sendRequest(texts, priority),
1380
+ "Batch embed"
1381
+ );
1382
+ return !result.error && result.vectors ? result.vectors : null;
1383
+ }
1384
+ function disconnectClient() {
1385
+ if (_socket) {
1386
+ _socket.destroy();
1387
+ _socket = null;
1388
+ }
1389
+ _connected = false;
1390
+ _buffer = "";
1391
+ for (const [id, entry] of _pending) {
1392
+ clearTimeout(entry.timer);
1393
+ _pending.delete(id);
1394
+ entry.resolve({ error: "Client disconnected" });
1395
+ }
1396
+ }
1397
+ function isClientConnected() {
1398
+ return _connected;
1399
+ }
1400
+ function sendIngestRequest(payload) {
1401
+ if (!_socket || !_connected) return false;
1402
+ try {
1403
+ const id = randomUUID();
1404
+ const token = process.env[DAEMON_TOKEN_ENV] ?? readDaemonToken();
1405
+ _socket.write(JSON.stringify({ id, token, type: "ingest", ...payload }) + "\n");
1406
+ return true;
1407
+ } catch {
1408
+ return false;
1409
+ }
1410
+ }
1411
+ 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;
1412
+ var init_exe_daemon_client = __esm({
1413
+ "src/lib/exe-daemon-client.ts"() {
1414
+ "use strict";
1415
+ init_config();
1416
+ init_daemon_auth();
1417
+ SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path5.join(EXE_AI_DIR, "exed.sock");
1418
+ PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path5.join(EXE_AI_DIR, "exed.pid");
1419
+ SPAWN_LOCK_PATH = path5.join(EXE_AI_DIR, "exed-spawn.lock");
1420
+ SPAWN_LOCK_STALE_MS = 3e4;
1421
+ CONNECT_TIMEOUT_MS = 15e3;
1422
+ REQUEST_TIMEOUT_MS = 3e4;
1423
+ DAEMON_TOKEN_ENV = "EXE_DAEMON_TOKEN";
1424
+ _socket = null;
1425
+ _connected = false;
1426
+ _buffer = "";
1427
+ _requestCount = 0;
1428
+ _consecutiveFailures = 0;
1429
+ HEALTH_CHECK_INTERVAL = 100;
1430
+ MAX_RETRIES_BEFORE_RESTART = 3;
1431
+ RETRY_DELAYS_MS = [1e3, 3e3, 5e3];
1432
+ MIN_DAEMON_AGE_MS = 3e4;
1433
+ _pending = /* @__PURE__ */ new Map();
1434
+ MAX_BUFFER = 1e7;
1435
+ }
1436
+ });
1437
+
1438
+ // src/lib/daemon-protocol.ts
1439
+ var daemon_protocol_exports = {};
1440
+ __export(daemon_protocol_exports, {
1441
+ deserializeArgs: () => deserializeArgs,
1442
+ deserializeResultSet: () => deserializeResultSet,
1443
+ deserializeValue: () => deserializeValue,
1444
+ serializeArgs: () => serializeArgs,
1445
+ serializeResultSet: () => serializeResultSet,
1446
+ serializeValue: () => serializeValue
1447
+ });
1448
+ function serializeValue(v) {
1449
+ if (v === null || v === void 0) return null;
1450
+ if (typeof v === "bigint") return Number(v);
1451
+ if (typeof v === "boolean") return v ? 1 : 0;
1452
+ if (v instanceof Uint8Array) {
1453
+ return { __blob: Buffer.from(v).toString("base64") };
1454
+ }
1455
+ if (ArrayBuffer.isView(v)) {
1456
+ return { __blob: Buffer.from(v.buffer, v.byteOffset, v.byteLength).toString("base64") };
1457
+ }
1458
+ if (v instanceof ArrayBuffer) {
1459
+ return { __blob: Buffer.from(v).toString("base64") };
1460
+ }
1461
+ if (typeof v === "string" || typeof v === "number") return v;
1462
+ return String(v);
1463
+ }
1464
+ function deserializeValue(v) {
1465
+ if (v === null) return null;
1466
+ if (typeof v === "object" && v !== null && "__blob" in v) {
1467
+ const buf = Buffer.from(v.__blob, "base64");
1468
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
1469
+ }
1470
+ return v;
1471
+ }
1472
+ function serializeArgs(args) {
1473
+ return args.map(serializeValue);
1474
+ }
1475
+ function deserializeArgs(args) {
1476
+ return args.map(deserializeValue);
1477
+ }
1478
+ function serializeResultSet(rs) {
1479
+ const rows = [];
1480
+ for (const row of rs.rows) {
1481
+ const obj = {};
1482
+ for (let i = 0; i < rs.columns.length; i++) {
1483
+ const col = rs.columns[i];
1484
+ if (col !== void 0) {
1485
+ obj[col] = serializeValue(row[i]);
1486
+ }
1487
+ }
1488
+ rows.push(obj);
1489
+ }
1490
+ return {
1491
+ columns: [...rs.columns],
1492
+ columnTypes: [...rs.columnTypes ?? []],
1493
+ rows,
1494
+ rowsAffected: typeof rs.rowsAffected === "bigint" ? Number(rs.rowsAffected) : rs.rowsAffected ?? 0,
1495
+ lastInsertRowid: rs.lastInsertRowid != null ? typeof rs.lastInsertRowid === "bigint" ? Number(rs.lastInsertRowid) : rs.lastInsertRowid : null
1496
+ };
1497
+ }
1498
+ function deserializeResultSet(srs) {
1499
+ const rows = srs.rows.map((obj) => {
1500
+ const values = srs.columns.map(
1501
+ (col) => deserializeValue(obj[col] ?? null)
1502
+ );
1503
+ const row = values;
1504
+ for (let i = 0; i < srs.columns.length; i++) {
1505
+ const col = srs.columns[i];
1506
+ if (col !== void 0) {
1507
+ row[col] = values[i] ?? null;
1508
+ }
1509
+ }
1510
+ Object.defineProperty(row, "length", {
1511
+ value: values.length,
1512
+ enumerable: false
1513
+ });
1514
+ return row;
1515
+ });
1516
+ return {
1517
+ columns: srs.columns,
1518
+ columnTypes: srs.columnTypes ?? [],
1519
+ rows,
1520
+ rowsAffected: srs.rowsAffected,
1521
+ lastInsertRowid: srs.lastInsertRowid != null ? BigInt(srs.lastInsertRowid) : void 0,
1522
+ toJSON: () => ({
1523
+ columns: srs.columns,
1524
+ columnTypes: srs.columnTypes ?? [],
1525
+ rows: srs.rows,
1526
+ rowsAffected: srs.rowsAffected,
1527
+ lastInsertRowid: srs.lastInsertRowid
1528
+ })
1529
+ };
1530
+ }
1531
+ var init_daemon_protocol = __esm({
1532
+ "src/lib/daemon-protocol.ts"() {
1533
+ "use strict";
1534
+ }
1535
+ });
1536
+
1537
+ // src/lib/db-daemon-client.ts
1538
+ var db_daemon_client_exports = {};
1539
+ __export(db_daemon_client_exports, {
1540
+ createDaemonDbClient: () => createDaemonDbClient,
1541
+ initDaemonDbClient: () => initDaemonDbClient
1542
+ });
1543
+ function normalizeStatement2(stmt) {
1544
+ if (typeof stmt === "string") {
1545
+ return { sql: stmt, args: [] };
1546
+ }
1547
+ const sql = stmt.sql;
1548
+ let args = [];
1549
+ if (Array.isArray(stmt.args)) {
1550
+ args = stmt.args.map((v) => serializeValue(v));
1551
+ } else if (stmt.args && typeof stmt.args === "object") {
1552
+ const named = {};
1553
+ for (const [key, val] of Object.entries(stmt.args)) {
1554
+ named[key] = serializeValue(val);
1555
+ }
1556
+ return { sql, args: named };
1557
+ }
1558
+ return { sql, args };
1559
+ }
1560
+ function createDaemonDbClient(fallbackClient) {
1561
+ let _useDaemon = false;
1562
+ const client = {
1563
+ async execute(stmt) {
1564
+ if (!_useDaemon || !isClientConnected()) {
1565
+ return fallbackClient.execute(stmt);
1566
+ }
1567
+ const { sql, args } = normalizeStatement2(stmt);
1568
+ const response = await sendDaemonRequest({
1569
+ type: "db-execute",
1570
+ sql,
1571
+ args
1572
+ });
1573
+ if (response.error) {
1574
+ const errMsg = String(response.error);
1575
+ if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
1576
+ process.stderr.write(`[db-daemon] Transport error (${errMsg}), falling back to direct
1577
+ `);
1578
+ return fallbackClient.execute(stmt);
1579
+ }
1580
+ throw new Error(errMsg);
1581
+ }
1582
+ if (response.db) {
1583
+ return deserializeResultSet(response.db);
1584
+ }
1585
+ process.stderr.write("[db-daemon] Unexpected response shape, falling back to direct\n");
1586
+ return fallbackClient.execute(stmt);
1587
+ },
1588
+ async batch(stmts, mode) {
1589
+ if (!_useDaemon || !isClientConnected()) {
1590
+ return fallbackClient.batch(stmts, mode);
1591
+ }
1592
+ const statements = stmts.map(normalizeStatement2);
1593
+ const response = await sendDaemonRequest({
1594
+ type: "db-batch",
1595
+ statements,
1596
+ mode: mode ?? "deferred"
1597
+ });
1598
+ if (response.error) {
1599
+ const errMsg = String(response.error);
1600
+ if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
1601
+ process.stderr.write(`[db-daemon] Batch transport error (${errMsg}), falling back to direct
1602
+ `);
1603
+ return fallbackClient.batch(stmts, mode);
1604
+ }
1605
+ throw new Error(errMsg);
1606
+ }
1607
+ const batchResults = response["db-batch"];
1608
+ if (batchResults) {
1609
+ return batchResults.map(deserializeResultSet);
1610
+ }
1611
+ process.stderr.write("[db-daemon] Unexpected batch response shape, falling back to direct\n");
1612
+ return fallbackClient.batch(stmts, mode);
1613
+ },
1614
+ // Transaction support — delegate to fallback (transactions need direct connection)
1615
+ async transaction(mode) {
1616
+ return fallbackClient.transaction(mode);
1617
+ },
1618
+ // executeMultiple — delegate to fallback (used only for schema migrations)
1619
+ async executeMultiple(sql) {
1620
+ return fallbackClient.executeMultiple(sql);
1621
+ },
1622
+ // migrate — delegate to fallback
1623
+ async migrate(stmts) {
1624
+ return fallbackClient.migrate(stmts);
1625
+ },
1626
+ // Sync mode — delegate to fallback
1627
+ sync() {
1628
+ return fallbackClient.sync();
1629
+ },
1630
+ close() {
1631
+ _useDaemon = false;
1632
+ },
1633
+ get closed() {
1634
+ return fallbackClient.closed;
1635
+ },
1636
+ get protocol() {
1637
+ return fallbackClient.protocol;
1638
+ }
1639
+ };
1640
+ return {
1641
+ ...client,
1642
+ /** Enable daemon routing (call after confirming daemon is connected) */
1643
+ _enableDaemon() {
1644
+ _useDaemon = true;
1645
+ },
1646
+ /** Check if daemon routing is active */
1647
+ _isDaemonActive() {
1648
+ return _useDaemon && isClientConnected();
1649
+ }
1650
+ };
1651
+ }
1652
+ async function initDaemonDbClient(fallbackClient) {
1653
+ if (process.env.EXE_IS_DAEMON === "1") return null;
1654
+ const connected = await connectEmbedDaemon();
1655
+ if (!connected) {
1656
+ process.stderr.write("[db-daemon] Daemon unavailable \u2014 using direct SQLite\n");
1657
+ return null;
1658
+ }
1659
+ const client = createDaemonDbClient(fallbackClient);
1660
+ client._enableDaemon();
1661
+ process.stderr.write("[db-daemon] DB routing through daemon (single-writer)\n");
1662
+ return client;
1663
+ }
1664
+ var init_db_daemon_client = __esm({
1665
+ "src/lib/db-daemon-client.ts"() {
1666
+ "use strict";
1667
+ init_exe_daemon_client();
1668
+ init_daemon_protocol();
1669
+ }
1670
+ });
1671
+
1672
+ // src/lib/database.ts
1673
+ var database_exports = {};
1674
+ __export(database_exports, {
1675
+ disposeDatabase: () => disposeDatabase,
1676
+ disposeTurso: () => disposeTurso,
1677
+ ensureSchema: () => ensureSchema,
1678
+ getClient: () => getClient,
1679
+ getRawClient: () => getRawClient,
1680
+ initDaemonClient: () => initDaemonClient,
1681
+ initDatabase: () => initDatabase,
1682
+ initTurso: () => initTurso,
1683
+ isInitialized: () => isInitialized
1684
+ });
1685
+ import { createClient } from "@libsql/client";
1686
+ async function initDatabase(config) {
1687
+ if (_walCheckpointTimer) {
1688
+ clearInterval(_walCheckpointTimer);
1689
+ _walCheckpointTimer = null;
1690
+ }
1691
+ if (_daemonClient) {
1692
+ _daemonClient.close();
1693
+ _daemonClient = null;
1694
+ }
1695
+ if (_adapterClient && _adapterClient !== _resilientClient) {
1696
+ _adapterClient.close();
1697
+ }
1698
+ _adapterClient = null;
1699
+ if (_client) {
1700
+ _client.close();
1701
+ _client = null;
1702
+ _resilientClient = null;
1703
+ }
1704
+ const opts = {
1705
+ url: `file:${config.dbPath}`
1706
+ };
1707
+ if (config.encryptionKey) {
1708
+ opts.encryptionKey = config.encryptionKey;
1709
+ }
1710
+ _client = createClient(opts);
1711
+ _resilientClient = wrapWithRetry(_client);
1712
+ _adapterClient = _resilientClient;
1713
+ _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
1714
+ });
1715
+ _client.execute("PRAGMA journal_mode = WAL").catch(() => {
1716
+ });
1717
+ if (_walCheckpointTimer) clearInterval(_walCheckpointTimer);
1718
+ _walCheckpointTimer = setInterval(() => {
1719
+ _client?.execute("PRAGMA wal_checkpoint(PASSIVE)").catch(() => {
1720
+ });
1721
+ }, 3e4);
1722
+ _walCheckpointTimer.unref();
1723
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
1724
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
1725
+ }
1726
+ }
1727
+ function isInitialized() {
1728
+ return _adapterClient !== null || _client !== null;
1729
+ }
1730
+ function getClient() {
1731
+ if (!_adapterClient) {
1732
+ throw new Error("Database client not initialized. Call initDatabase() first.");
1733
+ }
1734
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
1735
+ return _adapterClient;
1736
+ }
1737
+ if (process.env.EXE_IS_DAEMON === "1") {
1738
+ return _resilientClient;
1739
+ }
1740
+ if (_daemonClient && _daemonClient._isDaemonActive()) {
1741
+ return _daemonClient;
1742
+ }
1743
+ return _resilientClient;
1744
+ }
1745
+ async function initDaemonClient() {
1746
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") return;
1747
+ if (process.env.EXE_IS_DAEMON === "1") return;
1748
+ if (process.env.VITEST) return;
1749
+ if (!_resilientClient) return;
1750
+ if (_daemonClient) return;
1751
+ try {
1752
+ const { initDaemonDbClient: initDaemonDbClient2 } = await Promise.resolve().then(() => (init_db_daemon_client(), db_daemon_client_exports));
1753
+ _daemonClient = await initDaemonDbClient2(_resilientClient);
1754
+ } catch (err) {
1755
+ process.stderr.write(
1756
+ `[database] Daemon client init failed (non-fatal): ${err instanceof Error ? err.message : String(err)}
1757
+ `
1758
+ );
1759
+ }
1760
+ }
1761
+ function getRawClient() {
1762
+ if (!_client) {
1763
+ throw new Error("Database client not initialized. Call initDatabase() first.");
1764
+ }
1765
+ return _client;
1766
+ }
1767
+ async function ensureSchema() {
1768
+ const client = getRawClient();
1769
+ await client.execute("PRAGMA journal_mode = WAL");
1770
+ await client.execute("PRAGMA busy_timeout = 30000");
1771
+ await client.execute("PRAGMA wal_autocheckpoint = 1000");
1772
+ try {
1773
+ await client.execute("PRAGMA libsql_vector_search_ef = 128");
1774
+ } catch {
1775
+ }
1776
+ await client.executeMultiple(`
1777
+ CREATE TABLE IF NOT EXISTS memories (
1778
+ id TEXT PRIMARY KEY,
1779
+ agent_id TEXT NOT NULL,
1780
+ agent_role TEXT NOT NULL,
1781
+ session_id TEXT NOT NULL,
1782
+ timestamp TEXT NOT NULL,
1783
+ tool_name TEXT NOT NULL,
1784
+ project_name TEXT NOT NULL,
1785
+ has_error INTEGER NOT NULL DEFAULT 0,
1786
+ raw_text TEXT NOT NULL,
1787
+ vector F32_BLOB(1024),
1788
+ version INTEGER NOT NULL DEFAULT 0
1789
+ );
1790
+
1791
+ CREATE INDEX IF NOT EXISTS idx_memories_agent
1792
+ ON memories(agent_id);
1793
+
1794
+ CREATE INDEX IF NOT EXISTS idx_memories_timestamp
1795
+ ON memories(timestamp);
1796
+
1797
+ CREATE INDEX IF NOT EXISTS idx_memories_session
1798
+ ON memories(session_id);
1799
+
1800
+ CREATE INDEX IF NOT EXISTS idx_memories_project
1801
+ ON memories(project_name);
1802
+
1803
+ CREATE INDEX IF NOT EXISTS idx_memories_tool
1804
+ ON memories(tool_name);
1805
+
1806
+ CREATE INDEX IF NOT EXISTS idx_memories_version
1807
+ ON memories(version);
1808
+
1809
+ CREATE INDEX IF NOT EXISTS idx_memories_agent_project
1810
+ ON memories(agent_id, project_name);
1811
+ `);
1812
+ await client.executeMultiple(`
1813
+ CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
1814
+ raw_text,
1815
+ content='memories',
1816
+ content_rowid='rowid'
1817
+ );
1818
+
1819
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
1820
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1821
+ END;
1822
+
1823
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
1824
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1825
+ END;
1826
+
1827
+ CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
1828
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1829
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1830
+ END;
1831
+ `);
1832
+ await client.executeMultiple(`
1833
+ CREATE TABLE IF NOT EXISTS sync_meta (
1834
+ key TEXT PRIMARY KEY,
1835
+ value TEXT NOT NULL
1836
+ );
1837
+ `);
1838
+ await client.executeMultiple(`
1839
+ CREATE TABLE IF NOT EXISTS tasks (
1840
+ id TEXT PRIMARY KEY,
1841
+ title TEXT NOT NULL,
1842
+ assigned_to TEXT NOT NULL,
1843
+ assigned_by TEXT NOT NULL,
1844
+ project_name TEXT NOT NULL,
1845
+ priority TEXT NOT NULL DEFAULT 'p1',
1846
+ status TEXT NOT NULL DEFAULT 'open',
1847
+ task_file TEXT,
1848
+ created_at TEXT NOT NULL,
1849
+ updated_at TEXT NOT NULL
1850
+ );
1851
+
1852
+ CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
1853
+ ON tasks(assigned_to, status);
1854
+ `);
1855
+ await client.executeMultiple(`
1856
+ CREATE TABLE IF NOT EXISTS behaviors (
1857
+ id TEXT PRIMARY KEY,
1858
+ agent_id TEXT NOT NULL,
1859
+ project_name TEXT,
1860
+ domain TEXT,
1861
+ content TEXT NOT NULL,
1862
+ active INTEGER NOT NULL DEFAULT 1,
1863
+ created_at TEXT NOT NULL,
1864
+ updated_at TEXT NOT NULL
1865
+ );
1866
+
1867
+ CREATE INDEX IF NOT EXISTS idx_behaviors_agent
1868
+ ON behaviors(agent_id, active);
1869
+ `);
1870
+ try {
1871
+ const coordinatorName = getCoordinatorName();
1872
+ const existing = await client.execute({
1873
+ sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = ?",
1874
+ args: [coordinatorName]
1875
+ });
1876
+ if (Number(existing.rows[0]?.cnt) === 0) {
1877
+ const seededAt = "2026-03-25T00:00:00Z";
1878
+ for (const [domain, content] of [
1879
+ ["workflow", `Don't ask "keep going?" \u2014 just keep executing phases/plans autonomously`],
1880
+ ["tool-use", "Always use create_task MCP tool, never write .md files directly for task creation"],
1881
+ ["workflow", "Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission"]
1882
+ ]) {
1883
+ await client.execute({
1884
+ sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
1885
+ VALUES (hex(randomblob(16)), ?, NULL, ?, ?, 1, ?, ?)`,
1886
+ args: [coordinatorName, domain, content, seededAt, seededAt]
1887
+ });
1888
+ }
1889
+ }
1890
+ } catch {
1891
+ }
1892
+ try {
1893
+ await client.execute({
1894
+ sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
1895
+ args: []
1896
+ });
1897
+ } catch {
1898
+ }
1899
+ try {
1900
+ await client.execute({
1901
+ sql: `ALTER TABLE behaviors ADD COLUMN vector F32_BLOB(${EMBEDDING_DIM})`,
1902
+ args: []
1903
+ });
1904
+ } catch {
1905
+ }
1906
+ try {
1107
1907
  await client.execute({
1108
1908
  sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
1109
1909
  args: []
@@ -1940,26 +2740,159 @@ async function ensureSchema() {
1940
2740
  }
1941
2741
  }
1942
2742
  try {
1943
- await client.execute({
1944
- sql: `UPDATE tasks SET status = 'closed' WHERE status = 'done' AND result IS NOT NULL`,
1945
- args: []
1946
- });
1947
- } catch {
2743
+ await client.execute({
2744
+ sql: `UPDATE tasks SET status = 'closed' WHERE status = 'done' AND result IS NOT NULL`,
2745
+ args: []
2746
+ });
2747
+ } catch {
2748
+ }
2749
+ }
2750
+ async function disposeDatabase() {
2751
+ if (_walCheckpointTimer) {
2752
+ clearInterval(_walCheckpointTimer);
2753
+ _walCheckpointTimer = null;
2754
+ }
2755
+ if (_daemonClient) {
2756
+ _daemonClient.close();
2757
+ _daemonClient = null;
2758
+ }
2759
+ if (_adapterClient && _adapterClient !== _resilientClient) {
2760
+ _adapterClient.close();
2761
+ }
2762
+ _adapterClient = null;
2763
+ if (_client) {
2764
+ _client.close();
2765
+ _client = null;
2766
+ _resilientClient = null;
2767
+ }
2768
+ }
2769
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso, disposeTurso;
2770
+ var init_database = __esm({
2771
+ "src/lib/database.ts"() {
2772
+ "use strict";
2773
+ init_db_retry();
2774
+ init_employees();
2775
+ init_database_adapter();
2776
+ init_memory();
2777
+ _client = null;
2778
+ _resilientClient = null;
2779
+ _walCheckpointTimer = null;
2780
+ _daemonClient = null;
2781
+ _adapterClient = null;
2782
+ initTurso = initDatabase;
2783
+ disposeTurso = disposeDatabase;
2784
+ }
2785
+ });
2786
+
2787
+ // src/lib/keychain.ts
2788
+ import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
2789
+ import { existsSync as existsSync6 } from "fs";
2790
+ import path6 from "path";
2791
+ import os5 from "os";
2792
+ function getKeyDir() {
2793
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path6.join(os5.homedir(), ".exe-os");
2794
+ }
2795
+ function getKeyPath() {
2796
+ return path6.join(getKeyDir(), "master.key");
2797
+ }
2798
+ async function tryKeytar() {
2799
+ try {
2800
+ return await import("keytar");
2801
+ } catch {
2802
+ return null;
2803
+ }
2804
+ }
2805
+ async function getMasterKey() {
2806
+ const keytar = await tryKeytar();
2807
+ if (keytar) {
2808
+ try {
2809
+ const stored = await keytar.getPassword(SERVICE, ACCOUNT);
2810
+ if (stored) {
2811
+ return Buffer.from(stored, "base64");
2812
+ }
2813
+ } catch {
2814
+ }
2815
+ }
2816
+ const keyPath = getKeyPath();
2817
+ if (!existsSync6(keyPath)) {
2818
+ process.stderr.write(
2819
+ `[keychain] Key not found at ${keyPath} (HOME=${os5.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2820
+ `
2821
+ );
2822
+ return null;
2823
+ }
2824
+ try {
2825
+ const content = await readFile3(keyPath, "utf-8");
2826
+ return Buffer.from(content.trim(), "base64");
2827
+ } catch (err) {
2828
+ process.stderr.write(
2829
+ `[keychain] Key read failed at ${keyPath}: ${err instanceof Error ? err.message : String(err)}
2830
+ `
2831
+ );
2832
+ return null;
1948
2833
  }
1949
2834
  }
1950
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
1951
- var init_database = __esm({
1952
- "src/lib/database.ts"() {
2835
+ var SERVICE, ACCOUNT;
2836
+ var init_keychain = __esm({
2837
+ "src/lib/keychain.ts"() {
1953
2838
  "use strict";
1954
- init_db_retry();
1955
- init_employees();
1956
- init_database_adapter();
1957
- _client = null;
1958
- _resilientClient = null;
1959
- _walCheckpointTimer = null;
1960
- _daemonClient = null;
1961
- _adapterClient = null;
1962
- initTurso = initDatabase;
2839
+ SERVICE = "exe-mem";
2840
+ ACCOUNT = "master-key";
2841
+ }
2842
+ });
2843
+
2844
+ // src/lib/state-bus.ts
2845
+ var StateBus, orgBus;
2846
+ var init_state_bus = __esm({
2847
+ "src/lib/state-bus.ts"() {
2848
+ "use strict";
2849
+ StateBus = class {
2850
+ handlers = /* @__PURE__ */ new Map();
2851
+ globalHandlers = /* @__PURE__ */ new Set();
2852
+ /** Emit an event to all subscribers */
2853
+ emit(event) {
2854
+ const typeHandlers = this.handlers.get(event.type);
2855
+ if (typeHandlers) {
2856
+ for (const handler of typeHandlers) {
2857
+ try {
2858
+ handler(event);
2859
+ } catch {
2860
+ }
2861
+ }
2862
+ }
2863
+ for (const handler of this.globalHandlers) {
2864
+ try {
2865
+ handler(event);
2866
+ } catch {
2867
+ }
2868
+ }
2869
+ }
2870
+ /** Subscribe to a specific event type */
2871
+ on(type, handler) {
2872
+ if (!this.handlers.has(type)) {
2873
+ this.handlers.set(type, /* @__PURE__ */ new Set());
2874
+ }
2875
+ this.handlers.get(type).add(handler);
2876
+ }
2877
+ /** Subscribe to ALL events */
2878
+ onAny(handler) {
2879
+ this.globalHandlers.add(handler);
2880
+ }
2881
+ /** Unsubscribe from a specific event type */
2882
+ off(type, handler) {
2883
+ this.handlers.get(type)?.delete(handler);
2884
+ }
2885
+ /** Unsubscribe from ALL events */
2886
+ offAny(handler) {
2887
+ this.globalHandlers.delete(handler);
2888
+ }
2889
+ /** Remove all listeners */
2890
+ clear() {
2891
+ this.handlers.clear();
2892
+ this.globalHandlers.clear();
2893
+ }
2894
+ };
2895
+ orgBus = new StateBus();
1963
2896
  }
1964
2897
  });
1965
2898
 
@@ -1977,12 +2910,12 @@ __export(shard_manager_exports, {
1977
2910
  listShards: () => listShards,
1978
2911
  shardExists: () => shardExists
1979
2912
  });
1980
- import path5 from "path";
1981
- import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync } from "fs";
2913
+ import path7 from "path";
2914
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, readdirSync } from "fs";
1982
2915
  import { createClient as createClient2 } from "@libsql/client";
1983
2916
  function initShardManager(encryptionKey) {
1984
2917
  _encryptionKey = encryptionKey;
1985
- if (!existsSync5(SHARDS_DIR)) {
2918
+ if (!existsSync7(SHARDS_DIR)) {
1986
2919
  mkdirSync2(SHARDS_DIR, { recursive: true });
1987
2920
  }
1988
2921
  _shardingEnabled = true;
@@ -2012,7 +2945,7 @@ function getShardClient(projectName) {
2012
2945
  while (_shards.size >= MAX_OPEN_SHARDS) {
2013
2946
  evictLRU();
2014
2947
  }
2015
- const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
2948
+ const dbPath = path7.join(SHARDS_DIR, `${safeName}.db`);
2016
2949
  const client = createClient2({
2017
2950
  url: `file:${dbPath}`,
2018
2951
  encryptionKey: _encryptionKey
@@ -2023,10 +2956,10 @@ function getShardClient(projectName) {
2023
2956
  }
2024
2957
  function shardExists(projectName) {
2025
2958
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
2026
- return existsSync5(path5.join(SHARDS_DIR, `${safeName}.db`));
2959
+ return existsSync7(path7.join(SHARDS_DIR, `${safeName}.db`));
2027
2960
  }
2028
2961
  function listShards() {
2029
- if (!existsSync5(SHARDS_DIR)) return [];
2962
+ if (!existsSync7(SHARDS_DIR)) return [];
2030
2963
  return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
2031
2964
  }
2032
2965
  async function ensureShardSchema(client) {
@@ -2273,7 +3206,7 @@ var init_shard_manager = __esm({
2273
3206
  "src/lib/shard-manager.ts"() {
2274
3207
  "use strict";
2275
3208
  init_config();
2276
- SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
3209
+ SHARDS_DIR = path7.join(EXE_AI_DIR, "shards");
2277
3210
  SHARD_IDLE_MS = 5 * 60 * 1e3;
2278
3211
  MAX_OPEN_SHARDS = 10;
2279
3212
  EVICTION_INTERVAL_MS = 60 * 1e3;
@@ -2393,6 +3326,68 @@ var init_platform_procedures = __esm({
2393
3326
  domain: "architecture",
2394
3327
  priority: "p0",
2395
3328
  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."
3329
+ },
3330
+ // --- MCP is the ONLY data interface ---
3331
+ {
3332
+ title: "MCP disconnect \u2014 ask the user, never work around it",
3333
+ domain: "workflow",
3334
+ priority: "p0",
3335
+ 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."
3336
+ },
3337
+ // --- MCP Tool Catalog (Layer 0 — every agent knows what tools exist) ---
3338
+ {
3339
+ title: "MCP tools \u2014 memory and search",
3340
+ domain: "tool-use",
3341
+ priority: "p1",
3342
+ 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)."
3343
+ },
3344
+ {
3345
+ title: "MCP tools \u2014 task orchestration",
3346
+ domain: "tool-use",
3347
+ priority: "p1",
3348
+ 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."
3349
+ },
3350
+ {
3351
+ title: "MCP tools \u2014 knowledge graph (GraphRAG)",
3352
+ domain: "tool-use",
3353
+ priority: "p1",
3354
+ 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."
3355
+ },
3356
+ {
3357
+ title: "MCP tools \u2014 identity, behavior, and decisions",
3358
+ domain: "tool-use",
3359
+ priority: "p1",
3360
+ 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."
3361
+ },
3362
+ {
3363
+ title: "MCP tools \u2014 communication and messaging",
3364
+ domain: "tool-use",
3365
+ priority: "p1",
3366
+ 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.)."
3367
+ },
3368
+ {
3369
+ title: "MCP tools \u2014 wiki, documents, and content",
3370
+ domain: "tool-use",
3371
+ priority: "p1",
3372
+ 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."
3373
+ },
3374
+ {
3375
+ title: "MCP tools \u2014 system, operations, and admin",
3376
+ domain: "tool-use",
3377
+ priority: "p1",
3378
+ 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."
3379
+ },
3380
+ {
3381
+ title: "MCP tools \u2014 config, licensing, and team",
3382
+ domain: "tool-use",
3383
+ priority: "p1",
3384
+ 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."
3385
+ },
3386
+ {
3387
+ title: "MCP tools \u2014 advanced (triggers, skills, orchestration)",
3388
+ domain: "tool-use",
3389
+ priority: "p1",
3390
+ 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."
2396
3391
  }
2397
3392
  ];
2398
3393
  PLATFORM_PROCEDURE_TITLES = new Set(
@@ -2409,7 +3404,7 @@ __export(global_procedures_exports, {
2409
3404
  loadGlobalProcedures: () => loadGlobalProcedures,
2410
3405
  storeGlobalProcedure: () => storeGlobalProcedure
2411
3406
  });
2412
- import { randomUUID } from "crypto";
3407
+ import { randomUUID as randomUUID2 } from "crypto";
2413
3408
  async function loadGlobalProcedures() {
2414
3409
  const client = getClient();
2415
3410
  const result = await client.execute({
@@ -2438,7 +3433,7 @@ ${sections.join("\n\n")}
2438
3433
  `;
2439
3434
  }
2440
3435
  async function storeGlobalProcedure(input) {
2441
- const id = randomUUID();
3436
+ const id = randomUUID2();
2442
3437
  const now = (/* @__PURE__ */ new Date()).toISOString();
2443
3438
  const client = getClient();
2444
3439
  await client.execute({
@@ -2472,119 +3467,25 @@ ${p.content}`).join("\n\n");
2472
3467
  }
2473
3468
  });
2474
3469
 
2475
- // src/bin/exe-team.ts
2476
- init_employees();
2477
-
2478
3470
  // src/lib/store.ts
3471
+ var store_exports = {};
3472
+ __export(store_exports, {
3473
+ attachDocumentMetadata: () => attachDocumentMetadata,
3474
+ buildRawVisibilityFilter: () => buildRawVisibilityFilter,
3475
+ buildWikiScopeFilter: () => buildWikiScopeFilter,
3476
+ classifyTier: () => classifyTier,
3477
+ disposeStore: () => disposeStore,
3478
+ flushBatch: () => flushBatch,
3479
+ flushTier3: () => flushTier3,
3480
+ getMemoryCardinality: () => getMemoryCardinality,
3481
+ initStore: () => initStore,
3482
+ reserveVersions: () => reserveVersions,
3483
+ searchMemories: () => searchMemories,
3484
+ updateMemoryStatus: () => updateMemoryStatus,
3485
+ vectorToBlob: () => vectorToBlob,
3486
+ writeMemory: () => writeMemory
3487
+ });
2479
3488
  import { createHash } from "crypto";
2480
- init_database();
2481
-
2482
- // src/lib/keychain.ts
2483
- import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
2484
- import { existsSync as existsSync4 } from "fs";
2485
- import path4 from "path";
2486
- import os4 from "os";
2487
- var SERVICE = "exe-mem";
2488
- var ACCOUNT = "master-key";
2489
- function getKeyDir() {
2490
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
2491
- }
2492
- function getKeyPath() {
2493
- return path4.join(getKeyDir(), "master.key");
2494
- }
2495
- async function tryKeytar() {
2496
- try {
2497
- return await import("keytar");
2498
- } catch {
2499
- return null;
2500
- }
2501
- }
2502
- async function getMasterKey() {
2503
- const keytar = await tryKeytar();
2504
- if (keytar) {
2505
- try {
2506
- const stored = await keytar.getPassword(SERVICE, ACCOUNT);
2507
- if (stored) {
2508
- return Buffer.from(stored, "base64");
2509
- }
2510
- } catch {
2511
- }
2512
- }
2513
- const keyPath = getKeyPath();
2514
- if (!existsSync4(keyPath)) {
2515
- process.stderr.write(
2516
- `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2517
- `
2518
- );
2519
- return null;
2520
- }
2521
- try {
2522
- const content = await readFile3(keyPath, "utf-8");
2523
- return Buffer.from(content.trim(), "base64");
2524
- } catch (err) {
2525
- process.stderr.write(
2526
- `[keychain] Key read failed at ${keyPath}: ${err instanceof Error ? err.message : String(err)}
2527
- `
2528
- );
2529
- return null;
2530
- }
2531
- }
2532
-
2533
- // src/lib/store.ts
2534
- init_config();
2535
-
2536
- // src/lib/state-bus.ts
2537
- var StateBus = class {
2538
- handlers = /* @__PURE__ */ new Map();
2539
- globalHandlers = /* @__PURE__ */ new Set();
2540
- /** Emit an event to all subscribers */
2541
- emit(event) {
2542
- const typeHandlers = this.handlers.get(event.type);
2543
- if (typeHandlers) {
2544
- for (const handler of typeHandlers) {
2545
- try {
2546
- handler(event);
2547
- } catch {
2548
- }
2549
- }
2550
- }
2551
- for (const handler of this.globalHandlers) {
2552
- try {
2553
- handler(event);
2554
- } catch {
2555
- }
2556
- }
2557
- }
2558
- /** Subscribe to a specific event type */
2559
- on(type, handler) {
2560
- if (!this.handlers.has(type)) {
2561
- this.handlers.set(type, /* @__PURE__ */ new Set());
2562
- }
2563
- this.handlers.get(type).add(handler);
2564
- }
2565
- /** Subscribe to ALL events */
2566
- onAny(handler) {
2567
- this.globalHandlers.add(handler);
2568
- }
2569
- /** Unsubscribe from a specific event type */
2570
- off(type, handler) {
2571
- this.handlers.get(type)?.delete(handler);
2572
- }
2573
- /** Unsubscribe from ALL events */
2574
- offAny(handler) {
2575
- this.globalHandlers.delete(handler);
2576
- }
2577
- /** Remove all listeners */
2578
- clear() {
2579
- this.handlers.clear();
2580
- this.globalHandlers.clear();
2581
- }
2582
- };
2583
- var orgBus = new StateBus();
2584
-
2585
- // src/lib/store.ts
2586
- var INIT_MAX_RETRIES = 3;
2587
- var INIT_RETRY_DELAY_MS = 1e3;
2588
3489
  function isBusyError2(err) {
2589
3490
  if (err instanceof Error) {
2590
3491
  const msg = err.message.toLowerCase();
@@ -2607,12 +3508,6 @@ async function retryOnBusy2(fn, label) {
2607
3508
  }
2608
3509
  throw new Error("unreachable");
2609
3510
  }
2610
- var _pendingRecords = [];
2611
- var _batchSize = 20;
2612
- var _flushIntervalMs = 1e4;
2613
- var _flushTimer = null;
2614
- var _flushing = false;
2615
- var _nextVersion = 1;
2616
3511
  async function initStore(options) {
2617
3512
  if (_flushTimer !== null) {
2618
3513
  clearInterval(_flushTimer);
@@ -2642,6 +3537,11 @@ async function initStore(options) {
2642
3537
  encryptionKey: hexKey
2643
3538
  });
2644
3539
  await retryOnBusy2(() => ensureSchema(), "ensureSchema");
3540
+ try {
3541
+ const { initDaemonClient: initDaemonClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
3542
+ await initDaemonClient2();
3543
+ } catch {
3544
+ }
2645
3545
  if (!options?.lightweight) {
2646
3546
  try {
2647
3547
  const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
@@ -2661,19 +3561,577 @@ async function initStore(options) {
2661
3561
  }
2662
3562
  }
2663
3563
  }
3564
+ function classifyTier(record) {
3565
+ if (record.tool_name === "commit_to_long_term_memory" && (record.importance ?? 0) >= 8) return 1;
3566
+ if (["store_memory", "manual"].includes(record.tool_name ?? "") && (record.importance ?? 0) >= 5) return 2;
3567
+ return 3;
3568
+ }
3569
+ function inferFilePaths(record) {
3570
+ if (!["Read", "Write", "Edit"].includes(record.tool_name)) return null;
3571
+ const firstLine = record.raw_text.split("\n")[0] ?? "";
3572
+ const match = firstLine.match(/(\/[\w./-]+\.\w+)/);
3573
+ return match ? JSON.stringify([match[1]]) : null;
3574
+ }
3575
+ function inferCommitHash(record) {
3576
+ if (record.tool_name !== "Bash") return null;
3577
+ const match = record.raw_text.match(/\b([a-f0-9]{7,40})\b/);
3578
+ return match ? match[1] : null;
3579
+ }
3580
+ function inferLanguageType(record) {
3581
+ const text = record.raw_text;
3582
+ if (!text || text.length < 10) return null;
3583
+ const trimmed = text.trimStart();
3584
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) return "json";
3585
+ if (/\b(SELECT|INSERT|UPDATE|DELETE|CREATE TABLE|ALTER TABLE)\b/i.test(text)) return "sql";
3586
+ if (/\b(function |const |import |export |class |def |async |=>)\b/.test(text)) return "code";
3587
+ if (trimmed.startsWith("#") || trimmed.startsWith("*")) return "prose";
3588
+ return "mixed";
3589
+ }
3590
+ function inferDomain(record) {
3591
+ const proj = (record.project_name ?? "").toLowerCase();
3592
+ if (proj.includes("marketing") || proj.includes("content")) return "marketing";
3593
+ if (proj.includes("crm") || proj.includes("customer")) return "customer";
3594
+ return null;
3595
+ }
3596
+ async function writeMemory(record) {
3597
+ if (record.vector !== null && record.vector.length !== EMBEDDING_DIM) {
3598
+ throw new Error(
3599
+ `Expected ${EMBEDDING_DIM}-dim vector, got ${record.vector.length}`
3600
+ );
3601
+ }
3602
+ const contentHash = createHash("md5").update(record.raw_text).digest("hex");
3603
+ if (_pendingRecords.some((r) => r.content_hash === contentHash && r.agent_id === record.agent_id)) {
3604
+ return;
3605
+ }
3606
+ try {
3607
+ const client = getClient();
3608
+ const existing = await client.execute({
3609
+ sql: "SELECT id FROM memories WHERE content_hash = ? AND agent_id = ? LIMIT 1",
3610
+ args: [contentHash, record.agent_id]
3611
+ });
3612
+ if (existing.rows.length > 0) return;
3613
+ } catch {
3614
+ }
3615
+ const dbRow = {
3616
+ id: record.id,
3617
+ agent_id: record.agent_id,
3618
+ agent_role: record.agent_role,
3619
+ session_id: record.session_id,
3620
+ timestamp: record.timestamp,
3621
+ tool_name: record.tool_name,
3622
+ project_name: record.project_name,
3623
+ has_error: record.has_error ? 1 : 0,
3624
+ raw_text: record.raw_text,
3625
+ vector: record.vector,
3626
+ version: 0,
3627
+ // Placeholder — assigned atomically at flush time
3628
+ task_id: record.task_id ?? null,
3629
+ importance: record.importance ?? 5,
3630
+ status: record.status ?? "active",
3631
+ confidence: record.confidence ?? 0.7,
3632
+ last_accessed: record.last_accessed ?? record.timestamp,
3633
+ workspace_id: record.workspace_id ?? null,
3634
+ document_id: record.document_id ?? null,
3635
+ user_id: record.user_id ?? null,
3636
+ char_offset: record.char_offset ?? null,
3637
+ page_number: record.page_number ?? null,
3638
+ source_path: record.source_path ?? null,
3639
+ source_type: record.source_type ?? null,
3640
+ tier: record.tier ?? classifyTier(record),
3641
+ supersedes_id: record.supersedes_id ?? null,
3642
+ draft: record.draft ? 1 : 0,
3643
+ memory_type: record.memory_type ?? "raw",
3644
+ trajectory: record.trajectory ? JSON.stringify(record.trajectory) : null,
3645
+ content_hash: contentHash,
3646
+ intent: record.intent ?? null,
3647
+ outcome: record.outcome ?? null,
3648
+ domain: record.domain ?? inferDomain(record),
3649
+ referenced_entities: record.referenced_entities ?? null,
3650
+ retrieval_count: record.retrieval_count ?? 0,
3651
+ chain_position: record.chain_position ?? null,
3652
+ review_status: record.review_status ?? null,
3653
+ context_window_pct: record.context_window_pct ?? null,
3654
+ file_paths: record.file_paths ?? inferFilePaths(record),
3655
+ commit_hash: record.commit_hash ?? inferCommitHash(record),
3656
+ duration_ms: record.duration_ms ?? null,
3657
+ token_cost: record.token_cost ?? null,
3658
+ audience: record.audience ?? null,
3659
+ language_type: record.language_type ?? inferLanguageType(record),
3660
+ parent_memory_id: record.parent_memory_id ?? null
3661
+ };
3662
+ _pendingRecords.push(dbRow);
3663
+ orgBus.emit({
3664
+ type: "memory_stored",
3665
+ agentId: record.agent_id,
3666
+ project: record.project_name,
3667
+ timestamp: record.timestamp
3668
+ });
3669
+ const MAX_PENDING = 1e3;
3670
+ if (_pendingRecords.length > MAX_PENDING) {
3671
+ const dropped = _pendingRecords.length - MAX_PENDING;
3672
+ _pendingRecords = _pendingRecords.slice(-MAX_PENDING);
3673
+ console.warn(`[store] Dropped ${dropped} oldest pending records (overflow)`);
3674
+ }
3675
+ if (_flushTimer === null) {
3676
+ _flushTimer = setInterval(() => {
3677
+ void flushBatch();
3678
+ }, _flushIntervalMs);
3679
+ if (_flushTimer && typeof _flushTimer === "object" && "unref" in _flushTimer) {
3680
+ _flushTimer.unref();
3681
+ }
3682
+ }
3683
+ if (_pendingRecords.length >= _batchSize) {
3684
+ await flushBatch();
3685
+ }
3686
+ }
3687
+ async function flushBatch() {
3688
+ if (_flushing || _pendingRecords.length === 0) return 0;
3689
+ _flushing = true;
3690
+ try {
3691
+ const batch = _pendingRecords.slice(0);
3692
+ const client = getClient();
3693
+ const vResult = await client.execute("SELECT MAX(version) as max_v FROM memories");
3694
+ let baseVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
3695
+ for (const row of batch) {
3696
+ row.version = baseVersion++;
3697
+ }
3698
+ _nextVersion = baseVersion;
3699
+ const buildStmt = (row) => {
3700
+ const hasVector = row.vector !== null;
3701
+ const taskId = row.task_id ?? null;
3702
+ const importance = row.importance ?? 5;
3703
+ const status = row.status ?? "active";
3704
+ const confidence = row.confidence ?? 0.7;
3705
+ const lastAccessed = row.last_accessed ?? row.timestamp;
3706
+ const workspaceId = row.workspace_id ?? null;
3707
+ const documentId = row.document_id ?? null;
3708
+ const userId = row.user_id ?? null;
3709
+ const charOffset = row.char_offset ?? null;
3710
+ const pageNumber = row.page_number ?? null;
3711
+ const sourcePath = row.source_path ?? null;
3712
+ const sourceType = row.source_type ?? null;
3713
+ const tier = row.tier ?? 3;
3714
+ const supersedesId = row.supersedes_id ?? null;
3715
+ const draft = row.draft ? 1 : 0;
3716
+ const memoryType = row.memory_type ?? "raw";
3717
+ const trajectory = row.trajectory ?? null;
3718
+ const contentHash = row.content_hash ?? null;
3719
+ const intent = row.intent ?? null;
3720
+ const outcome = row.outcome ?? null;
3721
+ const domain = row.domain ?? null;
3722
+ const referencedEntities = row.referenced_entities ?? null;
3723
+ const retrievalCount = row.retrieval_count ?? 0;
3724
+ const chainPosition = row.chain_position ?? null;
3725
+ const reviewStatus = row.review_status ?? null;
3726
+ const contextWindowPct = row.context_window_pct ?? null;
3727
+ const filePaths = row.file_paths ?? null;
3728
+ const commitHash = row.commit_hash ?? null;
3729
+ const durationMs = row.duration_ms ?? null;
3730
+ const tokenCost = row.token_cost ?? null;
3731
+ const audience = row.audience ?? null;
3732
+ const languageType = row.language_type ?? null;
3733
+ const parentMemoryId = row.parent_memory_id ?? null;
3734
+ const cols = `id, agent_id, agent_role, session_id, timestamp,
3735
+ tool_name, project_name,
3736
+ has_error, raw_text, vector, version, task_id, importance, status,
3737
+ confidence, last_accessed,
3738
+ workspace_id, document_id, user_id, char_offset, page_number,
3739
+ source_path, source_type, tier, supersedes_id, draft, memory_type, trajectory, content_hash,
3740
+ intent, outcome, domain, referenced_entities, retrieval_count,
3741
+ chain_position, review_status, context_window_pct, file_paths, commit_hash,
3742
+ duration_ms, token_cost, audience, language_type, parent_memory_id`;
3743
+ const metaArgs = [
3744
+ intent,
3745
+ outcome,
3746
+ domain,
3747
+ referencedEntities,
3748
+ retrievalCount,
3749
+ chainPosition,
3750
+ reviewStatus,
3751
+ contextWindowPct,
3752
+ filePaths,
3753
+ commitHash,
3754
+ durationMs,
3755
+ tokenCost,
3756
+ audience,
3757
+ languageType,
3758
+ parentMemoryId
3759
+ ];
3760
+ const baseArgs = [
3761
+ row.id,
3762
+ row.agent_id,
3763
+ row.agent_role,
3764
+ row.session_id,
3765
+ row.timestamp,
3766
+ row.tool_name,
3767
+ row.project_name,
3768
+ row.has_error,
3769
+ row.raw_text
3770
+ ];
3771
+ const sharedArgs = [
3772
+ row.version,
3773
+ taskId,
3774
+ importance,
3775
+ status,
3776
+ confidence,
3777
+ lastAccessed,
3778
+ workspaceId,
3779
+ documentId,
3780
+ userId,
3781
+ charOffset,
3782
+ pageNumber,
3783
+ sourcePath,
3784
+ sourceType,
3785
+ tier,
3786
+ supersedesId,
3787
+ draft,
3788
+ memoryType,
3789
+ trajectory,
3790
+ contentHash
3791
+ ];
3792
+ return {
3793
+ sql: hasVector ? `INSERT OR IGNORE INTO memories (${cols})
3794
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, vector32(?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` : `INSERT OR IGNORE INTO memories (${cols})
3795
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
3796
+ args: hasVector ? [...baseArgs, vectorToBlob(row.vector), ...sharedArgs, ...metaArgs] : [...baseArgs, ...sharedArgs, ...metaArgs]
3797
+ };
3798
+ };
3799
+ const globalClient = getClient();
3800
+ const globalStmts = batch.map(buildStmt);
3801
+ await globalClient.batch(globalStmts, "write");
3802
+ _pendingRecords.splice(0, batch.length);
3803
+ try {
3804
+ const { isShardingEnabled: isShardingEnabled2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
3805
+ if (isShardingEnabled2()) {
3806
+ const byProject = /* @__PURE__ */ new Map();
3807
+ for (const row of batch) {
3808
+ const proj = row.project_name || "unknown";
3809
+ if (!byProject.has(proj)) byProject.set(proj, []);
3810
+ byProject.get(proj).push(row);
3811
+ }
3812
+ for (const [project, rows] of byProject) {
3813
+ try {
3814
+ const shardClient = await getReadyShardClient2(project);
3815
+ const shardStmts = rows.map(buildStmt);
3816
+ await shardClient.batch(shardStmts, "write");
3817
+ } catch (err) {
3818
+ process.stderr.write(
3819
+ `[store] Shard write failed for ${project}: ${err instanceof Error ? err.message : String(err)}
3820
+ `
3821
+ );
3822
+ }
3823
+ }
3824
+ }
3825
+ } catch {
3826
+ }
3827
+ return batch.length;
3828
+ } finally {
3829
+ _flushing = false;
3830
+ }
3831
+ }
3832
+ function buildWikiScopeFilter(options, columnPrefix) {
3833
+ const args = [];
3834
+ let clause = "";
3835
+ if (options?.workspaceId !== void 0) {
3836
+ clause += ` AND ${columnPrefix}workspace_id = ?`;
3837
+ args.push(options.workspaceId);
3838
+ }
3839
+ if (options?.userId === void 0) {
3840
+ clause += ` AND ${columnPrefix}user_id IS NULL`;
3841
+ } else if (options.userId === null) {
3842
+ clause += ` AND ${columnPrefix}user_id IS NULL`;
3843
+ } else {
3844
+ clause += ` AND (${columnPrefix}user_id = ? OR ${columnPrefix}user_id IS NULL)`;
3845
+ args.push(options.userId);
3846
+ }
3847
+ return { clause, args };
3848
+ }
3849
+ function buildRawVisibilityFilter(options, columnPrefix) {
3850
+ if (options?.includeRaw === false) {
3851
+ return {
3852
+ clause: ` AND COALESCE(${columnPrefix}memory_type, 'raw') != 'raw'`,
3853
+ args: []
3854
+ };
3855
+ }
3856
+ return { clause: "", args: [] };
3857
+ }
3858
+ async function searchMemories(queryVector, agentId, options) {
3859
+ let client;
3860
+ try {
3861
+ const { isShardingEnabled: isShardingEnabled2, shardExists: shardExists2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
3862
+ if (isShardingEnabled2() && options?.projectName && shardExists2(options.projectName)) {
3863
+ client = await getReadyShardClient2(options.projectName);
3864
+ } else {
3865
+ client = getClient();
3866
+ }
3867
+ } catch {
3868
+ client = getClient();
3869
+ }
3870
+ const limit = options?.limit ?? 10;
3871
+ const statusFilter = options?.includeArchived ? "" : `
3872
+ AND COALESCE(status, 'active') = 'active'`;
3873
+ const draftFilter = options?.includeDrafts ? "" : `
3874
+ AND (draft = 0 OR draft IS NULL)`;
3875
+ let sql = `SELECT id, agent_id, agent_role, session_id, timestamp,
3876
+ tool_name, project_name,
3877
+ has_error, raw_text, vector, importance, status,
3878
+ confidence, last_accessed,
3879
+ workspace_id, document_id, user_id,
3880
+ char_offset, page_number,
3881
+ source_path, source_type
3882
+ FROM memories
3883
+ WHERE agent_id = ?
3884
+ AND vector IS NOT NULL${statusFilter}${draftFilter}
3885
+ AND COALESCE(confidence, 0.7) >= 0.3`;
3886
+ const args = [agentId];
3887
+ const scope = buildWikiScopeFilter(options, "");
3888
+ sql += scope.clause;
3889
+ args.push(...scope.args);
3890
+ const rawVisibility = buildRawVisibilityFilter(options, "");
3891
+ sql += rawVisibility.clause;
3892
+ args.push(...rawVisibility.args);
3893
+ if (options?.projectName) {
3894
+ sql += ` AND project_name = ?`;
3895
+ args.push(options.projectName);
3896
+ }
3897
+ if (options?.toolName) {
3898
+ sql += ` AND tool_name = ?`;
3899
+ args.push(options.toolName);
3900
+ }
3901
+ if (options?.hasError !== void 0) {
3902
+ sql += ` AND has_error = ?`;
3903
+ args.push(options.hasError ? 1 : 0);
3904
+ }
3905
+ if (options?.since) {
3906
+ sql += ` AND timestamp >= ?`;
3907
+ args.push(options.since);
3908
+ }
3909
+ if (options?.memoryType) {
3910
+ sql += ` AND memory_type = ?`;
3911
+ args.push(options.memoryType);
3912
+ }
3913
+ sql += ` ORDER BY vector_distance_cos(vector, vector32(?))`;
3914
+ args.push(vectorToBlob(queryVector));
3915
+ sql += ` LIMIT ?`;
3916
+ args.push(limit);
3917
+ const result = await client.execute({ sql, args });
3918
+ return result.rows.map((row) => ({
3919
+ id: row.id,
3920
+ agent_id: row.agent_id,
3921
+ agent_role: row.agent_role,
3922
+ session_id: row.session_id,
3923
+ timestamp: row.timestamp,
3924
+ tool_name: row.tool_name,
3925
+ project_name: row.project_name,
3926
+ has_error: row.has_error === 1,
3927
+ raw_text: row.raw_text,
3928
+ vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
3929
+ importance: row.importance ?? 5,
3930
+ status: row.status ?? "active",
3931
+ confidence: row.confidence ?? 0.7,
3932
+ last_accessed: row.last_accessed ?? row.timestamp,
3933
+ workspace_id: row.workspace_id ?? null,
3934
+ document_id: row.document_id ?? null,
3935
+ user_id: row.user_id ?? null,
3936
+ char_offset: row.char_offset ?? null,
3937
+ page_number: row.page_number ?? null,
3938
+ source_path: row.source_path ?? null,
3939
+ source_type: row.source_type ?? null
3940
+ }));
3941
+ }
3942
+ async function attachDocumentMetadata(records) {
3943
+ const docIds = [
3944
+ ...new Set(
3945
+ records.map((r) => r.document_id).filter((id) => typeof id === "string" && id.length > 0)
3946
+ )
3947
+ ];
3948
+ if (docIds.length === 0) return records;
3949
+ try {
3950
+ const client = getClient();
3951
+ const placeholders = docIds.map(() => "?").join(",");
3952
+ const result = await client.execute({
3953
+ sql: `SELECT id, filename, mime, source_type, uploaded_at
3954
+ FROM documents
3955
+ WHERE id IN (${placeholders})`,
3956
+ args: docIds
3957
+ });
3958
+ const byId = /* @__PURE__ */ new Map();
3959
+ for (const row of result.rows) {
3960
+ const id = row.id;
3961
+ byId.set(id, {
3962
+ document_id: id,
3963
+ filename: row.filename,
3964
+ mime: row.mime ?? null,
3965
+ source_type: row.source_type ?? null,
3966
+ uploaded_at: row.uploaded_at
3967
+ });
3968
+ }
3969
+ for (const record of records) {
3970
+ if (!record.document_id) continue;
3971
+ record.document_metadata = byId.get(record.document_id) ?? null;
3972
+ }
3973
+ } catch {
3974
+ }
3975
+ return records;
3976
+ }
3977
+ async function flushTier3(agentId, options) {
3978
+ const client = getClient();
3979
+ const maxAge = options?.maxAgeHours ?? 72;
3980
+ const cutoff = new Date(Date.now() - maxAge * 36e5).toISOString();
3981
+ if (options?.dryRun) {
3982
+ const result2 = await client.execute({
3983
+ sql: `SELECT COUNT(*) as cnt FROM memories
3984
+ WHERE agent_id = ? AND tier = 3 AND status = 'active' AND timestamp < ?`,
3985
+ args: [agentId, cutoff]
3986
+ });
3987
+ return { archived: Number(result2.rows[0]?.cnt ?? 0) };
3988
+ }
3989
+ const result = await client.execute({
3990
+ sql: `UPDATE memories SET status = 'archived'
3991
+ WHERE agent_id = ? AND tier = 3 AND status = 'active' AND timestamp < ?`,
3992
+ args: [agentId, cutoff]
3993
+ });
3994
+ return { archived: result.rowsAffected };
3995
+ }
3996
+ async function disposeStore() {
3997
+ if (_flushTimer !== null) {
3998
+ clearInterval(_flushTimer);
3999
+ _flushTimer = null;
4000
+ }
4001
+ if (_pendingRecords.length > 0) {
4002
+ await flushBatch();
4003
+ }
4004
+ await disposeTurso();
4005
+ _pendingRecords = [];
4006
+ _nextVersion = 1;
4007
+ }
4008
+ function vectorToBlob(vector) {
4009
+ const f32 = vector instanceof Float32Array ? vector : new Float32Array(vector);
4010
+ return JSON.stringify(Array.from(f32));
4011
+ }
4012
+ async function updateMemoryStatus(id, status) {
4013
+ const client = getClient();
4014
+ await client.execute({
4015
+ sql: `UPDATE memories SET status = ? WHERE id = ?`,
4016
+ args: [status, id]
4017
+ });
4018
+ }
4019
+ function reserveVersions(count) {
4020
+ const reserved = [];
4021
+ for (let i = 0; i < count; i++) {
4022
+ reserved.push(_nextVersion++);
4023
+ }
4024
+ return reserved;
4025
+ }
4026
+ async function getMemoryCardinality(agentId) {
4027
+ try {
4028
+ const client = getClient();
4029
+ const result = await client.execute({
4030
+ sql: `SELECT COUNT(*) as cnt FROM memories WHERE agent_id = ? AND COALESCE(status, 'active') = 'active'`,
4031
+ args: [agentId]
4032
+ });
4033
+ return Number(result.rows[0]?.cnt) || 0;
4034
+ } catch {
4035
+ return 0;
4036
+ }
4037
+ }
4038
+ var INIT_MAX_RETRIES, INIT_RETRY_DELAY_MS, _pendingRecords, _batchSize, _flushIntervalMs, _flushTimer, _flushing, _nextVersion;
4039
+ var init_store = __esm({
4040
+ "src/lib/store.ts"() {
4041
+ "use strict";
4042
+ init_memory();
4043
+ init_database();
4044
+ init_keychain();
4045
+ init_config();
4046
+ init_state_bus();
4047
+ INIT_MAX_RETRIES = 3;
4048
+ INIT_RETRY_DELAY_MS = 1e3;
4049
+ _pendingRecords = [];
4050
+ _batchSize = 20;
4051
+ _flushIntervalMs = 1e4;
4052
+ _flushTimer = null;
4053
+ _flushing = false;
4054
+ _nextVersion = 1;
4055
+ }
4056
+ });
4057
+
4058
+ // src/bin/exe-team.ts
4059
+ init_employees();
4060
+
4061
+ // src/bin/fast-db-init.ts
4062
+ async function fastDbInit() {
4063
+ const { isInitialized: isInitialized2, getClient: getClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
4064
+ if (isInitialized2()) {
4065
+ return getClient2();
4066
+ }
4067
+ try {
4068
+ const { connectEmbedDaemon: connectEmbedDaemon2, sendDaemonRequest: sendDaemonRequest2, isClientConnected: isClientConnected2 } = await Promise.resolve().then(() => (init_exe_daemon_client(), exe_daemon_client_exports));
4069
+ const { deserializeResultSet: deserializeResultSet2 } = await Promise.resolve().then(() => (init_daemon_protocol(), daemon_protocol_exports));
4070
+ await connectEmbedDaemon2();
4071
+ if (isClientConnected2()) {
4072
+ const daemonClient = {
4073
+ async execute(stmt) {
4074
+ const sql = typeof stmt === "string" ? stmt : stmt.sql;
4075
+ const args = typeof stmt === "string" ? [] : Array.isArray(stmt.args) ? stmt.args : [];
4076
+ const resp = await sendDaemonRequest2({ type: "db-execute", sql, args });
4077
+ if (resp.error) throw new Error(String(resp.error));
4078
+ if (resp.db) return deserializeResultSet2(resp.db);
4079
+ throw new Error("Unexpected daemon response");
4080
+ },
4081
+ async batch(stmts, mode) {
4082
+ const statements = stmts.map((s) => {
4083
+ const sql = typeof s === "string" ? s : s.sql;
4084
+ const args = typeof s === "string" ? [] : Array.isArray(s.args) ? s.args : [];
4085
+ return { sql, args };
4086
+ });
4087
+ const resp = await sendDaemonRequest2({ type: "db-batch", statements, mode: mode ?? "deferred" });
4088
+ if (resp.error) throw new Error(String(resp.error));
4089
+ const batchResults = resp["db-batch"];
4090
+ if (batchResults) return batchResults.map(deserializeResultSet2);
4091
+ throw new Error("Unexpected daemon batch response");
4092
+ },
4093
+ async transaction(_mode) {
4094
+ throw new Error("Transactions not supported via daemon socket");
4095
+ },
4096
+ async executeMultiple(_sql) {
4097
+ throw new Error("executeMultiple not supported via daemon socket");
4098
+ },
4099
+ async migrate(_stmts) {
4100
+ throw new Error("migrate not supported via daemon socket");
4101
+ },
4102
+ sync() {
4103
+ return Promise.resolve(void 0);
4104
+ },
4105
+ close() {
4106
+ },
4107
+ get closed() {
4108
+ return false;
4109
+ },
4110
+ get protocol() {
4111
+ return "file";
4112
+ }
4113
+ };
4114
+ return daemonClient;
4115
+ }
4116
+ } catch {
4117
+ }
4118
+ const { initStore: initStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
4119
+ await initStore2({ lightweight: true });
4120
+ return getClient2();
4121
+ }
2664
4122
 
2665
4123
  // src/bin/exe-team.ts
2666
4124
  init_database();
2667
4125
 
2668
4126
  // src/lib/is-main.ts
2669
4127
  import { realpathSync } from "fs";
2670
- import { fileURLToPath } from "url";
4128
+ import { fileURLToPath as fileURLToPath2 } from "url";
2671
4129
  function isMainModule(importMetaUrl) {
2672
4130
  if (process.argv[1] == null) return false;
2673
4131
  if (process.argv[1].includes("mcp/server")) return false;
2674
4132
  try {
2675
4133
  const scriptPath = realpathSync(process.argv[1]);
2676
- const modulePath = realpathSync(fileURLToPath(importMetaUrl));
4134
+ const modulePath = realpathSync(fileURLToPath2(importMetaUrl));
2677
4135
  return scriptPath === modulePath;
2678
4136
  } catch {
2679
4137
  return importMetaUrl === `file://${process.argv[1]}` || importMetaUrl === new URL(process.argv[1], "file://").href;
@@ -2689,7 +4147,7 @@ async function main() {
2689
4147
  );
2690
4148
  return;
2691
4149
  }
2692
- await initStore();
4150
+ await fastDbInit();
2693
4151
  const client = getClient();
2694
4152
  const counts = /* @__PURE__ */ new Map();
2695
4153
  let totalMemories = 0;