@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
@@ -2,6 +2,12 @@ var __defProp = Object.defineProperty;
2
2
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
3
  var __getOwnPropNames = Object.getOwnPropertyNames;
4
4
  var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
6
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
7
+ }) : x)(function(x) {
8
+ if (typeof require !== "undefined") return require.apply(this, arguments);
9
+ throw Error('Dynamic require of "' + x + '" is not supported');
10
+ });
5
11
  var __esm = (fn, res) => function __init() {
6
12
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
7
13
  };
@@ -68,9 +74,9 @@ var MAX_RETRIES, BASE_DELAY_MS, MAX_JITTER_MS;
68
74
  var init_db_retry = __esm({
69
75
  "src/lib/db-retry.ts"() {
70
76
  "use strict";
71
- MAX_RETRIES = 3;
72
- BASE_DELAY_MS = 200;
73
- MAX_JITTER_MS = 300;
77
+ MAX_RETRIES = 5;
78
+ BASE_DELAY_MS = 250;
79
+ MAX_JITTER_MS = 400;
74
80
  }
75
81
  });
76
82
 
@@ -84,12 +90,25 @@ async function ensurePrivateDir(dirPath) {
84
90
  } catch {
85
91
  }
86
92
  }
93
+ function ensurePrivateDirSync(dirPath) {
94
+ mkdirSync(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
95
+ try {
96
+ chmodSync(dirPath, PRIVATE_DIR_MODE);
97
+ } catch {
98
+ }
99
+ }
87
100
  async function enforcePrivateFile(filePath) {
88
101
  try {
89
102
  await chmod(filePath, PRIVATE_FILE_MODE);
90
103
  } catch {
91
104
  }
92
105
  }
106
+ function enforcePrivateFileSync(filePath) {
107
+ try {
108
+ if (existsSync(filePath)) chmodSync(filePath, PRIVATE_FILE_MODE);
109
+ } catch {
110
+ }
111
+ }
93
112
  var PRIVATE_DIR_MODE, PRIVATE_FILE_MODE;
94
113
  var init_secure_files = __esm({
95
114
  "src/lib/secure-files.ts"() {
@@ -906,456 +925,1237 @@ var init_database_adapter = __esm({
906
925
  }
907
926
  });
908
927
 
909
- // src/lib/database.ts
910
- import { createClient } from "@libsql/client";
911
- async function initDatabase(config) {
912
- if (_walCheckpointTimer) {
913
- clearInterval(_walCheckpointTimer);
914
- _walCheckpointTimer = null;
928
+ // src/types/memory.ts
929
+ var EMBEDDING_DIM;
930
+ var init_memory = __esm({
931
+ "src/types/memory.ts"() {
932
+ "use strict";
933
+ EMBEDDING_DIM = 1024;
915
934
  }
916
- if (_daemonClient) {
917
- _daemonClient.close();
918
- _daemonClient = null;
935
+ });
936
+
937
+ // src/lib/daemon-auth.ts
938
+ import crypto from "crypto";
939
+ import path4 from "path";
940
+ import { existsSync as existsSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
941
+ function normalizeToken(token) {
942
+ if (!token) return null;
943
+ const trimmed = token.trim();
944
+ return trimmed.length > 0 ? trimmed : null;
945
+ }
946
+ function readDaemonToken() {
947
+ try {
948
+ if (!existsSync4(DAEMON_TOKEN_PATH)) return null;
949
+ return normalizeToken(readFileSync3(DAEMON_TOKEN_PATH, "utf8"));
950
+ } catch {
951
+ return null;
919
952
  }
920
- if (_adapterClient && _adapterClient !== _resilientClient) {
921
- _adapterClient.close();
953
+ }
954
+ function ensureDaemonToken(seed) {
955
+ const existing = readDaemonToken();
956
+ if (existing) return existing;
957
+ const token = normalizeToken(seed) ?? crypto.randomBytes(32).toString("hex");
958
+ ensurePrivateDirSync(EXE_AI_DIR);
959
+ writeFileSync2(DAEMON_TOKEN_PATH, `${token}
960
+ `, "utf8");
961
+ enforcePrivateFileSync(DAEMON_TOKEN_PATH);
962
+ return token;
963
+ }
964
+ var DAEMON_TOKEN_PATH;
965
+ var init_daemon_auth = __esm({
966
+ "src/lib/daemon-auth.ts"() {
967
+ "use strict";
968
+ init_config();
969
+ init_secure_files();
970
+ DAEMON_TOKEN_PATH = path4.join(EXE_AI_DIR, "exed.token");
922
971
  }
923
- _adapterClient = null;
924
- if (_client) {
925
- _client.close();
926
- _client = null;
927
- _resilientClient = null;
972
+ });
973
+
974
+ // src/lib/exe-daemon-client.ts
975
+ var exe_daemon_client_exports = {};
976
+ __export(exe_daemon_client_exports, {
977
+ connectEmbedDaemon: () => connectEmbedDaemon,
978
+ disconnectClient: () => disconnectClient,
979
+ embedBatchViaClient: () => embedBatchViaClient,
980
+ embedViaClient: () => embedViaClient,
981
+ isClientConnected: () => isClientConnected,
982
+ pingDaemon: () => pingDaemon,
983
+ sendDaemonRequest: () => sendDaemonRequest,
984
+ sendIngestRequest: () => sendIngestRequest
985
+ });
986
+ import net from "net";
987
+ import os4 from "os";
988
+ import { spawn } from "child_process";
989
+ import { randomUUID } from "crypto";
990
+ import { existsSync as existsSync5, unlinkSync as unlinkSync2, readFileSync as readFileSync4, openSync, closeSync, statSync } from "fs";
991
+ import path5 from "path";
992
+ import { fileURLToPath } from "url";
993
+ function handleData(chunk) {
994
+ _buffer += chunk.toString();
995
+ if (_buffer.length > MAX_BUFFER) {
996
+ _buffer = "";
997
+ return;
998
+ }
999
+ let newlineIdx;
1000
+ while ((newlineIdx = _buffer.indexOf("\n")) !== -1) {
1001
+ const line = _buffer.slice(0, newlineIdx).trim();
1002
+ _buffer = _buffer.slice(newlineIdx + 1);
1003
+ if (!line) continue;
1004
+ try {
1005
+ const response = JSON.parse(line);
1006
+ const id = response.id;
1007
+ if (!id) continue;
1008
+ const entry = _pending.get(id);
1009
+ if (entry) {
1010
+ clearTimeout(entry.timer);
1011
+ _pending.delete(id);
1012
+ entry.resolve(response);
1013
+ }
1014
+ } catch {
1015
+ }
928
1016
  }
929
- const opts = {
930
- url: `file:${config.dbPath}`
931
- };
932
- if (config.encryptionKey) {
933
- opts.encryptionKey = config.encryptionKey;
1017
+ }
1018
+ function cleanupStaleFiles() {
1019
+ if (existsSync5(PID_PATH)) {
1020
+ try {
1021
+ const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
1022
+ if (pid > 0) {
1023
+ try {
1024
+ process.kill(pid, 0);
1025
+ return;
1026
+ } catch {
1027
+ }
1028
+ }
1029
+ } catch {
1030
+ }
1031
+ try {
1032
+ unlinkSync2(PID_PATH);
1033
+ } catch {
1034
+ }
1035
+ try {
1036
+ unlinkSync2(SOCKET_PATH);
1037
+ } catch {
1038
+ }
934
1039
  }
935
- _client = createClient(opts);
936
- _resilientClient = wrapWithRetry(_client);
937
- _adapterClient = _resilientClient;
938
- _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
939
- });
940
- _client.execute("PRAGMA journal_mode = WAL").catch(() => {
941
- });
942
- if (_walCheckpointTimer) clearInterval(_walCheckpointTimer);
943
- _walCheckpointTimer = setInterval(() => {
944
- _client?.execute("PRAGMA wal_checkpoint(PASSIVE)").catch(() => {
945
- });
946
- }, 3e4);
947
- _walCheckpointTimer.unref();
948
- if (process.env.DATABASE_URL) {
949
- _adapterClient = await createPrismaDbAdapter(_resilientClient);
1040
+ }
1041
+ function findPackageRoot() {
1042
+ let dir = path5.dirname(fileURLToPath(import.meta.url));
1043
+ const { root } = path5.parse(dir);
1044
+ while (dir !== root) {
1045
+ if (existsSync5(path5.join(dir, "package.json"))) return dir;
1046
+ dir = path5.dirname(dir);
950
1047
  }
1048
+ return null;
951
1049
  }
952
- function getClient() {
953
- if (!_adapterClient) {
954
- throw new Error("Database client not initialized. Call initDatabase() first.");
1050
+ function getAvailableMemoryGB() {
1051
+ if (process.platform === "darwin") {
1052
+ try {
1053
+ const { execSync: execSync4 } = __require("child_process");
1054
+ const vmstat = execSync4("vm_stat", { encoding: "utf8" });
1055
+ const pageSize = 16384;
1056
+ const pageSizeMatch = vmstat.match(/page size of (\d+) bytes/);
1057
+ const actualPageSize = pageSizeMatch ? parseInt(pageSizeMatch[1], 10) : pageSize;
1058
+ const free = vmstat.match(/Pages free:\s+(\d+)/);
1059
+ const inactive = vmstat.match(/Pages inactive:\s+(\d+)/);
1060
+ const speculative = vmstat.match(/Pages speculative:\s+(\d+)/);
1061
+ const freePages = free ? parseInt(free[1], 10) : 0;
1062
+ const inactivePages = inactive ? parseInt(inactive[1], 10) : 0;
1063
+ const speculativePages = speculative ? parseInt(speculative[1], 10) : 0;
1064
+ return (freePages + inactivePages + speculativePages) * actualPageSize / (1024 * 1024 * 1024);
1065
+ } catch {
1066
+ return os4.freemem() / (1024 * 1024 * 1024);
1067
+ }
955
1068
  }
956
- if (process.env.DATABASE_URL) {
957
- return _adapterClient;
1069
+ return os4.freemem() / (1024 * 1024 * 1024);
1070
+ }
1071
+ function spawnDaemon() {
1072
+ const freeGB = getAvailableMemoryGB();
1073
+ const totalGB = os4.totalmem() / (1024 * 1024 * 1024);
1074
+ if (totalGB <= 8) {
1075
+ process.stderr.write(
1076
+ `[exed-client] SKIP: ${totalGB.toFixed(0)}GB system \u2014 embedding daemon disabled. Using keyword search only. Minimum 16GB recommended for vector search.
1077
+ `
1078
+ );
1079
+ return;
958
1080
  }
959
- if (process.env.EXE_IS_DAEMON === "1") {
960
- return _resilientClient;
1081
+ if (totalGB <= 16 && freeGB < 2) {
1082
+ process.stderr.write(
1083
+ `[exed-client] SKIP: low memory (${freeGB.toFixed(1)}GB available / ${totalGB.toFixed(0)}GB total). Embedding daemon not started \u2014 using keyword search only.
1084
+ `
1085
+ );
1086
+ return;
961
1087
  }
962
- if (_daemonClient && _daemonClient._isDaemonActive()) {
963
- return _daemonClient;
1088
+ const pkgRoot = findPackageRoot();
1089
+ if (!pkgRoot) {
1090
+ process.stderr.write("[exed-client] WARN: cannot find package root\n");
1091
+ return;
964
1092
  }
965
- return _resilientClient;
966
- }
967
- function getRawClient() {
968
- if (!_client) {
969
- throw new Error("Database client not initialized. Call initDatabase() first.");
1093
+ const daemonPath = path5.join(pkgRoot, "dist", "lib", "exe-daemon.js");
1094
+ if (!existsSync5(daemonPath)) {
1095
+ process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
1096
+ `);
1097
+ return;
970
1098
  }
971
- return _client;
972
- }
973
- async function ensureSchema() {
974
- const client = getRawClient();
975
- await client.execute("PRAGMA journal_mode = WAL");
976
- await client.execute("PRAGMA busy_timeout = 30000");
977
- await client.execute("PRAGMA wal_autocheckpoint = 1000");
1099
+ const resolvedPath = daemonPath;
1100
+ const daemonToken = ensureDaemonToken(process.env[DAEMON_TOKEN_ENV] ?? null);
1101
+ process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
1102
+ `);
1103
+ const logPath = path5.join(path5.dirname(SOCKET_PATH), "exed.log");
1104
+ let stderrFd = "ignore";
978
1105
  try {
979
- await client.execute("PRAGMA libsql_vector_search_ef = 128");
1106
+ stderrFd = openSync(logPath, "a");
980
1107
  } catch {
981
1108
  }
982
- await client.executeMultiple(`
983
- CREATE TABLE IF NOT EXISTS memories (
984
- id TEXT PRIMARY KEY,
985
- agent_id TEXT NOT NULL,
986
- agent_role TEXT NOT NULL,
987
- session_id TEXT NOT NULL,
988
- timestamp TEXT NOT NULL,
989
- tool_name TEXT NOT NULL,
990
- project_name TEXT NOT NULL,
991
- has_error INTEGER NOT NULL DEFAULT 0,
992
- raw_text TEXT NOT NULL,
993
- vector F32_BLOB(1024),
994
- version INTEGER NOT NULL DEFAULT 0
995
- );
996
-
997
- CREATE INDEX IF NOT EXISTS idx_memories_agent
998
- ON memories(agent_id);
999
-
1000
- CREATE INDEX IF NOT EXISTS idx_memories_timestamp
1001
- ON memories(timestamp);
1002
-
1003
- CREATE INDEX IF NOT EXISTS idx_memories_session
1004
- ON memories(session_id);
1005
-
1006
- CREATE INDEX IF NOT EXISTS idx_memories_project
1007
- ON memories(project_name);
1008
-
1009
- CREATE INDEX IF NOT EXISTS idx_memories_tool
1010
- ON memories(tool_name);
1011
-
1012
- CREATE INDEX IF NOT EXISTS idx_memories_version
1013
- ON memories(version);
1014
-
1015
- CREATE INDEX IF NOT EXISTS idx_memories_agent_project
1016
- ON memories(agent_id, project_name);
1017
- `);
1018
- await client.executeMultiple(`
1019
- CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
1020
- raw_text,
1021
- content='memories',
1022
- content_rowid='rowid'
1023
- );
1024
-
1025
- CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
1026
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1027
- END;
1028
-
1029
- CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
1030
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1031
- END;
1032
-
1033
- CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
1034
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1035
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1036
- END;
1037
- `);
1038
- await client.executeMultiple(`
1039
- CREATE TABLE IF NOT EXISTS sync_meta (
1040
- key TEXT PRIMARY KEY,
1041
- value TEXT NOT NULL
1042
- );
1043
- `);
1044
- await client.executeMultiple(`
1045
- CREATE TABLE IF NOT EXISTS tasks (
1046
- id TEXT PRIMARY KEY,
1047
- title TEXT NOT NULL,
1048
- assigned_to TEXT NOT NULL,
1049
- assigned_by TEXT NOT NULL,
1050
- project_name TEXT NOT NULL,
1051
- priority TEXT NOT NULL DEFAULT 'p1',
1052
- status TEXT NOT NULL DEFAULT 'open',
1053
- task_file TEXT,
1054
- created_at TEXT NOT NULL,
1055
- updated_at TEXT NOT NULL
1056
- );
1057
-
1058
- CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
1059
- ON tasks(assigned_to, status);
1060
- `);
1061
- await client.executeMultiple(`
1062
- CREATE TABLE IF NOT EXISTS behaviors (
1063
- id TEXT PRIMARY KEY,
1064
- agent_id TEXT NOT NULL,
1065
- project_name TEXT,
1066
- domain TEXT,
1067
- content TEXT NOT NULL,
1068
- active INTEGER NOT NULL DEFAULT 1,
1069
- created_at TEXT NOT NULL,
1070
- updated_at TEXT NOT NULL
1071
- );
1072
-
1073
- CREATE INDEX IF NOT EXISTS idx_behaviors_agent
1074
- ON behaviors(agent_id, active);
1075
- `);
1109
+ const heapCapMB = totalGB <= 8 ? 256 : 512;
1110
+ const nodeArgs = [`--max-old-space-size=${heapCapMB}`, resolvedPath];
1111
+ const child = spawn(process.execPath, nodeArgs, {
1112
+ detached: true,
1113
+ stdio: ["ignore", "ignore", stderrFd],
1114
+ env: {
1115
+ ...process.env,
1116
+ TMUX: void 0,
1117
+ // Daemon is global — must not inherit session scope
1118
+ TMUX_PANE: void 0,
1119
+ // Prevents resolveExeSession() from scoping to one session
1120
+ EXE_DAEMON_SOCK: SOCKET_PATH,
1121
+ EXE_DAEMON_PID: PID_PATH,
1122
+ [DAEMON_TOKEN_ENV]: daemonToken
1123
+ }
1124
+ });
1125
+ child.unref();
1126
+ if (typeof stderrFd === "number") {
1127
+ try {
1128
+ closeSync(stderrFd);
1129
+ } catch {
1130
+ }
1131
+ }
1132
+ }
1133
+ function acquireSpawnLock() {
1076
1134
  try {
1077
- const coordinatorName = getCoordinatorName();
1078
- const existing = await client.execute({
1079
- sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = ?",
1080
- args: [coordinatorName]
1081
- });
1082
- if (Number(existing.rows[0]?.cnt) === 0) {
1083
- const seededAt = "2026-03-25T00:00:00Z";
1084
- for (const [domain, content] of [
1085
- ["workflow", `Don't ask "keep going?" \u2014 just keep executing phases/plans autonomously`],
1086
- ["tool-use", "Always use create_task MCP tool, never write .md files directly for task creation"],
1087
- ["workflow", "Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission"]
1088
- ]) {
1089
- await client.execute({
1090
- sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
1091
- VALUES (hex(randomblob(16)), ?, NULL, ?, ?, 1, ?, ?)`,
1092
- args: [coordinatorName, domain, content, seededAt, seededAt]
1093
- });
1135
+ const fd = openSync(SPAWN_LOCK_PATH, "wx");
1136
+ closeSync(fd);
1137
+ return true;
1138
+ } catch {
1139
+ try {
1140
+ const stat = statSync(SPAWN_LOCK_PATH);
1141
+ if (Date.now() - stat.mtimeMs > SPAWN_LOCK_STALE_MS) {
1142
+ try {
1143
+ unlinkSync2(SPAWN_LOCK_PATH);
1144
+ } catch {
1145
+ }
1146
+ try {
1147
+ const fd = openSync(SPAWN_LOCK_PATH, "wx");
1148
+ closeSync(fd);
1149
+ return true;
1150
+ } catch {
1151
+ }
1094
1152
  }
1153
+ } catch {
1095
1154
  }
1096
- } catch {
1155
+ return false;
1097
1156
  }
1157
+ }
1158
+ function releaseSpawnLock() {
1098
1159
  try {
1099
- await client.execute({
1100
- sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
1101
- args: []
1102
- });
1160
+ unlinkSync2(SPAWN_LOCK_PATH);
1103
1161
  } catch {
1104
1162
  }
1105
- try {
1106
- await client.execute({
1107
- sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
1108
- args: []
1163
+ }
1164
+ function connectToSocket() {
1165
+ return new Promise((resolve) => {
1166
+ if (_socket && _connected) {
1167
+ resolve(true);
1168
+ return;
1169
+ }
1170
+ const socket = net.createConnection({ path: SOCKET_PATH });
1171
+ const connectTimeout = setTimeout(() => {
1172
+ socket.destroy();
1173
+ resolve(false);
1174
+ }, 2e3);
1175
+ socket.on("connect", () => {
1176
+ clearTimeout(connectTimeout);
1177
+ _socket = socket;
1178
+ _connected = true;
1179
+ _buffer = "";
1180
+ socket.on("data", handleData);
1181
+ socket.on("close", () => {
1182
+ _connected = false;
1183
+ _socket = null;
1184
+ for (const [id, entry] of _pending) {
1185
+ clearTimeout(entry.timer);
1186
+ _pending.delete(id);
1187
+ entry.resolve({ error: "Connection closed" });
1188
+ }
1189
+ });
1190
+ socket.on("error", () => {
1191
+ _connected = false;
1192
+ _socket = null;
1193
+ });
1194
+ resolve(true);
1109
1195
  });
1110
- } catch {
1111
- }
1112
- try {
1113
- await client.execute({
1114
- sql: `ALTER TABLE tasks ADD COLUMN parent_task_id TEXT`,
1115
- args: []
1196
+ socket.on("error", () => {
1197
+ clearTimeout(connectTimeout);
1198
+ resolve(false);
1116
1199
  });
1117
- } catch {
1200
+ });
1201
+ }
1202
+ async function connectEmbedDaemon() {
1203
+ if (_socket && _connected) return true;
1204
+ if (await connectToSocket()) return true;
1205
+ if (acquireSpawnLock()) {
1206
+ try {
1207
+ cleanupStaleFiles();
1208
+ spawnDaemon();
1209
+ } finally {
1210
+ releaseSpawnLock();
1211
+ }
1118
1212
  }
1119
- try {
1120
- await client.execute({
1121
- sql: `CREATE INDEX IF NOT EXISTS idx_tasks_parent_task_id
1122
- ON tasks(parent_task_id)
1123
- WHERE parent_task_id IS NOT NULL`,
1124
- args: []
1125
- });
1126
- } catch {
1213
+ const start = Date.now();
1214
+ let delay2 = 100;
1215
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1216
+ await new Promise((r) => setTimeout(r, delay2));
1217
+ if (await connectToSocket()) return true;
1218
+ delay2 = Math.min(delay2 * 2, 3e3);
1127
1219
  }
1128
- try {
1129
- await client.execute({
1130
- sql: `UPDATE tasks SET status = 'done' WHERE status = 'completed'`,
1131
- args: []
1132
- });
1133
- } catch {
1220
+ return false;
1221
+ }
1222
+ function sendRequest(texts, priority) {
1223
+ return sendDaemonRequest({ texts, priority });
1224
+ }
1225
+ function sendDaemonRequest(payload, timeoutMs = REQUEST_TIMEOUT_MS) {
1226
+ return new Promise((resolve) => {
1227
+ if (!_socket || !_connected) {
1228
+ resolve({ error: "Not connected" });
1229
+ return;
1230
+ }
1231
+ const id = randomUUID();
1232
+ const token = process.env[DAEMON_TOKEN_ENV] ?? readDaemonToken();
1233
+ const timer = setTimeout(() => {
1234
+ _pending.delete(id);
1235
+ resolve({ error: "Request timeout" });
1236
+ }, timeoutMs);
1237
+ _pending.set(id, { resolve, timer });
1238
+ try {
1239
+ _socket.write(JSON.stringify({ id, token, ...payload }) + "\n");
1240
+ } catch {
1241
+ clearTimeout(timer);
1242
+ _pending.delete(id);
1243
+ resolve({ error: "Write failed" });
1244
+ }
1245
+ });
1246
+ }
1247
+ async function pingDaemon() {
1248
+ if (!_socket || !_connected) return null;
1249
+ const response = await sendDaemonRequest({ type: "health" }, 5e3);
1250
+ if (response.health) {
1251
+ return response.health;
1134
1252
  }
1135
- try {
1136
- await client.execute({
1137
- sql: `ALTER TABLE tasks ADD COLUMN reviewer TEXT`,
1138
- args: []
1139
- });
1140
- } catch {
1253
+ return null;
1254
+ }
1255
+ function killAndRespawnDaemon() {
1256
+ if (!acquireSpawnLock()) {
1257
+ process.stderr.write("[exed-client] Another process is already restarting daemon \u2014 skipping\n");
1258
+ if (_socket) {
1259
+ _socket.destroy();
1260
+ _socket = null;
1261
+ }
1262
+ _connected = false;
1263
+ _buffer = "";
1264
+ return;
1141
1265
  }
1142
1266
  try {
1143
- await client.execute({
1144
- sql: `ALTER TABLE tasks ADD COLUMN context TEXT`,
1145
- args: []
1146
- });
1147
- } catch {
1267
+ process.stderr.write("[exed-client] Killing daemon for restart...\n");
1268
+ if (existsSync5(PID_PATH)) {
1269
+ try {
1270
+ const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
1271
+ if (pid > 0) {
1272
+ try {
1273
+ process.kill(pid, "SIGKILL");
1274
+ } catch {
1275
+ }
1276
+ }
1277
+ } catch {
1278
+ }
1279
+ }
1280
+ if (_socket) {
1281
+ _socket.destroy();
1282
+ _socket = null;
1283
+ }
1284
+ _connected = false;
1285
+ _buffer = "";
1286
+ try {
1287
+ unlinkSync2(PID_PATH);
1288
+ } catch {
1289
+ }
1290
+ try {
1291
+ unlinkSync2(SOCKET_PATH);
1292
+ } catch {
1293
+ }
1294
+ spawnDaemon();
1295
+ } finally {
1296
+ releaseSpawnLock();
1148
1297
  }
1298
+ }
1299
+ function isDaemonTooYoung() {
1149
1300
  try {
1150
- await client.execute({
1151
- sql: `ALTER TABLE tasks ADD COLUMN result TEXT`,
1152
- args: []
1153
- });
1301
+ const stat = statSync(PID_PATH);
1302
+ return Date.now() - stat.mtimeMs < MIN_DAEMON_AGE_MS;
1154
1303
  } catch {
1304
+ return false;
1155
1305
  }
1156
- try {
1157
- await client.execute({
1158
- sql: `ALTER TABLE tasks ADD COLUMN assigned_tmux TEXT`,
1159
- args: []
1160
- });
1161
- } catch {
1306
+ }
1307
+ async function retryThenRestart(doRequest, label) {
1308
+ const result = await doRequest();
1309
+ if (!result.error) {
1310
+ _consecutiveFailures = 0;
1311
+ return result;
1312
+ }
1313
+ _consecutiveFailures++;
1314
+ for (let i = 0; i < MAX_RETRIES_BEFORE_RESTART; i++) {
1315
+ const delayMs = RETRY_DELAYS_MS[i] ?? 5e3;
1316
+ process.stderr.write(`[exed-client] ${label} failed (${result.error}), retry ${i + 1}/${MAX_RETRIES_BEFORE_RESTART} in ${delayMs}ms
1317
+ `);
1318
+ await new Promise((r) => setTimeout(r, delayMs));
1319
+ if (!_connected) {
1320
+ if (!await connectToSocket()) continue;
1321
+ }
1322
+ const retry = await doRequest();
1323
+ if (!retry.error) {
1324
+ _consecutiveFailures = 0;
1325
+ return retry;
1326
+ }
1327
+ _consecutiveFailures++;
1162
1328
  }
1163
- try {
1164
- await client.execute({
1165
- sql: `ALTER TABLE tasks ADD COLUMN checkpoint TEXT`,
1166
- args: []
1167
- });
1168
- } catch {
1329
+ if (isDaemonTooYoung()) {
1330
+ process.stderr.write(`[exed-client] ${label}: daemon too young (< ${MIN_DAEMON_AGE_MS / 1e3}s) \u2014 skipping restart
1331
+ `);
1332
+ return { error: result.error };
1169
1333
  }
1170
- try {
1171
- await client.execute({
1172
- sql: `ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER NOT NULL DEFAULT 0`,
1173
- args: []
1174
- });
1175
- } catch {
1334
+ process.stderr.write(`[exed-client] ${label}: ${_consecutiveFailures} consecutive failures \u2014 restarting daemon
1335
+ `);
1336
+ killAndRespawnDaemon();
1337
+ const start = Date.now();
1338
+ let delay2 = 200;
1339
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1340
+ await new Promise((r) => setTimeout(r, delay2));
1341
+ if (await connectToSocket()) break;
1342
+ delay2 = Math.min(delay2 * 2, 3e3);
1343
+ }
1344
+ if (!_connected) return { error: "Daemon restart failed" };
1345
+ const final = await doRequest();
1346
+ if (!final.error) _consecutiveFailures = 0;
1347
+ return final;
1348
+ }
1349
+ async function embedViaClient(text, priority = "high") {
1350
+ if (!_connected && !await connectEmbedDaemon()) return null;
1351
+ _requestCount++;
1352
+ if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
1353
+ const health = await pingDaemon();
1354
+ if (!health && !isDaemonTooYoung()) {
1355
+ process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
1356
+ `);
1357
+ killAndRespawnDaemon();
1358
+ const start = Date.now();
1359
+ let d = 200;
1360
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1361
+ await new Promise((r) => setTimeout(r, d));
1362
+ if (await connectToSocket()) break;
1363
+ d = Math.min(d * 2, 3e3);
1364
+ }
1365
+ if (!_connected) return null;
1366
+ }
1176
1367
  }
1177
- try {
1178
- await client.execute({
1179
- sql: `ALTER TABLE tasks ADD COLUMN complexity TEXT NOT NULL DEFAULT 'standard'`,
1180
- args: []
1181
- });
1182
- } catch {
1368
+ const result = await retryThenRestart(
1369
+ () => sendRequest([text], priority),
1370
+ "Embed"
1371
+ );
1372
+ return !result.error && result.vectors?.[0] ? result.vectors[0] : null;
1373
+ }
1374
+ async function embedBatchViaClient(texts, priority = "high") {
1375
+ if (!_connected && !await connectEmbedDaemon()) return null;
1376
+ _requestCount++;
1377
+ const result = await retryThenRestart(
1378
+ () => sendRequest(texts, priority),
1379
+ "Batch embed"
1380
+ );
1381
+ return !result.error && result.vectors ? result.vectors : null;
1382
+ }
1383
+ function disconnectClient() {
1384
+ if (_socket) {
1385
+ _socket.destroy();
1386
+ _socket = null;
1387
+ }
1388
+ _connected = false;
1389
+ _buffer = "";
1390
+ for (const [id, entry] of _pending) {
1391
+ clearTimeout(entry.timer);
1392
+ _pending.delete(id);
1393
+ entry.resolve({ error: "Client disconnected" });
1183
1394
  }
1395
+ }
1396
+ function isClientConnected() {
1397
+ return _connected;
1398
+ }
1399
+ function sendIngestRequest(payload) {
1400
+ if (!_socket || !_connected) return false;
1184
1401
  try {
1185
- await client.execute({
1186
- sql: `ALTER TABLE tasks ADD COLUMN session_scope TEXT`,
1187
- args: []
1188
- });
1402
+ const id = randomUUID();
1403
+ const token = process.env[DAEMON_TOKEN_ENV] ?? readDaemonToken();
1404
+ _socket.write(JSON.stringify({ id, token, type: "ingest", ...payload }) + "\n");
1405
+ return true;
1189
1406
  } catch {
1407
+ return false;
1190
1408
  }
1191
- try {
1192
- await client.execute({
1193
- sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
1194
- args: []
1195
- });
1196
- } catch {
1409
+ }
1410
+ 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;
1411
+ var init_exe_daemon_client = __esm({
1412
+ "src/lib/exe-daemon-client.ts"() {
1413
+ "use strict";
1414
+ init_config();
1415
+ init_daemon_auth();
1416
+ SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path5.join(EXE_AI_DIR, "exed.sock");
1417
+ PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path5.join(EXE_AI_DIR, "exed.pid");
1418
+ SPAWN_LOCK_PATH = path5.join(EXE_AI_DIR, "exed-spawn.lock");
1419
+ SPAWN_LOCK_STALE_MS = 3e4;
1420
+ CONNECT_TIMEOUT_MS = 15e3;
1421
+ REQUEST_TIMEOUT_MS = 3e4;
1422
+ DAEMON_TOKEN_ENV = "EXE_DAEMON_TOKEN";
1423
+ _socket = null;
1424
+ _connected = false;
1425
+ _buffer = "";
1426
+ _requestCount = 0;
1427
+ _consecutiveFailures = 0;
1428
+ HEALTH_CHECK_INTERVAL = 100;
1429
+ MAX_RETRIES_BEFORE_RESTART = 3;
1430
+ RETRY_DELAYS_MS = [1e3, 3e3, 5e3];
1431
+ MIN_DAEMON_AGE_MS = 3e4;
1432
+ _pending = /* @__PURE__ */ new Map();
1433
+ MAX_BUFFER = 1e7;
1197
1434
  }
1198
- try {
1199
- await client.execute({
1200
- sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
1201
- args: []
1202
- });
1203
- } catch {
1435
+ });
1436
+
1437
+ // src/lib/daemon-protocol.ts
1438
+ var daemon_protocol_exports = {};
1439
+ __export(daemon_protocol_exports, {
1440
+ deserializeArgs: () => deserializeArgs,
1441
+ deserializeResultSet: () => deserializeResultSet,
1442
+ deserializeValue: () => deserializeValue,
1443
+ serializeArgs: () => serializeArgs,
1444
+ serializeResultSet: () => serializeResultSet,
1445
+ serializeValue: () => serializeValue
1446
+ });
1447
+ function serializeValue(v) {
1448
+ if (v === null || v === void 0) return null;
1449
+ if (typeof v === "bigint") return Number(v);
1450
+ if (typeof v === "boolean") return v ? 1 : 0;
1451
+ if (v instanceof Uint8Array) {
1452
+ return { __blob: Buffer.from(v).toString("base64") };
1204
1453
  }
1205
- try {
1206
- await client.execute({
1207
- sql: `ALTER TABLE memories ADD COLUMN author_device_id TEXT`,
1208
- args: []
1209
- });
1210
- } catch {
1454
+ if (ArrayBuffer.isView(v)) {
1455
+ return { __blob: Buffer.from(v.buffer, v.byteOffset, v.byteLength).toString("base64") };
1211
1456
  }
1212
- try {
1213
- await client.execute({
1214
- sql: `ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'`,
1215
- args: []
1216
- });
1217
- } catch {
1457
+ if (v instanceof ArrayBuffer) {
1458
+ return { __blob: Buffer.from(v).toString("base64") };
1218
1459
  }
1219
- await client.executeMultiple(`
1220
- CREATE TABLE IF NOT EXISTS consolidations (
1221
- id TEXT PRIMARY KEY,
1222
- consolidated_memory_id TEXT NOT NULL,
1223
- source_memory_id TEXT NOT NULL,
1224
- created_at TEXT NOT NULL
1225
- );
1226
-
1227
- CREATE INDEX IF NOT EXISTS idx_consolidations_source
1228
- ON consolidations(source_memory_id);
1229
-
1230
- CREATE INDEX IF NOT EXISTS idx_consolidations_consolidated
1231
- ON consolidations(consolidated_memory_id);
1232
- `);
1233
- await client.executeMultiple(`
1234
- CREATE TABLE IF NOT EXISTS reminders (
1235
- id TEXT PRIMARY KEY,
1236
- text TEXT NOT NULL,
1237
- created_at TEXT NOT NULL,
1238
- due_date TEXT,
1239
- completed_at TEXT
1240
- );
1241
- `);
1242
- await client.executeMultiple(`
1243
- CREATE TABLE IF NOT EXISTS notifications (
1244
- id TEXT PRIMARY KEY,
1245
- agent_id TEXT NOT NULL,
1246
- agent_role TEXT NOT NULL,
1247
- event TEXT NOT NULL,
1248
- project TEXT NOT NULL,
1249
- summary TEXT NOT NULL,
1250
- task_file TEXT,
1251
- session_scope TEXT,
1252
- read INTEGER NOT NULL DEFAULT 0,
1253
- created_at TEXT NOT NULL
1460
+ if (typeof v === "string" || typeof v === "number") return v;
1461
+ return String(v);
1462
+ }
1463
+ function deserializeValue(v) {
1464
+ if (v === null) return null;
1465
+ if (typeof v === "object" && v !== null && "__blob" in v) {
1466
+ const buf = Buffer.from(v.__blob, "base64");
1467
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
1468
+ }
1469
+ return v;
1470
+ }
1471
+ function serializeArgs(args) {
1472
+ return args.map(serializeValue);
1473
+ }
1474
+ function deserializeArgs(args) {
1475
+ return args.map(deserializeValue);
1476
+ }
1477
+ function serializeResultSet(rs) {
1478
+ const rows = [];
1479
+ for (const row of rs.rows) {
1480
+ const obj = {};
1481
+ for (let i = 0; i < rs.columns.length; i++) {
1482
+ const col = rs.columns[i];
1483
+ if (col !== void 0) {
1484
+ obj[col] = serializeValue(row[i]);
1485
+ }
1486
+ }
1487
+ rows.push(obj);
1488
+ }
1489
+ return {
1490
+ columns: [...rs.columns],
1491
+ columnTypes: [...rs.columnTypes ?? []],
1492
+ rows,
1493
+ rowsAffected: typeof rs.rowsAffected === "bigint" ? Number(rs.rowsAffected) : rs.rowsAffected ?? 0,
1494
+ lastInsertRowid: rs.lastInsertRowid != null ? typeof rs.lastInsertRowid === "bigint" ? Number(rs.lastInsertRowid) : rs.lastInsertRowid : null
1495
+ };
1496
+ }
1497
+ function deserializeResultSet(srs) {
1498
+ const rows = srs.rows.map((obj) => {
1499
+ const values = srs.columns.map(
1500
+ (col) => deserializeValue(obj[col] ?? null)
1254
1501
  );
1502
+ const row = values;
1503
+ for (let i = 0; i < srs.columns.length; i++) {
1504
+ const col = srs.columns[i];
1505
+ if (col !== void 0) {
1506
+ row[col] = values[i] ?? null;
1507
+ }
1508
+ }
1509
+ Object.defineProperty(row, "length", {
1510
+ value: values.length,
1511
+ enumerable: false
1512
+ });
1513
+ return row;
1514
+ });
1515
+ return {
1516
+ columns: srs.columns,
1517
+ columnTypes: srs.columnTypes ?? [],
1518
+ rows,
1519
+ rowsAffected: srs.rowsAffected,
1520
+ lastInsertRowid: srs.lastInsertRowid != null ? BigInt(srs.lastInsertRowid) : void 0,
1521
+ toJSON: () => ({
1522
+ columns: srs.columns,
1523
+ columnTypes: srs.columnTypes ?? [],
1524
+ rows: srs.rows,
1525
+ rowsAffected: srs.rowsAffected,
1526
+ lastInsertRowid: srs.lastInsertRowid
1527
+ })
1528
+ };
1529
+ }
1530
+ var init_daemon_protocol = __esm({
1531
+ "src/lib/daemon-protocol.ts"() {
1532
+ "use strict";
1533
+ }
1534
+ });
1255
1535
 
1256
- CREATE INDEX IF NOT EXISTS idx_notifications_read
1257
- ON notifications(read);
1536
+ // src/lib/db-daemon-client.ts
1537
+ var db_daemon_client_exports = {};
1538
+ __export(db_daemon_client_exports, {
1539
+ createDaemonDbClient: () => createDaemonDbClient,
1540
+ initDaemonDbClient: () => initDaemonDbClient
1541
+ });
1542
+ function normalizeStatement2(stmt) {
1543
+ if (typeof stmt === "string") {
1544
+ return { sql: stmt, args: [] };
1545
+ }
1546
+ const sql = stmt.sql;
1547
+ let args = [];
1548
+ if (Array.isArray(stmt.args)) {
1549
+ args = stmt.args.map((v) => serializeValue(v));
1550
+ } else if (stmt.args && typeof stmt.args === "object") {
1551
+ const named = {};
1552
+ for (const [key, val] of Object.entries(stmt.args)) {
1553
+ named[key] = serializeValue(val);
1554
+ }
1555
+ return { sql, args: named };
1556
+ }
1557
+ return { sql, args };
1558
+ }
1559
+ function createDaemonDbClient(fallbackClient) {
1560
+ let _useDaemon = false;
1561
+ const client = {
1562
+ async execute(stmt) {
1563
+ if (!_useDaemon || !isClientConnected()) {
1564
+ return fallbackClient.execute(stmt);
1565
+ }
1566
+ const { sql, args } = normalizeStatement2(stmt);
1567
+ const response = await sendDaemonRequest({
1568
+ type: "db-execute",
1569
+ sql,
1570
+ args
1571
+ });
1572
+ if (response.error) {
1573
+ const errMsg = String(response.error);
1574
+ if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
1575
+ process.stderr.write(`[db-daemon] Transport error (${errMsg}), falling back to direct
1576
+ `);
1577
+ return fallbackClient.execute(stmt);
1578
+ }
1579
+ throw new Error(errMsg);
1580
+ }
1581
+ if (response.db) {
1582
+ return deserializeResultSet(response.db);
1583
+ }
1584
+ process.stderr.write("[db-daemon] Unexpected response shape, falling back to direct\n");
1585
+ return fallbackClient.execute(stmt);
1586
+ },
1587
+ async batch(stmts, mode) {
1588
+ if (!_useDaemon || !isClientConnected()) {
1589
+ return fallbackClient.batch(stmts, mode);
1590
+ }
1591
+ const statements = stmts.map(normalizeStatement2);
1592
+ const response = await sendDaemonRequest({
1593
+ type: "db-batch",
1594
+ statements,
1595
+ mode: mode ?? "deferred"
1596
+ });
1597
+ if (response.error) {
1598
+ const errMsg = String(response.error);
1599
+ if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
1600
+ process.stderr.write(`[db-daemon] Batch transport error (${errMsg}), falling back to direct
1601
+ `);
1602
+ return fallbackClient.batch(stmts, mode);
1603
+ }
1604
+ throw new Error(errMsg);
1605
+ }
1606
+ const batchResults = response["db-batch"];
1607
+ if (batchResults) {
1608
+ return batchResults.map(deserializeResultSet);
1609
+ }
1610
+ process.stderr.write("[db-daemon] Unexpected batch response shape, falling back to direct\n");
1611
+ return fallbackClient.batch(stmts, mode);
1612
+ },
1613
+ // Transaction support — delegate to fallback (transactions need direct connection)
1614
+ async transaction(mode) {
1615
+ return fallbackClient.transaction(mode);
1616
+ },
1617
+ // executeMultiple — delegate to fallback (used only for schema migrations)
1618
+ async executeMultiple(sql) {
1619
+ return fallbackClient.executeMultiple(sql);
1620
+ },
1621
+ // migrate — delegate to fallback
1622
+ async migrate(stmts) {
1623
+ return fallbackClient.migrate(stmts);
1624
+ },
1625
+ // Sync mode — delegate to fallback
1626
+ sync() {
1627
+ return fallbackClient.sync();
1628
+ },
1629
+ close() {
1630
+ _useDaemon = false;
1631
+ },
1632
+ get closed() {
1633
+ return fallbackClient.closed;
1634
+ },
1635
+ get protocol() {
1636
+ return fallbackClient.protocol;
1637
+ }
1638
+ };
1639
+ return {
1640
+ ...client,
1641
+ /** Enable daemon routing (call after confirming daemon is connected) */
1642
+ _enableDaemon() {
1643
+ _useDaemon = true;
1644
+ },
1645
+ /** Check if daemon routing is active */
1646
+ _isDaemonActive() {
1647
+ return _useDaemon && isClientConnected();
1648
+ }
1649
+ };
1650
+ }
1651
+ async function initDaemonDbClient(fallbackClient) {
1652
+ if (process.env.EXE_IS_DAEMON === "1") return null;
1653
+ const connected = await connectEmbedDaemon();
1654
+ if (!connected) {
1655
+ process.stderr.write("[db-daemon] Daemon unavailable \u2014 using direct SQLite\n");
1656
+ return null;
1657
+ }
1658
+ const client = createDaemonDbClient(fallbackClient);
1659
+ client._enableDaemon();
1660
+ process.stderr.write("[db-daemon] DB routing through daemon (single-writer)\n");
1661
+ return client;
1662
+ }
1663
+ var init_db_daemon_client = __esm({
1664
+ "src/lib/db-daemon-client.ts"() {
1665
+ "use strict";
1666
+ init_exe_daemon_client();
1667
+ init_daemon_protocol();
1668
+ }
1669
+ });
1258
1670
 
1259
- CREATE INDEX IF NOT EXISTS idx_notifications_agent
1260
- ON notifications(agent_id, session_scope);
1671
+ // src/lib/database.ts
1672
+ var database_exports = {};
1673
+ __export(database_exports, {
1674
+ disposeDatabase: () => disposeDatabase,
1675
+ disposeTurso: () => disposeTurso,
1676
+ ensureSchema: () => ensureSchema,
1677
+ getClient: () => getClient,
1678
+ getRawClient: () => getRawClient,
1679
+ initDaemonClient: () => initDaemonClient,
1680
+ initDatabase: () => initDatabase,
1681
+ initTurso: () => initTurso,
1682
+ isInitialized: () => isInitialized
1683
+ });
1684
+ import { createClient } from "@libsql/client";
1685
+ async function initDatabase(config) {
1686
+ if (_walCheckpointTimer) {
1687
+ clearInterval(_walCheckpointTimer);
1688
+ _walCheckpointTimer = null;
1689
+ }
1690
+ if (_daemonClient) {
1691
+ _daemonClient.close();
1692
+ _daemonClient = null;
1693
+ }
1694
+ if (_adapterClient && _adapterClient !== _resilientClient) {
1695
+ _adapterClient.close();
1696
+ }
1697
+ _adapterClient = null;
1698
+ if (_client) {
1699
+ _client.close();
1700
+ _client = null;
1701
+ _resilientClient = null;
1702
+ }
1703
+ const opts = {
1704
+ url: `file:${config.dbPath}`
1705
+ };
1706
+ if (config.encryptionKey) {
1707
+ opts.encryptionKey = config.encryptionKey;
1708
+ }
1709
+ _client = createClient(opts);
1710
+ _resilientClient = wrapWithRetry(_client);
1711
+ _adapterClient = _resilientClient;
1712
+ _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
1713
+ });
1714
+ _client.execute("PRAGMA journal_mode = WAL").catch(() => {
1715
+ });
1716
+ if (_walCheckpointTimer) clearInterval(_walCheckpointTimer);
1717
+ _walCheckpointTimer = setInterval(() => {
1718
+ _client?.execute("PRAGMA wal_checkpoint(PASSIVE)").catch(() => {
1719
+ });
1720
+ }, 3e4);
1721
+ _walCheckpointTimer.unref();
1722
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
1723
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
1724
+ }
1725
+ }
1726
+ function isInitialized() {
1727
+ return _adapterClient !== null || _client !== null;
1728
+ }
1729
+ function getClient() {
1730
+ if (!_adapterClient) {
1731
+ throw new Error("Database client not initialized. Call initDatabase() first.");
1732
+ }
1733
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
1734
+ return _adapterClient;
1735
+ }
1736
+ if (process.env.EXE_IS_DAEMON === "1") {
1737
+ return _resilientClient;
1738
+ }
1739
+ if (_daemonClient && _daemonClient._isDaemonActive()) {
1740
+ return _daemonClient;
1741
+ }
1742
+ return _resilientClient;
1743
+ }
1744
+ async function initDaemonClient() {
1745
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") return;
1746
+ if (process.env.EXE_IS_DAEMON === "1") return;
1747
+ if (process.env.VITEST) return;
1748
+ if (!_resilientClient) return;
1749
+ if (_daemonClient) return;
1750
+ try {
1751
+ const { initDaemonDbClient: initDaemonDbClient2 } = await Promise.resolve().then(() => (init_db_daemon_client(), db_daemon_client_exports));
1752
+ _daemonClient = await initDaemonDbClient2(_resilientClient);
1753
+ } catch (err) {
1754
+ process.stderr.write(
1755
+ `[database] Daemon client init failed (non-fatal): ${err instanceof Error ? err.message : String(err)}
1756
+ `
1757
+ );
1758
+ }
1759
+ }
1760
+ function getRawClient() {
1761
+ if (!_client) {
1762
+ throw new Error("Database client not initialized. Call initDatabase() first.");
1763
+ }
1764
+ return _client;
1765
+ }
1766
+ async function ensureSchema() {
1767
+ const client = getRawClient();
1768
+ await client.execute("PRAGMA journal_mode = WAL");
1769
+ await client.execute("PRAGMA busy_timeout = 30000");
1770
+ await client.execute("PRAGMA wal_autocheckpoint = 1000");
1771
+ try {
1772
+ await client.execute("PRAGMA libsql_vector_search_ef = 128");
1773
+ } catch {
1774
+ }
1775
+ await client.executeMultiple(`
1776
+ CREATE TABLE IF NOT EXISTS memories (
1777
+ id TEXT PRIMARY KEY,
1778
+ agent_id TEXT NOT NULL,
1779
+ agent_role TEXT NOT NULL,
1780
+ session_id TEXT NOT NULL,
1781
+ timestamp TEXT NOT NULL,
1782
+ tool_name TEXT NOT NULL,
1783
+ project_name TEXT NOT NULL,
1784
+ has_error INTEGER NOT NULL DEFAULT 0,
1785
+ raw_text TEXT NOT NULL,
1786
+ vector F32_BLOB(1024),
1787
+ version INTEGER NOT NULL DEFAULT 0
1788
+ );
1261
1789
 
1262
- CREATE INDEX IF NOT EXISTS idx_notifications_task_file
1263
- ON notifications(task_file);
1790
+ CREATE INDEX IF NOT EXISTS idx_memories_agent
1791
+ ON memories(agent_id);
1792
+
1793
+ CREATE INDEX IF NOT EXISTS idx_memories_timestamp
1794
+ ON memories(timestamp);
1795
+
1796
+ CREATE INDEX IF NOT EXISTS idx_memories_session
1797
+ ON memories(session_id);
1798
+
1799
+ CREATE INDEX IF NOT EXISTS idx_memories_project
1800
+ ON memories(project_name);
1801
+
1802
+ CREATE INDEX IF NOT EXISTS idx_memories_tool
1803
+ ON memories(tool_name);
1804
+
1805
+ CREATE INDEX IF NOT EXISTS idx_memories_version
1806
+ ON memories(version);
1807
+
1808
+ CREATE INDEX IF NOT EXISTS idx_memories_agent_project
1809
+ ON memories(agent_id, project_name);
1264
1810
  `);
1265
1811
  await client.executeMultiple(`
1266
- CREATE TABLE IF NOT EXISTS schedules (
1267
- id TEXT PRIMARY KEY,
1268
- cron TEXT NOT NULL,
1269
- description TEXT NOT NULL,
1270
- job_type TEXT NOT NULL DEFAULT 'report',
1271
- prompt TEXT,
1272
- assigned_to TEXT,
1273
- project_name TEXT,
1274
- active INTEGER NOT NULL DEFAULT 1,
1275
- use_crontab INTEGER NOT NULL DEFAULT 0,
1276
- created_at TEXT NOT NULL
1812
+ CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
1813
+ raw_text,
1814
+ content='memories',
1815
+ content_rowid='rowid'
1277
1816
  );
1817
+
1818
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
1819
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1820
+ END;
1821
+
1822
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
1823
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1824
+ END;
1825
+
1826
+ CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
1827
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1828
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1829
+ END;
1278
1830
  `);
1279
1831
  await client.executeMultiple(`
1280
- CREATE TABLE IF NOT EXISTS device_registry (
1281
- device_id TEXT PRIMARY KEY,
1282
- friendly_name TEXT NOT NULL,
1283
- hostname TEXT NOT NULL,
1284
- projects TEXT NOT NULL DEFAULT '[]',
1285
- agents TEXT NOT NULL DEFAULT '[]',
1286
- connected INTEGER DEFAULT 0,
1287
- last_seen TEXT NOT NULL
1832
+ CREATE TABLE IF NOT EXISTS sync_meta (
1833
+ key TEXT PRIMARY KEY,
1834
+ value TEXT NOT NULL
1288
1835
  );
1289
1836
  `);
1290
1837
  await client.executeMultiple(`
1291
- CREATE TABLE IF NOT EXISTS messages (
1292
- id TEXT PRIMARY KEY,
1293
- from_agent TEXT NOT NULL,
1294
- from_device TEXT NOT NULL DEFAULT 'local',
1295
- target_agent TEXT NOT NULL,
1296
- target_project TEXT,
1297
- target_device TEXT NOT NULL DEFAULT 'local',
1298
- session_scope TEXT,
1299
- content TEXT NOT NULL,
1300
- priority TEXT DEFAULT 'normal',
1301
- status TEXT DEFAULT 'pending',
1302
- server_seq INTEGER,
1303
- retry_count INTEGER DEFAULT 0,
1304
- created_at TEXT NOT NULL,
1305
- delivered_at TEXT,
1306
- processed_at TEXT,
1307
- failed_at TEXT,
1308
- failure_reason TEXT
1838
+ CREATE TABLE IF NOT EXISTS tasks (
1839
+ id TEXT PRIMARY KEY,
1840
+ title TEXT NOT NULL,
1841
+ assigned_to TEXT NOT NULL,
1842
+ assigned_by TEXT NOT NULL,
1843
+ project_name TEXT NOT NULL,
1844
+ priority TEXT NOT NULL DEFAULT 'p1',
1845
+ status TEXT NOT NULL DEFAULT 'open',
1846
+ task_file TEXT,
1847
+ created_at TEXT NOT NULL,
1848
+ updated_at TEXT NOT NULL
1309
1849
  );
1310
1850
 
1311
- CREATE INDEX IF NOT EXISTS idx_messages_target
1312
- ON messages(target_agent, session_scope, status);
1851
+ CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
1852
+ ON tasks(assigned_to, status);
1853
+ `);
1854
+ await client.executeMultiple(`
1855
+ CREATE TABLE IF NOT EXISTS behaviors (
1856
+ id TEXT PRIMARY KEY,
1857
+ agent_id TEXT NOT NULL,
1858
+ project_name TEXT,
1859
+ domain TEXT,
1860
+ content TEXT NOT NULL,
1861
+ active INTEGER NOT NULL DEFAULT 1,
1862
+ created_at TEXT NOT NULL,
1863
+ updated_at TEXT NOT NULL
1864
+ );
1313
1865
 
1314
- CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
1315
- ON messages(target_agent, session_scope, from_agent, server_seq);
1866
+ CREATE INDEX IF NOT EXISTS idx_behaviors_agent
1867
+ ON behaviors(agent_id, active);
1316
1868
  `);
1317
1869
  try {
1318
- await client.execute({
1319
- sql: `ALTER TABLE notifications ADD COLUMN session_scope TEXT`,
1320
- args: []
1870
+ const coordinatorName = getCoordinatorName();
1871
+ const existing = await client.execute({
1872
+ sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = ?",
1873
+ args: [coordinatorName]
1321
1874
  });
1875
+ if (Number(existing.rows[0]?.cnt) === 0) {
1876
+ const seededAt = "2026-03-25T00:00:00Z";
1877
+ for (const [domain, content] of [
1878
+ ["workflow", `Don't ask "keep going?" \u2014 just keep executing phases/plans autonomously`],
1879
+ ["tool-use", "Always use create_task MCP tool, never write .md files directly for task creation"],
1880
+ ["workflow", "Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission"]
1881
+ ]) {
1882
+ await client.execute({
1883
+ sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
1884
+ VALUES (hex(randomblob(16)), ?, NULL, ?, ?, 1, ?, ?)`,
1885
+ args: [coordinatorName, domain, content, seededAt, seededAt]
1886
+ });
1887
+ }
1888
+ }
1322
1889
  } catch {
1323
1890
  }
1324
1891
  try {
1325
1892
  await client.execute({
1326
- sql: `ALTER TABLE messages ADD COLUMN session_scope TEXT`,
1893
+ sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
1327
1894
  args: []
1328
1895
  });
1329
1896
  } catch {
1330
1897
  }
1331
- await client.executeMultiple(`
1332
- CREATE INDEX IF NOT EXISTS idx_notifications_agent_scope_read
1333
- ON notifications(agent_id, session_scope, read, created_at);
1334
-
1335
- CREATE INDEX IF NOT EXISTS idx_messages_target_scope_status
1336
- ON messages(target_agent, session_scope, status, created_at);
1337
- `);
1338
1898
  try {
1339
1899
  await client.execute({
1340
- sql: `UPDATE memories SET project_name = 'exe-create' WHERE project_name = 'web'`,
1900
+ sql: `ALTER TABLE behaviors ADD COLUMN vector F32_BLOB(${EMBEDDING_DIM})`,
1341
1901
  args: []
1342
1902
  });
1903
+ } catch {
1904
+ }
1905
+ try {
1343
1906
  await client.execute({
1344
- sql: `UPDATE memories SET project_name = 'exe-os' WHERE project_name = 'worker'`,
1907
+ sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
1345
1908
  args: []
1346
1909
  });
1910
+ } catch {
1911
+ }
1912
+ try {
1347
1913
  await client.execute({
1348
- sql: `UPDATE tasks SET project_name = 'exe-create' WHERE project_name = 'web'`,
1914
+ sql: `ALTER TABLE tasks ADD COLUMN parent_task_id TEXT`,
1349
1915
  args: []
1350
1916
  });
1917
+ } catch {
1918
+ }
1919
+ try {
1351
1920
  await client.execute({
1352
- sql: `UPDATE tasks SET project_name = 'exe-os' WHERE project_name = 'worker'`,
1921
+ sql: `CREATE INDEX IF NOT EXISTS idx_tasks_parent_task_id
1922
+ ON tasks(parent_task_id)
1923
+ WHERE parent_task_id IS NOT NULL`,
1353
1924
  args: []
1354
1925
  });
1355
1926
  } catch {
1356
1927
  }
1357
- await client.executeMultiple(`
1358
- CREATE TABLE IF NOT EXISTS trajectories (
1928
+ try {
1929
+ await client.execute({
1930
+ sql: `UPDATE tasks SET status = 'done' WHERE status = 'completed'`,
1931
+ args: []
1932
+ });
1933
+ } catch {
1934
+ }
1935
+ try {
1936
+ await client.execute({
1937
+ sql: `ALTER TABLE tasks ADD COLUMN reviewer TEXT`,
1938
+ args: []
1939
+ });
1940
+ } catch {
1941
+ }
1942
+ try {
1943
+ await client.execute({
1944
+ sql: `ALTER TABLE tasks ADD COLUMN context TEXT`,
1945
+ args: []
1946
+ });
1947
+ } catch {
1948
+ }
1949
+ try {
1950
+ await client.execute({
1951
+ sql: `ALTER TABLE tasks ADD COLUMN result TEXT`,
1952
+ args: []
1953
+ });
1954
+ } catch {
1955
+ }
1956
+ try {
1957
+ await client.execute({
1958
+ sql: `ALTER TABLE tasks ADD COLUMN assigned_tmux TEXT`,
1959
+ args: []
1960
+ });
1961
+ } catch {
1962
+ }
1963
+ try {
1964
+ await client.execute({
1965
+ sql: `ALTER TABLE tasks ADD COLUMN checkpoint TEXT`,
1966
+ args: []
1967
+ });
1968
+ } catch {
1969
+ }
1970
+ try {
1971
+ await client.execute({
1972
+ sql: `ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER NOT NULL DEFAULT 0`,
1973
+ args: []
1974
+ });
1975
+ } catch {
1976
+ }
1977
+ try {
1978
+ await client.execute({
1979
+ sql: `ALTER TABLE tasks ADD COLUMN complexity TEXT NOT NULL DEFAULT 'standard'`,
1980
+ args: []
1981
+ });
1982
+ } catch {
1983
+ }
1984
+ try {
1985
+ await client.execute({
1986
+ sql: `ALTER TABLE tasks ADD COLUMN session_scope TEXT`,
1987
+ args: []
1988
+ });
1989
+ } catch {
1990
+ }
1991
+ try {
1992
+ await client.execute({
1993
+ sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
1994
+ args: []
1995
+ });
1996
+ } catch {
1997
+ }
1998
+ try {
1999
+ await client.execute({
2000
+ sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
2001
+ args: []
2002
+ });
2003
+ } catch {
2004
+ }
2005
+ try {
2006
+ await client.execute({
2007
+ sql: `ALTER TABLE memories ADD COLUMN author_device_id TEXT`,
2008
+ args: []
2009
+ });
2010
+ } catch {
2011
+ }
2012
+ try {
2013
+ await client.execute({
2014
+ sql: `ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'`,
2015
+ args: []
2016
+ });
2017
+ } catch {
2018
+ }
2019
+ await client.executeMultiple(`
2020
+ CREATE TABLE IF NOT EXISTS consolidations (
2021
+ id TEXT PRIMARY KEY,
2022
+ consolidated_memory_id TEXT NOT NULL,
2023
+ source_memory_id TEXT NOT NULL,
2024
+ created_at TEXT NOT NULL
2025
+ );
2026
+
2027
+ CREATE INDEX IF NOT EXISTS idx_consolidations_source
2028
+ ON consolidations(source_memory_id);
2029
+
2030
+ CREATE INDEX IF NOT EXISTS idx_consolidations_consolidated
2031
+ ON consolidations(consolidated_memory_id);
2032
+ `);
2033
+ await client.executeMultiple(`
2034
+ CREATE TABLE IF NOT EXISTS reminders (
2035
+ id TEXT PRIMARY KEY,
2036
+ text TEXT NOT NULL,
2037
+ created_at TEXT NOT NULL,
2038
+ due_date TEXT,
2039
+ completed_at TEXT
2040
+ );
2041
+ `);
2042
+ await client.executeMultiple(`
2043
+ CREATE TABLE IF NOT EXISTS notifications (
2044
+ id TEXT PRIMARY KEY,
2045
+ agent_id TEXT NOT NULL,
2046
+ agent_role TEXT NOT NULL,
2047
+ event TEXT NOT NULL,
2048
+ project TEXT NOT NULL,
2049
+ summary TEXT NOT NULL,
2050
+ task_file TEXT,
2051
+ session_scope TEXT,
2052
+ read INTEGER NOT NULL DEFAULT 0,
2053
+ created_at TEXT NOT NULL
2054
+ );
2055
+
2056
+ CREATE INDEX IF NOT EXISTS idx_notifications_read
2057
+ ON notifications(read);
2058
+
2059
+ CREATE INDEX IF NOT EXISTS idx_notifications_agent
2060
+ ON notifications(agent_id, session_scope);
2061
+
2062
+ CREATE INDEX IF NOT EXISTS idx_notifications_task_file
2063
+ ON notifications(task_file);
2064
+ `);
2065
+ await client.executeMultiple(`
2066
+ CREATE TABLE IF NOT EXISTS schedules (
2067
+ id TEXT PRIMARY KEY,
2068
+ cron TEXT NOT NULL,
2069
+ description TEXT NOT NULL,
2070
+ job_type TEXT NOT NULL DEFAULT 'report',
2071
+ prompt TEXT,
2072
+ assigned_to TEXT,
2073
+ project_name TEXT,
2074
+ active INTEGER NOT NULL DEFAULT 1,
2075
+ use_crontab INTEGER NOT NULL DEFAULT 0,
2076
+ created_at TEXT NOT NULL
2077
+ );
2078
+ `);
2079
+ await client.executeMultiple(`
2080
+ CREATE TABLE IF NOT EXISTS device_registry (
2081
+ device_id TEXT PRIMARY KEY,
2082
+ friendly_name TEXT NOT NULL,
2083
+ hostname TEXT NOT NULL,
2084
+ projects TEXT NOT NULL DEFAULT '[]',
2085
+ agents TEXT NOT NULL DEFAULT '[]',
2086
+ connected INTEGER DEFAULT 0,
2087
+ last_seen TEXT NOT NULL
2088
+ );
2089
+ `);
2090
+ await client.executeMultiple(`
2091
+ CREATE TABLE IF NOT EXISTS messages (
2092
+ id TEXT PRIMARY KEY,
2093
+ from_agent TEXT NOT NULL,
2094
+ from_device TEXT NOT NULL DEFAULT 'local',
2095
+ target_agent TEXT NOT NULL,
2096
+ target_project TEXT,
2097
+ target_device TEXT NOT NULL DEFAULT 'local',
2098
+ session_scope TEXT,
2099
+ content TEXT NOT NULL,
2100
+ priority TEXT DEFAULT 'normal',
2101
+ status TEXT DEFAULT 'pending',
2102
+ server_seq INTEGER,
2103
+ retry_count INTEGER DEFAULT 0,
2104
+ created_at TEXT NOT NULL,
2105
+ delivered_at TEXT,
2106
+ processed_at TEXT,
2107
+ failed_at TEXT,
2108
+ failure_reason TEXT
2109
+ );
2110
+
2111
+ CREATE INDEX IF NOT EXISTS idx_messages_target
2112
+ ON messages(target_agent, session_scope, status);
2113
+
2114
+ CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
2115
+ ON messages(target_agent, session_scope, from_agent, server_seq);
2116
+ `);
2117
+ try {
2118
+ await client.execute({
2119
+ sql: `ALTER TABLE notifications ADD COLUMN session_scope TEXT`,
2120
+ args: []
2121
+ });
2122
+ } catch {
2123
+ }
2124
+ try {
2125
+ await client.execute({
2126
+ sql: `ALTER TABLE messages ADD COLUMN session_scope TEXT`,
2127
+ args: []
2128
+ });
2129
+ } catch {
2130
+ }
2131
+ await client.executeMultiple(`
2132
+ CREATE INDEX IF NOT EXISTS idx_notifications_agent_scope_read
2133
+ ON notifications(agent_id, session_scope, read, created_at);
2134
+
2135
+ CREATE INDEX IF NOT EXISTS idx_messages_target_scope_status
2136
+ ON messages(target_agent, session_scope, status, created_at);
2137
+ `);
2138
+ try {
2139
+ await client.execute({
2140
+ sql: `UPDATE memories SET project_name = 'exe-create' WHERE project_name = 'web'`,
2141
+ args: []
2142
+ });
2143
+ await client.execute({
2144
+ sql: `UPDATE memories SET project_name = 'exe-os' WHERE project_name = 'worker'`,
2145
+ args: []
2146
+ });
2147
+ await client.execute({
2148
+ sql: `UPDATE tasks SET project_name = 'exe-create' WHERE project_name = 'web'`,
2149
+ args: []
2150
+ });
2151
+ await client.execute({
2152
+ sql: `UPDATE tasks SET project_name = 'exe-os' WHERE project_name = 'worker'`,
2153
+ args: []
2154
+ });
2155
+ } catch {
2156
+ }
2157
+ await client.executeMultiple(`
2158
+ CREATE TABLE IF NOT EXISTS trajectories (
1359
2159
  id TEXT PRIMARY KEY,
1360
2160
  task_id TEXT NOT NULL,
1361
2161
  agent_id TEXT NOT NULL,
@@ -1946,1055 +2746,1154 @@ async function ensureSchema() {
1946
2746
  } catch {
1947
2747
  }
1948
2748
  }
1949
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
2749
+ async function disposeDatabase() {
2750
+ if (_walCheckpointTimer) {
2751
+ clearInterval(_walCheckpointTimer);
2752
+ _walCheckpointTimer = null;
2753
+ }
2754
+ if (_daemonClient) {
2755
+ _daemonClient.close();
2756
+ _daemonClient = null;
2757
+ }
2758
+ if (_adapterClient && _adapterClient !== _resilientClient) {
2759
+ _adapterClient.close();
2760
+ }
2761
+ _adapterClient = null;
2762
+ if (_client) {
2763
+ _client.close();
2764
+ _client = null;
2765
+ _resilientClient = null;
2766
+ }
2767
+ }
2768
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso, disposeTurso;
1950
2769
  var init_database = __esm({
1951
2770
  "src/lib/database.ts"() {
1952
2771
  "use strict";
1953
2772
  init_db_retry();
1954
2773
  init_employees();
1955
2774
  init_database_adapter();
2775
+ init_memory();
1956
2776
  _client = null;
1957
2777
  _resilientClient = null;
1958
2778
  _walCheckpointTimer = null;
1959
2779
  _daemonClient = null;
1960
2780
  _adapterClient = null;
1961
2781
  initTurso = initDatabase;
2782
+ disposeTurso = disposeDatabase;
1962
2783
  }
1963
2784
  });
1964
2785
 
1965
- // src/lib/state-bus.ts
1966
- var StateBus, orgBus;
1967
- var init_state_bus = __esm({
1968
- "src/lib/state-bus.ts"() {
1969
- "use strict";
1970
- StateBus = class {
1971
- handlers = /* @__PURE__ */ new Map();
1972
- globalHandlers = /* @__PURE__ */ new Set();
1973
- /** Emit an event to all subscribers */
1974
- emit(event) {
1975
- const typeHandlers = this.handlers.get(event.type);
1976
- if (typeHandlers) {
1977
- for (const handler of typeHandlers) {
1978
- try {
1979
- handler(event);
1980
- } catch {
1981
- }
1982
- }
2786
+ // src/lib/session-registry.ts
2787
+ import path6 from "path";
2788
+ import os5 from "os";
2789
+ var REGISTRY_PATH;
2790
+ var init_session_registry = __esm({
2791
+ "src/lib/session-registry.ts"() {
2792
+ "use strict";
2793
+ REGISTRY_PATH = path6.join(os5.homedir(), ".exe-os", "session-registry.json");
2794
+ }
2795
+ });
2796
+
2797
+ // src/lib/session-key.ts
2798
+ import { execSync as execSync2 } from "child_process";
2799
+ function normalizeCommand(command) {
2800
+ const trimmed = command.trim().toLowerCase();
2801
+ const parts = trimmed.split(/[\\/]/);
2802
+ return parts[parts.length - 1] ?? trimmed;
2803
+ }
2804
+ function detectRuntimeFromCommand(command) {
2805
+ const normalized = normalizeCommand(command);
2806
+ for (const [runtime, commands] of Object.entries(RUNTIME_COMMANDS)) {
2807
+ if (commands.includes(normalized)) {
2808
+ return runtime;
2809
+ }
2810
+ }
2811
+ return null;
2812
+ }
2813
+ function resolveRuntimeProcess() {
2814
+ let pid = process.ppid;
2815
+ for (let i = 0; i < 10; i++) {
2816
+ try {
2817
+ const info = execSync2(`ps -p ${pid} -o ppid=,comm=`, {
2818
+ encoding: "utf8",
2819
+ timeout: 2e3
2820
+ }).trim();
2821
+ const match = info.match(/^\s*(\d+)\s+(.+)$/);
2822
+ if (!match) break;
2823
+ const [, ppid, cmd] = match;
2824
+ const runtime = detectRuntimeFromCommand(cmd ?? "");
2825
+ if (runtime) {
2826
+ return { pid: String(pid), runtime };
2827
+ }
2828
+ pid = parseInt(ppid, 10);
2829
+ if (pid <= 1) break;
2830
+ } catch {
2831
+ break;
2832
+ }
2833
+ }
2834
+ return null;
2835
+ }
2836
+ function getSessionKey() {
2837
+ if (_cached) return _cached;
2838
+ if (process.env.EXE_SESSION_KEY) {
2839
+ _cached = process.env.EXE_SESSION_KEY;
2840
+ return _cached;
2841
+ }
2842
+ const resolved = resolveRuntimeProcess();
2843
+ if (resolved) {
2844
+ _cachedRuntime = resolved.runtime;
2845
+ _cached = resolved.pid;
2846
+ return _cached;
2847
+ }
2848
+ _cached = process.env.CLAUDE_CODE_SSE_PORT ?? String(process.ppid);
2849
+ return _cached;
2850
+ }
2851
+ var _cached, _cachedRuntime, RUNTIME_COMMANDS;
2852
+ var init_session_key = __esm({
2853
+ "src/lib/session-key.ts"() {
2854
+ "use strict";
2855
+ _cached = null;
2856
+ _cachedRuntime = null;
2857
+ RUNTIME_COMMANDS = {
2858
+ claude: ["claude", "claude.exe", "claude-native"],
2859
+ codex: ["codex"],
2860
+ opencode: ["opencode"]
2861
+ };
2862
+ }
2863
+ });
2864
+
2865
+ // src/lib/tmux-transport.ts
2866
+ var tmux_transport_exports = {};
2867
+ __export(tmux_transport_exports, {
2868
+ TmuxTransport: () => TmuxTransport
2869
+ });
2870
+ import { execFileSync } from "child_process";
2871
+ var QUIET, TmuxTransport;
2872
+ var init_tmux_transport = __esm({
2873
+ "src/lib/tmux-transport.ts"() {
2874
+ "use strict";
2875
+ QUIET = {
2876
+ encoding: "utf8",
2877
+ stdio: ["pipe", "pipe", "pipe"]
2878
+ };
2879
+ TmuxTransport = class {
2880
+ getMySession() {
2881
+ try {
2882
+ return execFileSync("tmux", ["display-message", "-p", "#{session_name}"], QUIET).trim() || null;
2883
+ } catch {
2884
+ return null;
1983
2885
  }
1984
- for (const handler of this.globalHandlers) {
1985
- try {
1986
- handler(event);
1987
- } catch {
1988
- }
2886
+ }
2887
+ listSessions() {
2888
+ try {
2889
+ return execFileSync("tmux", ["list-sessions", "-F", "#{session_name}"], QUIET).trim().split("\n").filter(Boolean);
2890
+ } catch {
2891
+ return [];
1989
2892
  }
1990
2893
  }
1991
- /** Subscribe to a specific event type */
1992
- on(type, handler) {
1993
- if (!this.handlers.has(type)) {
1994
- this.handlers.set(type, /* @__PURE__ */ new Set());
2894
+ isAlive(target) {
2895
+ try {
2896
+ const sessions = this.listSessions();
2897
+ if (!sessions.includes(target)) return false;
2898
+ const paneStatus = execFileSync(
2899
+ "tmux",
2900
+ ["list-panes", "-t", target, "-F", "#{pane_dead}"],
2901
+ QUIET
2902
+ ).trim();
2903
+ return paneStatus !== "1";
2904
+ } catch {
2905
+ return false;
1995
2906
  }
1996
- this.handlers.get(type).add(handler);
1997
2907
  }
1998
- /** Subscribe to ALL events */
1999
- onAny(handler) {
2000
- this.globalHandlers.add(handler);
2908
+ sendKeys(target, keys) {
2909
+ execFileSync("tmux", ["send-keys", "-t", target, keys, "Enter"], QUIET);
2001
2910
  }
2002
- /** Unsubscribe from a specific event type */
2003
- off(type, handler) {
2004
- this.handlers.get(type)?.delete(handler);
2911
+ /**
2912
+ * Send text as literal characters, then submit with Enter as a separate call.
2913
+ * Fixes Codex intercom bug: long text + Enter in one send-keys blast causes
2914
+ * Codex to drop the Enter. Splitting them ensures the text renders before
2915
+ * the submit keystroke arrives.
2916
+ */
2917
+ sendKeysLiteral(target, text) {
2918
+ execFileSync("tmux", ["send-keys", "-t", target, "-l", text], QUIET);
2919
+ execFileSync("tmux", ["send-keys", "-t", target, "Enter"], QUIET);
2005
2920
  }
2006
- /** Unsubscribe from ALL events */
2007
- offAny(handler) {
2008
- this.globalHandlers.delete(handler);
2921
+ capturePane(target, lines) {
2922
+ const args = ["capture-pane", "-t", target, "-p"];
2923
+ if (lines) args.push("-S", `-${lines}`);
2924
+ return execFileSync("tmux", args, { ...QUIET, timeout: 3e3 });
2009
2925
  }
2010
- /** Remove all listeners */
2011
- clear() {
2012
- this.handlers.clear();
2013
- this.globalHandlers.clear();
2926
+ isPaneInCopyMode(target) {
2927
+ try {
2928
+ const result = execFileSync(
2929
+ "tmux",
2930
+ ["display-message", "-p", "-t", target, "#{pane_in_mode}"],
2931
+ { ...QUIET, timeout: 3e3 }
2932
+ ).trim();
2933
+ return result === "1";
2934
+ } catch {
2935
+ return false;
2936
+ }
2937
+ }
2938
+ spawn(name, config) {
2939
+ try {
2940
+ const args = ["new-session", "-d", "-s", name];
2941
+ if (config.cwd) args.push("-c", config.cwd);
2942
+ args.push(config.command);
2943
+ execFileSync("tmux", args);
2944
+ return { sessionName: name };
2945
+ } catch (e) {
2946
+ return { sessionName: name, error: `spawn failed: ${e}` };
2947
+ }
2948
+ }
2949
+ kill(target) {
2950
+ try {
2951
+ execFileSync("tmux", ["kill-session", "-t", target], QUIET);
2952
+ } catch {
2953
+ }
2954
+ }
2955
+ pipeLog(target, logFile) {
2956
+ try {
2957
+ const safePath = logFile.replace(/'/g, "'\\''");
2958
+ execFileSync("tmux", ["pipe-pane", "-t", target, `cat >> '${safePath}'`], QUIET);
2959
+ } catch {
2960
+ }
2014
2961
  }
2015
2962
  };
2016
- orgBus = new StateBus();
2017
2963
  }
2018
2964
  });
2019
2965
 
2020
- // src/lib/shard-manager.ts
2021
- var shard_manager_exports = {};
2022
- __export(shard_manager_exports, {
2023
- disposeShards: () => disposeShards,
2024
- ensureShardSchema: () => ensureShardSchema,
2025
- getOpenShardCount: () => getOpenShardCount,
2026
- getReadyShardClient: () => getReadyShardClient,
2027
- getShardClient: () => getShardClient,
2028
- getShardsDir: () => getShardsDir,
2029
- initShardManager: () => initShardManager,
2030
- isShardingEnabled: () => isShardingEnabled,
2031
- listShards: () => listShards,
2032
- shardExists: () => shardExists
2033
- });
2034
- import path5 from "path";
2035
- import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync } from "fs";
2036
- import { createClient as createClient2 } from "@libsql/client";
2037
- function initShardManager(encryptionKey) {
2038
- _encryptionKey = encryptionKey;
2039
- if (!existsSync5(SHARDS_DIR)) {
2040
- mkdirSync2(SHARDS_DIR, { recursive: true });
2966
+ // src/lib/transport.ts
2967
+ function getTransport() {
2968
+ if (!_transport) {
2969
+ const { TmuxTransport: TmuxTransport2 } = (init_tmux_transport(), __toCommonJS(tmux_transport_exports));
2970
+ _transport = new TmuxTransport2();
2041
2971
  }
2042
- _shardingEnabled = true;
2043
- if (_evictionTimer) clearInterval(_evictionTimer);
2044
- _evictionTimer = setInterval(evictIdleShards, EVICTION_INTERVAL_MS);
2045
- _evictionTimer.unref();
2046
- }
2047
- function isShardingEnabled() {
2048
- return _shardingEnabled;
2049
- }
2050
- function getShardsDir() {
2051
- return SHARDS_DIR;
2972
+ return _transport;
2052
2973
  }
2053
- function getShardClient(projectName) {
2054
- if (!_encryptionKey) {
2055
- throw new Error("Shard manager not initialized. Call initShardManager() first.");
2974
+ var _transport;
2975
+ var init_transport = __esm({
2976
+ "src/lib/transport.ts"() {
2977
+ "use strict";
2978
+ _transport = null;
2056
2979
  }
2057
- const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
2058
- if (!safeName) {
2059
- throw new Error(`Invalid project name for shard: "${projectName}"`);
2980
+ });
2981
+
2982
+ // src/lib/cc-agent-support.ts
2983
+ import { execSync as execSync3 } from "child_process";
2984
+ var init_cc_agent_support = __esm({
2985
+ "src/lib/cc-agent-support.ts"() {
2986
+ "use strict";
2060
2987
  }
2061
- const cached = _shards.get(safeName);
2062
- if (cached) {
2063
- _shardLastAccess.set(safeName, Date.now());
2064
- return cached;
2988
+ });
2989
+
2990
+ // src/lib/mcp-prefix.ts
2991
+ var MCP_PRIMARY_KEY, MCP_LEGACY_KEY, MCP_TOOL_PREFIXES;
2992
+ var init_mcp_prefix = __esm({
2993
+ "src/lib/mcp-prefix.ts"() {
2994
+ "use strict";
2995
+ MCP_PRIMARY_KEY = "exe-os";
2996
+ MCP_LEGACY_KEY = "exe-mem";
2997
+ MCP_TOOL_PREFIXES = [
2998
+ `mcp__${MCP_PRIMARY_KEY}__`,
2999
+ `mcp__${MCP_LEGACY_KEY}__`
3000
+ ];
2065
3001
  }
2066
- while (_shards.size >= MAX_OPEN_SHARDS) {
2067
- evictLRU();
3002
+ });
3003
+
3004
+ // src/lib/provider-table.ts
3005
+ var init_provider_table = __esm({
3006
+ "src/lib/provider-table.ts"() {
3007
+ "use strict";
2068
3008
  }
2069
- const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
2070
- const client = createClient2({
2071
- url: `file:${dbPath}`,
2072
- encryptionKey: _encryptionKey
2073
- });
2074
- _shards.set(safeName, client);
2075
- _shardLastAccess.set(safeName, Date.now());
2076
- return client;
2077
- }
2078
- function shardExists(projectName) {
2079
- const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
2080
- return existsSync5(path5.join(SHARDS_DIR, `${safeName}.db`));
2081
- }
2082
- function listShards() {
2083
- if (!existsSync5(SHARDS_DIR)) return [];
2084
- return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
2085
- }
2086
- async function ensureShardSchema(client) {
2087
- await client.execute("PRAGMA journal_mode = WAL");
2088
- await client.execute("PRAGMA busy_timeout = 30000");
2089
- try {
2090
- await client.execute("PRAGMA libsql_vector_search_ef = 128");
2091
- } catch {
3009
+ });
3010
+
3011
+ // src/lib/runtime-table.ts
3012
+ var RUNTIME_TABLE;
3013
+ var init_runtime_table = __esm({
3014
+ "src/lib/runtime-table.ts"() {
3015
+ "use strict";
3016
+ RUNTIME_TABLE = {
3017
+ codex: {
3018
+ binary: "codex",
3019
+ launchMode: "interactive",
3020
+ autoApproveFlag: "--dangerously-bypass-approvals-and-sandbox",
3021
+ inlineFlag: "--no-alt-screen",
3022
+ apiKeyEnv: "OPENAI_API_KEY",
3023
+ defaultModel: "gpt-5.4"
3024
+ },
3025
+ opencode: {
3026
+ binary: "opencode",
3027
+ launchMode: "exec",
3028
+ autoApproveFlag: "--dangerously-skip-permissions",
3029
+ inlineFlag: "",
3030
+ apiKeyEnv: "ANTHROPIC_API_KEY",
3031
+ defaultModel: "anthropic/claude-sonnet-4-6"
3032
+ }
3033
+ };
2092
3034
  }
2093
- await client.executeMultiple(`
2094
- CREATE TABLE IF NOT EXISTS memories (
2095
- id TEXT PRIMARY KEY,
2096
- agent_id TEXT NOT NULL,
2097
- agent_role TEXT NOT NULL,
2098
- session_id TEXT NOT NULL,
2099
- timestamp TEXT NOT NULL,
2100
- tool_name TEXT NOT NULL,
2101
- project_name TEXT NOT NULL,
2102
- has_error INTEGER NOT NULL DEFAULT 0,
2103
- raw_text TEXT NOT NULL,
2104
- vector F32_BLOB(1024),
2105
- version INTEGER NOT NULL DEFAULT 0
2106
- );
3035
+ });
2107
3036
 
2108
- CREATE INDEX IF NOT EXISTS idx_memories_agent ON memories(agent_id);
2109
- CREATE INDEX IF NOT EXISTS idx_memories_timestamp ON memories(timestamp);
2110
- CREATE INDEX IF NOT EXISTS idx_memories_agent_project ON memories(agent_id, project_name);
2111
- `);
2112
- await client.executeMultiple(`
2113
- CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
2114
- raw_text,
2115
- content='memories',
2116
- content_rowid='rowid'
2117
- );
3037
+ // src/lib/agent-config.ts
3038
+ import { readFileSync as readFileSync5, writeFileSync as writeFileSync3, existsSync as existsSync6 } from "fs";
3039
+ import path7 from "path";
3040
+ var AGENT_CONFIG_PATH, DEFAULT_MODELS;
3041
+ var init_agent_config = __esm({
3042
+ "src/lib/agent-config.ts"() {
3043
+ "use strict";
3044
+ init_config();
3045
+ init_runtime_table();
3046
+ init_secure_files();
3047
+ AGENT_CONFIG_PATH = path7.join(EXE_AI_DIR, "agent-config.json");
3048
+ DEFAULT_MODELS = {
3049
+ claude: "claude-opus-4.6",
3050
+ codex: RUNTIME_TABLE.codex?.defaultModel ?? "gpt-5.4",
3051
+ opencode: RUNTIME_TABLE.opencode?.defaultModel ?? "anthropic/claude-sonnet-4-6"
3052
+ };
3053
+ }
3054
+ });
2118
3055
 
2119
- CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
2120
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
2121
- END;
3056
+ // src/lib/intercom-queue.ts
3057
+ import { readFileSync as readFileSync6, writeFileSync as writeFileSync4, renameSync as renameSync3, existsSync as existsSync7, mkdirSync as mkdirSync2 } from "fs";
3058
+ import path8 from "path";
3059
+ import os6 from "os";
3060
+ var QUEUE_PATH, TTL_MS, INTERCOM_LOG;
3061
+ var init_intercom_queue = __esm({
3062
+ "src/lib/intercom-queue.ts"() {
3063
+ "use strict";
3064
+ QUEUE_PATH = path8.join(os6.homedir(), ".exe-os", "intercom-queue.json");
3065
+ TTL_MS = 60 * 60 * 1e3;
3066
+ INTERCOM_LOG = path8.join(os6.homedir(), ".exe-os", "intercom.log");
3067
+ }
3068
+ });
2122
3069
 
2123
- CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
2124
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
2125
- END;
3070
+ // src/lib/license.ts
3071
+ import { readFileSync as readFileSync7, writeFileSync as writeFileSync5, existsSync as existsSync8, mkdirSync as mkdirSync3 } from "fs";
3072
+ import { randomUUID as randomUUID2 } from "crypto";
3073
+ import { createRequire as createRequire2 } from "module";
3074
+ import { pathToFileURL as pathToFileURL2 } from "url";
3075
+ import os7 from "os";
3076
+ import path9 from "path";
3077
+ import { jwtVerify, importSPKI } from "jose";
3078
+ var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH;
3079
+ var init_license = __esm({
3080
+ "src/lib/license.ts"() {
3081
+ "use strict";
3082
+ init_config();
3083
+ LICENSE_PATH = path9.join(EXE_AI_DIR, "license.key");
3084
+ CACHE_PATH = path9.join(EXE_AI_DIR, "license-cache.json");
3085
+ DEVICE_ID_PATH = path9.join(EXE_AI_DIR, "device-id");
3086
+ }
3087
+ });
2126
3088
 
2127
- CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
2128
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
2129
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
2130
- END;
2131
- `);
2132
- for (const col of [
2133
- "ALTER TABLE memories ADD COLUMN task_id TEXT",
2134
- "ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
2135
- "ALTER TABLE memories ADD COLUMN author_device_id TEXT",
2136
- "ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'",
2137
- "ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
2138
- "ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
2139
- "ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
2140
- "ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0",
2141
- "ALTER TABLE memories ADD COLUMN content_hash TEXT",
2142
- "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT",
2143
- "ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7",
2144
- "ALTER TABLE memories ADD COLUMN last_accessed TEXT",
2145
- // Wiki linkage columns (must match database.ts)
2146
- "ALTER TABLE memories ADD COLUMN workspace_id TEXT",
2147
- "ALTER TABLE memories ADD COLUMN document_id TEXT",
2148
- "ALTER TABLE memories ADD COLUMN user_id TEXT",
2149
- "ALTER TABLE memories ADD COLUMN char_offset INTEGER",
2150
- "ALTER TABLE memories ADD COLUMN page_number INTEGER",
2151
- // Source provenance columns (must match database.ts)
2152
- "ALTER TABLE memories ADD COLUMN source_path TEXT",
2153
- "ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'",
2154
- "ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3",
2155
- "ALTER TABLE memories ADD COLUMN supersedes_id TEXT",
2156
- // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
2157
- "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
2158
- "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
2159
- "ALTER TABLE memories ADD COLUMN trajectory TEXT",
2160
- // Metadata enrichment columns (must match database.ts)
2161
- "ALTER TABLE memories ADD COLUMN intent TEXT",
2162
- "ALTER TABLE memories ADD COLUMN outcome TEXT",
2163
- "ALTER TABLE memories ADD COLUMN domain TEXT",
2164
- "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
2165
- "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
2166
- "ALTER TABLE memories ADD COLUMN chain_position TEXT",
2167
- "ALTER TABLE memories ADD COLUMN review_status TEXT",
2168
- "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
2169
- "ALTER TABLE memories ADD COLUMN file_paths TEXT",
2170
- "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
2171
- "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
2172
- "ALTER TABLE memories ADD COLUMN token_cost REAL",
2173
- "ALTER TABLE memories ADD COLUMN audience TEXT",
2174
- "ALTER TABLE memories ADD COLUMN language_type TEXT",
2175
- "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
2176
- ]) {
2177
- try {
2178
- await client.execute(col);
2179
- } catch {
2180
- }
3089
+ // src/lib/plan-limits.ts
3090
+ import { readFileSync as readFileSync8, existsSync as existsSync9 } from "fs";
3091
+ import path10 from "path";
3092
+ var CACHE_PATH2;
3093
+ var init_plan_limits = __esm({
3094
+ "src/lib/plan-limits.ts"() {
3095
+ "use strict";
3096
+ init_database();
3097
+ init_employees();
3098
+ init_license();
3099
+ init_config();
3100
+ CACHE_PATH2 = path10.join(EXE_AI_DIR, "license-cache.json");
2181
3101
  }
2182
- for (const idx of [
2183
- "CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)",
2184
- "CREATE INDEX IF NOT EXISTS idx_memories_supersedes ON memories(supersedes_id) WHERE supersedes_id IS NOT NULL"
2185
- ]) {
2186
- try {
2187
- await client.execute(idx);
2188
- } catch {
2189
- }
3102
+ });
3103
+
3104
+ // src/lib/tmux-routing.ts
3105
+ import { readFileSync as readFileSync9, writeFileSync as writeFileSync6, mkdirSync as mkdirSync4, existsSync as existsSync10, appendFileSync, readdirSync } from "fs";
3106
+ import path11 from "path";
3107
+ import os8 from "os";
3108
+ import { fileURLToPath as fileURLToPath2 } from "url";
3109
+ function getMySession() {
3110
+ return getTransport().getMySession();
3111
+ }
3112
+ function extractRootExe(name) {
3113
+ if (!name) return null;
3114
+ if (!name.includes("-")) return name;
3115
+ const parts = name.split("-").filter(Boolean);
3116
+ return parts.length > 0 ? parts[parts.length - 1] : null;
3117
+ }
3118
+ function getParentExe(sessionKey) {
3119
+ try {
3120
+ const data = JSON.parse(readFileSync9(path11.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
3121
+ return data.parentExe || null;
3122
+ } catch {
3123
+ return null;
2190
3124
  }
3125
+ }
3126
+ function resolveExeSession() {
3127
+ const mySession = getMySession();
3128
+ if (!mySession) return null;
3129
+ const fromSessionName = extractRootExe(mySession);
2191
3130
  try {
2192
- await client.execute("CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)");
3131
+ const key = getSessionKey();
3132
+ const parentExe = getParentExe(key);
3133
+ if (parentExe) {
3134
+ const fromCache = extractRootExe(parentExe) ?? parentExe;
3135
+ if (fromSessionName && fromCache !== fromSessionName) {
3136
+ process.stderr.write(
3137
+ `[tmux-routing] WARN: cache says "${fromCache}" but session name says "${fromSessionName}". Trusting session name.
3138
+ `
3139
+ );
3140
+ return fromSessionName;
3141
+ }
3142
+ return fromCache;
3143
+ }
2193
3144
  } catch {
2194
3145
  }
2195
- for (const idx of [
2196
- "CREATE INDEX IF NOT EXISTS idx_memories_workspace ON memories(workspace_id)",
2197
- "CREATE INDEX IF NOT EXISTS idx_memories_document ON memories(document_id)",
2198
- "CREATE INDEX IF NOT EXISTS idx_memories_user ON memories(user_id)"
2199
- ]) {
2200
- try {
2201
- await client.execute(idx);
2202
- } catch {
2203
- }
3146
+ return fromSessionName ?? mySession;
3147
+ }
3148
+ var SPAWN_LOCK_DIR, SESSION_CACHE, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS;
3149
+ var init_tmux_routing = __esm({
3150
+ "src/lib/tmux-routing.ts"() {
3151
+ "use strict";
3152
+ init_session_registry();
3153
+ init_session_key();
3154
+ init_transport();
3155
+ init_cc_agent_support();
3156
+ init_mcp_prefix();
3157
+ init_provider_table();
3158
+ init_agent_config();
3159
+ init_runtime_table();
3160
+ init_intercom_queue();
3161
+ init_plan_limits();
3162
+ init_employees();
3163
+ SPAWN_LOCK_DIR = path11.join(os8.homedir(), ".exe-os", "spawn-locks");
3164
+ SESSION_CACHE = path11.join(os8.homedir(), ".exe-os", "session-cache");
3165
+ INTERCOM_LOG2 = path11.join(os8.homedir(), ".exe-os", "intercom.log");
3166
+ DEBOUNCE_FILE = path11.join(SESSION_CACHE, "intercom-debounce.json");
3167
+ DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
2204
3168
  }
2205
- await client.executeMultiple(`
2206
- CREATE TABLE IF NOT EXISTS entities (
2207
- id TEXT PRIMARY KEY,
2208
- name TEXT NOT NULL,
2209
- type TEXT NOT NULL,
2210
- first_seen TEXT NOT NULL,
2211
- last_seen TEXT NOT NULL,
2212
- properties TEXT DEFAULT '{}',
2213
- UNIQUE(name, type)
2214
- );
2215
-
2216
- CREATE TABLE IF NOT EXISTS relationships (
2217
- id TEXT PRIMARY KEY,
2218
- source_entity_id TEXT NOT NULL,
2219
- target_entity_id TEXT NOT NULL,
2220
- type TEXT NOT NULL,
2221
- weight REAL DEFAULT 1.0,
2222
- timestamp TEXT NOT NULL,
2223
- properties TEXT DEFAULT '{}',
2224
- UNIQUE(source_entity_id, target_entity_id, type)
2225
- );
2226
-
2227
- CREATE TABLE IF NOT EXISTS entity_memories (
2228
- entity_id TEXT NOT NULL,
2229
- memory_id TEXT NOT NULL,
2230
- PRIMARY KEY (entity_id, memory_id)
2231
- );
2232
-
2233
- CREATE TABLE IF NOT EXISTS relationship_memories (
2234
- relationship_id TEXT NOT NULL,
2235
- memory_id TEXT NOT NULL,
2236
- PRIMARY KEY (relationship_id, memory_id)
2237
- );
2238
-
2239
- CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
2240
- CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
2241
- CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
2242
- CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
2243
- CREATE INDEX IF NOT EXISTS idx_relationships_type ON relationships(type);
2244
-
2245
- CREATE TABLE IF NOT EXISTS hyperedges (
2246
- id TEXT PRIMARY KEY,
2247
- label TEXT NOT NULL,
2248
- relation TEXT NOT NULL,
2249
- confidence REAL DEFAULT 1.0,
2250
- timestamp TEXT NOT NULL
2251
- );
3169
+ });
2252
3170
 
2253
- CREATE TABLE IF NOT EXISTS hyperedge_nodes (
2254
- hyperedge_id TEXT NOT NULL,
2255
- entity_id TEXT NOT NULL,
2256
- PRIMARY KEY (hyperedge_id, entity_id)
2257
- );
2258
- `);
2259
- for (const col of [
2260
- "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
2261
- "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
2262
- ]) {
2263
- try {
2264
- await client.execute(col);
2265
- } catch {
2266
- }
3171
+ // src/lib/task-scope.ts
3172
+ function getCurrentSessionScope() {
3173
+ try {
3174
+ return resolveExeSession();
3175
+ } catch {
3176
+ return null;
2267
3177
  }
2268
3178
  }
2269
- async function getReadyShardClient(projectName) {
2270
- const client = getShardClient(projectName);
2271
- await ensureShardSchema(client);
2272
- return client;
3179
+ function strictSessionScopeFilter(sessionScope, tableAlias) {
3180
+ const scope = sessionScope !== void 0 ? sessionScope : getCurrentSessionScope();
3181
+ if (!scope) return { sql: "", args: [] };
3182
+ const col = tableAlias ? `${tableAlias}.session_scope` : "session_scope";
3183
+ return {
3184
+ sql: ` AND ${col} = ?`,
3185
+ args: [scope]
3186
+ };
2273
3187
  }
2274
- function evictLRU() {
2275
- let oldest = null;
2276
- let oldestTime = Infinity;
2277
- for (const [name, time] of _shardLastAccess) {
2278
- if (time < oldestTime) {
2279
- oldestTime = time;
2280
- oldest = name;
2281
- }
2282
- }
2283
- if (oldest) {
2284
- const client = _shards.get(oldest);
2285
- if (client) {
2286
- client.close();
2287
- }
2288
- _shards.delete(oldest);
2289
- _shardLastAccess.delete(oldest);
3188
+ var init_task_scope = __esm({
3189
+ "src/lib/task-scope.ts"() {
3190
+ "use strict";
3191
+ init_tmux_routing();
2290
3192
  }
3193
+ });
3194
+
3195
+ // src/lib/keychain.ts
3196
+ import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
3197
+ import { existsSync as existsSync11 } from "fs";
3198
+ import path12 from "path";
3199
+ import os9 from "os";
3200
+ function getKeyDir() {
3201
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path12.join(os9.homedir(), ".exe-os");
2291
3202
  }
2292
- function evictIdleShards() {
2293
- const now = Date.now();
2294
- const toEvict = [];
2295
- for (const [name, lastAccess] of _shardLastAccess) {
2296
- if (now - lastAccess > SHARD_IDLE_MS) {
2297
- toEvict.push(name);
2298
- }
3203
+ function getKeyPath() {
3204
+ return path12.join(getKeyDir(), "master.key");
3205
+ }
3206
+ async function tryKeytar() {
3207
+ try {
3208
+ return await import("keytar");
3209
+ } catch {
3210
+ return null;
2299
3211
  }
2300
- for (const name of toEvict) {
2301
- const client = _shards.get(name);
2302
- if (client) {
2303
- client.close();
3212
+ }
3213
+ async function getMasterKey() {
3214
+ const keytar = await tryKeytar();
3215
+ if (keytar) {
3216
+ try {
3217
+ const stored = await keytar.getPassword(SERVICE, ACCOUNT);
3218
+ if (stored) {
3219
+ return Buffer.from(stored, "base64");
3220
+ }
3221
+ } catch {
2304
3222
  }
2305
- _shards.delete(name);
2306
- _shardLastAccess.delete(name);
2307
3223
  }
2308
- }
2309
- function getOpenShardCount() {
2310
- return _shards.size;
2311
- }
2312
- function disposeShards() {
2313
- if (_evictionTimer) {
2314
- clearInterval(_evictionTimer);
2315
- _evictionTimer = null;
3224
+ const keyPath = getKeyPath();
3225
+ if (!existsSync11(keyPath)) {
3226
+ process.stderr.write(
3227
+ `[keychain] Key not found at ${keyPath} (HOME=${os9.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
3228
+ `
3229
+ );
3230
+ return null;
2316
3231
  }
2317
- for (const [, client] of _shards) {
2318
- client.close();
3232
+ try {
3233
+ const content = await readFile3(keyPath, "utf-8");
3234
+ return Buffer.from(content.trim(), "base64");
3235
+ } catch (err) {
3236
+ process.stderr.write(
3237
+ `[keychain] Key read failed at ${keyPath}: ${err instanceof Error ? err.message : String(err)}
3238
+ `
3239
+ );
3240
+ return null;
2319
3241
  }
2320
- _shards.clear();
2321
- _shardLastAccess.clear();
2322
- _shardingEnabled = false;
2323
- _encryptionKey = null;
2324
3242
  }
2325
- var SHARDS_DIR, SHARD_IDLE_MS, MAX_OPEN_SHARDS, EVICTION_INTERVAL_MS, _shards, _shardLastAccess, _evictionTimer, _encryptionKey, _shardingEnabled;
2326
- var init_shard_manager = __esm({
2327
- "src/lib/shard-manager.ts"() {
3243
+ var SERVICE, ACCOUNT;
3244
+ var init_keychain = __esm({
3245
+ "src/lib/keychain.ts"() {
2328
3246
  "use strict";
2329
- init_config();
2330
- SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
2331
- SHARD_IDLE_MS = 5 * 60 * 1e3;
2332
- MAX_OPEN_SHARDS = 10;
2333
- EVICTION_INTERVAL_MS = 60 * 1e3;
2334
- _shards = /* @__PURE__ */ new Map();
2335
- _shardLastAccess = /* @__PURE__ */ new Map();
2336
- _evictionTimer = null;
2337
- _encryptionKey = null;
2338
- _shardingEnabled = false;
3247
+ SERVICE = "exe-mem";
3248
+ ACCOUNT = "master-key";
2339
3249
  }
2340
3250
  });
2341
3251
 
2342
- // src/lib/platform-procedures.ts
2343
- var PLATFORM_PROCEDURES, PLATFORM_PROCEDURE_TITLES;
2344
- var init_platform_procedures = __esm({
2345
- "src/lib/platform-procedures.ts"() {
3252
+ // src/lib/state-bus.ts
3253
+ var StateBus, orgBus;
3254
+ var init_state_bus = __esm({
3255
+ "src/lib/state-bus.ts"() {
2346
3256
  "use strict";
2347
- PLATFORM_PROCEDURES = [
2348
- // --- Foundation: what is exe-os ---
2349
- {
2350
- title: "What is exe-os \u2014 the operating model every agent must understand",
2351
- domain: "architecture",
2352
- priority: "p0",
2353
- content: "Exe OS is an AI employee operating system. A founder runs 5-10 AI agents as a real org: COO, CTO, CMO, engineers, and content production specialists. Each agent has identity, expertise, and experience layers \u2014 persistent memory that makes them better over time. All data is local-first, E2EE, owned by the user. The MCP server is the ONLY data interface \u2014 never access the DB directly."
2354
- },
2355
- {
2356
- title: "Mode 1 \u2014 how exe-os runs inside Claude Code",
2357
- domain: "architecture",
2358
- priority: "p0",
2359
- content: "Mode 1: exe-os runs AS hooks + MCP + skills inside Claude Code, Codex, or OpenCode. The founder picks their default tool at setup. The COO manages employees in tmux sessions. Each coordinator session is a separate window/project. Employees run in their own tmux panes via create_task auto-spawn. The founder talks to the COO; the COO orchestrates the team. The tool is the shell, exe-os is the brain."
2360
- },
2361
- {
2362
- title: "Sessions explained \u2014 coordinator session names and projects",
2363
- domain: "architecture",
2364
- priority: "p0",
2365
- content: "Each coordinator session is an isolated project session. One might be exe-os development, another might be exe-wiki. Each session spawns its own employees using {employee}-{coordinatorSession}. Sessions share the same memory DB but tasks are scoped to the session that created them. A founder can run multiple projects simultaneously. Sessions never interfere with each other."
2366
- },
2367
- {
2368
- title: "Runtime settings \u2014 COO can view and change tools per agent",
2369
- domain: "workflow",
2370
- priority: "p1",
2371
- content: "exe-os supports three tools: Claude Code (Anthropic), Codex (OpenAI), and OpenCode (open source, 75+ providers). Each agent can use a different tool and model. COO uses set_agent_config MCP tool to view or change settings. Call with no args to show all agents. Call with agent_id + runtime + model to change. Users can also run `exe-os settings` from terminal for interactive arrow-key selection."
2372
- },
2373
- // --- Hierarchy and dispatch ---
2374
- {
2375
- title: "Chain of command \u2014 who talks to whom",
2376
- domain: "workflow",
2377
- priority: "p0",
2378
- content: "Founder -> COO -> CTO/CMO. CTO -> engineers. CMO -> content production. Never skip levels: the COO does not bypass managers for specialist work. Specialists report to their manager. If you need cross-team info, use ask_team_memory \u2014 don't read other agents' task folders. Each level owns dispatch downward and review upward."
2379
- },
2380
- {
2381
- title: "Single dispatch path \u2014 create_task only",
2382
- domain: "workflow",
2383
- priority: "p0",
2384
- content: "create_task is the ONLY way to dispatch work to another agent. No direct ensureEmployee calls, no manual tmux spawns, no send_message for actionable work. create_task \u2192 system auto-spawns \u2192 session correctly named. ONE PATH. No backdoors. No exceptions."
2385
- },
2386
- // --- Session isolation ---
2387
- {
2388
- title: "Session scoping \u2014 stay in your coordinator boundary",
2389
- domain: "security",
2390
- priority: "p0",
2391
- content: "Session scoping is mandatory. Managers dispatch to workers within their own coordinator session ONLY. Employee sessions use {employee}-{coordinatorSession}. Cross-session dispatch is blocked by the system. Verify session names before dispatch. Tasks are scoped to the creating coordinator session."
2392
- },
2393
- {
2394
- title: "Session isolation \u2014 never touch another session's work",
2395
- domain: "workflow",
2396
- priority: "p0",
2397
- content: "Sessions are isolated. A coordinator session owns ONLY tasks it dispatched. (1) Never close/update/cancel tasks from another coordinator session. (2) Never review work from a different session \u2014 report that it belongs to another session and skip. (3) Ignore other sessions' items in list_tasks results. (4) Employees inherit session: employee sessions work ONLY on their parent coordinator session's tasks. Cross-session work is a system violation."
2398
- },
2399
- // --- Engineering: session scoping in code ---
2400
- {
2401
- title: "Three-dimensional scoping \u2014 session, project, role \u2014 enforced in every query",
2402
- domain: "architecture",
2403
- priority: "p0",
2404
- content: "Every DB query, notification, review count, and task operation MUST be scoped on 3 dimensions: (1) Session \u2014 filter by session_scope matching the current coordinator session. (2) Project \u2014 filter by project_name. (3) Role \u2014 agents only see data at their hierarchy level. When writing ANY function that touches tasks, reviews, messages, or notifications: always accept a sessionScope parameter and pass it to the SQL WHERE clause. Unscoped queries are bugs. Test by running 2+ coordinator sessions simultaneously."
2405
- },
2406
- // --- Hard constraints ---
2407
- {
2408
- title: "What you CANNOT do in exe-os \u2014 hard constraints",
2409
- domain: "security",
2410
- priority: "p0",
2411
- content: "NEVER: (1) Access the database directly \u2014 it's SQLCipher encrypted, always fails. Use MCP tools only. (2) Manually spawn tmux sessions \u2014 create_task handles it. (3) Run git checkout main \u2014 agents work in worktrees. (4) Modify another agent's in-progress task. (5) Push to remote \u2014 the COO reviews and pushes. (6) Skip update_task(done) \u2014 it's the ONLY way your work gets reviewed. (7) Run git init."
2412
- },
2413
- // --- Operations ---
2414
- {
2415
- title: "Managers must supervise deployed workers",
2416
- domain: "workflow",
2417
- priority: "p0",
2418
- content: `Every manager (COO/CTO/CMO) who dispatches work to a worker MUST actively monitor them. Check tmux capture-pane every 10 minutes. Verify they're working, not stuck. If idle at prompt with in_progress task \u2192 send intercom. If stuck \u2192 unblock or escalate. "Standing by" without checking is negligence.`
2419
- },
2420
- {
2421
- title: "COO boot health check \u2014 memory, cloud sync, daemon on every launch",
2422
- domain: "workflow",
2423
- priority: "p0",
2424
- content: "On every /exe boot, COO MUST check system health BEFORE other work: (1) daemon \u2014 is exed PID alive, (2) cloud sync \u2014 grep workers.log for recent cloud-sync errors, (3) memory count \u2014 total in DB, (4) sync delta \u2014 local vs cloud storage_bytes. Report as 4-line status table. If ANY check fails, surface to founder immediately. Do not proceed to tasks until health confirmed."
2425
- },
2426
- {
2427
- title: "exe-build-adv mandatory for 3+ files",
2428
- domain: "workflow",
2429
- priority: "p0",
2430
- content: "exe-build-adv is MANDATORY for ALL work touching 3+ files. Run /exe-build-adv --auto BEFORE implementation. Pipeline: Spec \u2192 AC \u2192 Tests \u2192 Evaluate \u2192 Fix. No multi-file feature ships without pipeline artifacts. No exceptions \u2014 managers reject work without them."
2431
- },
2432
- {
2433
- title: "Desktop and TUI are the same product",
2434
- domain: "architecture",
2435
- priority: "p0",
2436
- content: "Desktop and TUI are the SAME product in different renderers. Same data contracts, same interactions, same acceptance criteria. Desktop tab specs in ARCHITECTURE.md ARE the TUI specs. When building TUI, cross-reference Desktop spec. Different tab names, identical behavior. Never treat them as separate products."
2437
- },
2438
- // --- Orchestration golden path ---
2439
- {
2440
- title: "Task lifecycle \u2014 the golden path every agent follows",
2441
- domain: "workflow",
2442
- priority: "p0",
2443
- content: "create_task is dispatch + delivery. Task lifecycle: open \u2192 in_progress (you start) \u2192 done (update_task when finished) \u2192 needs_review (reviewer nudged) \u2192 closed (COO only via close_task). DB is the reliable delivery \u2014 intercom is just a speedup nudge. If you finish a task, self-chain: check for next task immediately (step 7). Never wait for a nudge. Never say 'standing by.'"
2444
- },
2445
- {
2446
- title: "Intercom is a speedup, not delivery \u2014 DB is the source of truth",
2447
- domain: "architecture",
2448
- priority: "p0",
2449
- 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."
3257
+ StateBus = class {
3258
+ handlers = /* @__PURE__ */ new Map();
3259
+ globalHandlers = /* @__PURE__ */ new Set();
3260
+ /** Emit an event to all subscribers */
3261
+ emit(event) {
3262
+ const typeHandlers = this.handlers.get(event.type);
3263
+ if (typeHandlers) {
3264
+ for (const handler of typeHandlers) {
3265
+ try {
3266
+ handler(event);
3267
+ } catch {
3268
+ }
3269
+ }
3270
+ }
3271
+ for (const handler of this.globalHandlers) {
3272
+ try {
3273
+ handler(event);
3274
+ } catch {
3275
+ }
3276
+ }
2450
3277
  }
2451
- ];
2452
- PLATFORM_PROCEDURE_TITLES = new Set(
2453
- PLATFORM_PROCEDURES.map((p) => p.title)
2454
- );
3278
+ /** Subscribe to a specific event type */
3279
+ on(type, handler) {
3280
+ if (!this.handlers.has(type)) {
3281
+ this.handlers.set(type, /* @__PURE__ */ new Set());
3282
+ }
3283
+ this.handlers.get(type).add(handler);
3284
+ }
3285
+ /** Subscribe to ALL events */
3286
+ onAny(handler) {
3287
+ this.globalHandlers.add(handler);
3288
+ }
3289
+ /** Unsubscribe from a specific event type */
3290
+ off(type, handler) {
3291
+ this.handlers.get(type)?.delete(handler);
3292
+ }
3293
+ /** Unsubscribe from ALL events */
3294
+ offAny(handler) {
3295
+ this.globalHandlers.delete(handler);
3296
+ }
3297
+ /** Remove all listeners */
3298
+ clear() {
3299
+ this.handlers.clear();
3300
+ this.globalHandlers.clear();
3301
+ }
3302
+ };
3303
+ orgBus = new StateBus();
2455
3304
  }
2456
3305
  });
2457
3306
 
2458
- // src/lib/global-procedures.ts
2459
- var global_procedures_exports = {};
2460
- __export(global_procedures_exports, {
2461
- deactivateGlobalProcedure: () => deactivateGlobalProcedure,
2462
- getGlobalProceduresBlock: () => getGlobalProceduresBlock,
2463
- loadGlobalProcedures: () => loadGlobalProcedures,
2464
- storeGlobalProcedure: () => storeGlobalProcedure
3307
+ // src/lib/shard-manager.ts
3308
+ var shard_manager_exports = {};
3309
+ __export(shard_manager_exports, {
3310
+ disposeShards: () => disposeShards,
3311
+ ensureShardSchema: () => ensureShardSchema,
3312
+ getOpenShardCount: () => getOpenShardCount,
3313
+ getReadyShardClient: () => getReadyShardClient,
3314
+ getShardClient: () => getShardClient,
3315
+ getShardsDir: () => getShardsDir,
3316
+ initShardManager: () => initShardManager,
3317
+ isShardingEnabled: () => isShardingEnabled,
3318
+ listShards: () => listShards,
3319
+ shardExists: () => shardExists
2465
3320
  });
2466
- import { randomUUID } from "crypto";
2467
- async function loadGlobalProcedures() {
2468
- const client = getClient();
2469
- const result = await client.execute({
2470
- sql: "SELECT * FROM global_procedures WHERE active = 1 ORDER BY priority ASC, created_at ASC",
2471
- args: []
2472
- });
2473
- const allRows = result.rows;
2474
- const customerOnly = allRows.filter((p) => !PLATFORM_PROCEDURE_TITLES.has(p.title));
2475
- if (customerOnly.length > 0) {
2476
- _customerCache = customerOnly.map((p) => `### ${p.title}
2477
- ${p.content}`).join("\n\n");
2478
- } else {
2479
- _customerCache = "";
3321
+ import path13 from "path";
3322
+ import { existsSync as existsSync12, mkdirSync as mkdirSync5, readdirSync as readdirSync2 } from "fs";
3323
+ import { createClient as createClient2 } from "@libsql/client";
3324
+ function initShardManager(encryptionKey) {
3325
+ _encryptionKey = encryptionKey;
3326
+ if (!existsSync12(SHARDS_DIR)) {
3327
+ mkdirSync5(SHARDS_DIR, { recursive: true });
2480
3328
  }
2481
- _cacheLoaded = true;
2482
- return customerOnly;
2483
- }
2484
- function getGlobalProceduresBlock() {
2485
- const sections = [];
2486
- if (_platformCache) sections.push(_platformCache);
2487
- if (_cacheLoaded && _customerCache) sections.push(_customerCache);
2488
- if (sections.length === 0) return "";
2489
- return `## Organization-Wide Procedures (MANDATORY \u2014 supersedes all other rules)
2490
-
2491
- ${sections.join("\n\n")}
2492
- `;
3329
+ _shardingEnabled = true;
3330
+ if (_evictionTimer) clearInterval(_evictionTimer);
3331
+ _evictionTimer = setInterval(evictIdleShards, EVICTION_INTERVAL_MS);
3332
+ _evictionTimer.unref();
2493
3333
  }
2494
- async function storeGlobalProcedure(input) {
2495
- const id = randomUUID();
2496
- const now = (/* @__PURE__ */ new Date()).toISOString();
2497
- const client = getClient();
2498
- await client.execute({
2499
- sql: `INSERT INTO global_procedures (id, title, content, priority, domain, active, created_at, updated_at)
2500
- VALUES (?, ?, ?, ?, ?, 1, ?, ?)`,
2501
- args: [id, input.title, input.content, input.priority ?? "p0", input.domain ?? null, now, now]
2502
- });
2503
- await loadGlobalProcedures();
2504
- return id;
3334
+ function isShardingEnabled() {
3335
+ return _shardingEnabled;
2505
3336
  }
2506
- async function deactivateGlobalProcedure(id) {
2507
- const now = (/* @__PURE__ */ new Date()).toISOString();
2508
- const client = getClient();
2509
- const result = await client.execute({
2510
- sql: "UPDATE global_procedures SET active = 0, updated_at = ? WHERE id = ?",
2511
- args: [now, id]
2512
- });
2513
- await loadGlobalProcedures();
2514
- return result.rowsAffected > 0;
3337
+ function getShardsDir() {
3338
+ return SHARDS_DIR;
2515
3339
  }
2516
- var _customerCache, _cacheLoaded, _platformCache;
2517
- var init_global_procedures = __esm({
2518
- "src/lib/global-procedures.ts"() {
2519
- "use strict";
2520
- init_database();
2521
- init_platform_procedures();
2522
- _customerCache = "";
2523
- _cacheLoaded = false;
2524
- _platformCache = PLATFORM_PROCEDURES.map((p) => `### ${p.title}
2525
- ${p.content}`).join("\n\n");
3340
+ function getShardClient(projectName) {
3341
+ if (!_encryptionKey) {
3342
+ throw new Error("Shard manager not initialized. Call initShardManager() first.");
2526
3343
  }
2527
- });
2528
-
2529
- // src/lib/session-registry.ts
2530
- import path6 from "path";
2531
- import os5 from "os";
2532
- var REGISTRY_PATH;
2533
- var init_session_registry = __esm({
2534
- "src/lib/session-registry.ts"() {
2535
- "use strict";
2536
- REGISTRY_PATH = path6.join(os5.homedir(), ".exe-os", "session-registry.json");
3344
+ const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
3345
+ if (!safeName) {
3346
+ throw new Error(`Invalid project name for shard: "${projectName}"`);
2537
3347
  }
2538
- });
2539
-
2540
- // src/lib/session-key.ts
2541
- import { execSync as execSync2 } from "child_process";
2542
- function normalizeCommand(command) {
2543
- const trimmed = command.trim().toLowerCase();
2544
- const parts = trimmed.split(/[\\/]/);
2545
- return parts[parts.length - 1] ?? trimmed;
2546
- }
2547
- function detectRuntimeFromCommand(command) {
2548
- const normalized = normalizeCommand(command);
2549
- for (const [runtime, commands] of Object.entries(RUNTIME_COMMANDS)) {
2550
- if (commands.includes(normalized)) {
2551
- return runtime;
2552
- }
3348
+ const cached = _shards.get(safeName);
3349
+ if (cached) {
3350
+ _shardLastAccess.set(safeName, Date.now());
3351
+ return cached;
2553
3352
  }
2554
- return null;
2555
- }
2556
- function resolveRuntimeProcess() {
2557
- let pid = process.ppid;
2558
- for (let i = 0; i < 10; i++) {
2559
- try {
2560
- const info = execSync2(`ps -p ${pid} -o ppid=,comm=`, {
2561
- encoding: "utf8",
2562
- timeout: 2e3
2563
- }).trim();
2564
- const match = info.match(/^\s*(\d+)\s+(.+)$/);
2565
- if (!match) break;
2566
- const [, ppid, cmd] = match;
2567
- const runtime = detectRuntimeFromCommand(cmd ?? "");
2568
- if (runtime) {
2569
- return { pid: String(pid), runtime };
2570
- }
2571
- pid = parseInt(ppid, 10);
2572
- if (pid <= 1) break;
2573
- } catch {
2574
- break;
2575
- }
3353
+ while (_shards.size >= MAX_OPEN_SHARDS) {
3354
+ evictLRU();
2576
3355
  }
2577
- return null;
2578
- }
2579
- function getSessionKey() {
2580
- if (_cached) return _cached;
2581
- if (process.env.EXE_SESSION_KEY) {
2582
- _cached = process.env.EXE_SESSION_KEY;
2583
- return _cached;
2584
- }
2585
- const resolved = resolveRuntimeProcess();
2586
- if (resolved) {
2587
- _cachedRuntime = resolved.runtime;
2588
- _cached = resolved.pid;
2589
- return _cached;
2590
- }
2591
- _cached = process.env.CLAUDE_CODE_SSE_PORT ?? String(process.ppid);
2592
- return _cached;
3356
+ const dbPath = path13.join(SHARDS_DIR, `${safeName}.db`);
3357
+ const client = createClient2({
3358
+ url: `file:${dbPath}`,
3359
+ encryptionKey: _encryptionKey
3360
+ });
3361
+ _shards.set(safeName, client);
3362
+ _shardLastAccess.set(safeName, Date.now());
3363
+ return client;
2593
3364
  }
2594
- var _cached, _cachedRuntime, RUNTIME_COMMANDS;
2595
- var init_session_key = __esm({
2596
- "src/lib/session-key.ts"() {
2597
- "use strict";
2598
- _cached = null;
2599
- _cachedRuntime = null;
2600
- RUNTIME_COMMANDS = {
2601
- claude: ["claude", "claude.exe", "claude-native"],
2602
- codex: ["codex"],
2603
- opencode: ["opencode"]
2604
- };
3365
+ function shardExists(projectName) {
3366
+ const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
3367
+ return existsSync12(path13.join(SHARDS_DIR, `${safeName}.db`));
3368
+ }
3369
+ function listShards() {
3370
+ if (!existsSync12(SHARDS_DIR)) return [];
3371
+ return readdirSync2(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
3372
+ }
3373
+ async function ensureShardSchema(client) {
3374
+ await client.execute("PRAGMA journal_mode = WAL");
3375
+ await client.execute("PRAGMA busy_timeout = 30000");
3376
+ try {
3377
+ await client.execute("PRAGMA libsql_vector_search_ef = 128");
3378
+ } catch {
2605
3379
  }
2606
- });
3380
+ await client.executeMultiple(`
3381
+ CREATE TABLE IF NOT EXISTS memories (
3382
+ id TEXT PRIMARY KEY,
3383
+ agent_id TEXT NOT NULL,
3384
+ agent_role TEXT NOT NULL,
3385
+ session_id TEXT NOT NULL,
3386
+ timestamp TEXT NOT NULL,
3387
+ tool_name TEXT NOT NULL,
3388
+ project_name TEXT NOT NULL,
3389
+ has_error INTEGER NOT NULL DEFAULT 0,
3390
+ raw_text TEXT NOT NULL,
3391
+ vector F32_BLOB(1024),
3392
+ version INTEGER NOT NULL DEFAULT 0
3393
+ );
2607
3394
 
2608
- // src/lib/tmux-transport.ts
2609
- var tmux_transport_exports = {};
2610
- __export(tmux_transport_exports, {
2611
- TmuxTransport: () => TmuxTransport
2612
- });
2613
- import { execFileSync } from "child_process";
2614
- var QUIET, TmuxTransport;
2615
- var init_tmux_transport = __esm({
2616
- "src/lib/tmux-transport.ts"() {
2617
- "use strict";
2618
- QUIET = {
2619
- encoding: "utf8",
2620
- stdio: ["pipe", "pipe", "pipe"]
2621
- };
2622
- TmuxTransport = class {
2623
- getMySession() {
2624
- try {
2625
- return execFileSync("tmux", ["display-message", "-p", "#{session_name}"], QUIET).trim() || null;
2626
- } catch {
2627
- return null;
2628
- }
2629
- }
2630
- listSessions() {
2631
- try {
2632
- return execFileSync("tmux", ["list-sessions", "-F", "#{session_name}"], QUIET).trim().split("\n").filter(Boolean);
2633
- } catch {
2634
- return [];
2635
- }
2636
- }
2637
- isAlive(target) {
2638
- try {
2639
- const sessions = this.listSessions();
2640
- if (!sessions.includes(target)) return false;
2641
- const paneStatus = execFileSync(
2642
- "tmux",
2643
- ["list-panes", "-t", target, "-F", "#{pane_dead}"],
2644
- QUIET
2645
- ).trim();
2646
- return paneStatus !== "1";
2647
- } catch {
2648
- return false;
2649
- }
2650
- }
2651
- sendKeys(target, keys) {
2652
- execFileSync("tmux", ["send-keys", "-t", target, keys, "Enter"], QUIET);
2653
- }
2654
- /**
2655
- * Send text as literal characters, then submit with Enter as a separate call.
2656
- * Fixes Codex intercom bug: long text + Enter in one send-keys blast causes
2657
- * Codex to drop the Enter. Splitting them ensures the text renders before
2658
- * the submit keystroke arrives.
2659
- */
2660
- sendKeysLiteral(target, text) {
2661
- execFileSync("tmux", ["send-keys", "-t", target, "-l", text], QUIET);
2662
- execFileSync("tmux", ["send-keys", "-t", target, "Enter"], QUIET);
2663
- }
2664
- capturePane(target, lines) {
2665
- const args = ["capture-pane", "-t", target, "-p"];
2666
- if (lines) args.push("-S", `-${lines}`);
2667
- return execFileSync("tmux", args, { ...QUIET, timeout: 3e3 });
2668
- }
2669
- isPaneInCopyMode(target) {
2670
- try {
2671
- const result = execFileSync(
2672
- "tmux",
2673
- ["display-message", "-p", "-t", target, "#{pane_in_mode}"],
2674
- { ...QUIET, timeout: 3e3 }
2675
- ).trim();
2676
- return result === "1";
2677
- } catch {
2678
- return false;
2679
- }
2680
- }
2681
- spawn(name, config) {
2682
- try {
2683
- const args = ["new-session", "-d", "-s", name];
2684
- if (config.cwd) args.push("-c", config.cwd);
2685
- args.push(config.command);
2686
- execFileSync("tmux", args);
2687
- return { sessionName: name };
2688
- } catch (e) {
2689
- return { sessionName: name, error: `spawn failed: ${e}` };
2690
- }
2691
- }
2692
- kill(target) {
2693
- try {
2694
- execFileSync("tmux", ["kill-session", "-t", target], QUIET);
2695
- } catch {
2696
- }
2697
- }
2698
- pipeLog(target, logFile) {
2699
- try {
2700
- const safePath = logFile.replace(/'/g, "'\\''");
2701
- execFileSync("tmux", ["pipe-pane", "-t", target, `cat >> '${safePath}'`], QUIET);
2702
- } catch {
2703
- }
2704
- }
2705
- };
2706
- }
2707
- });
3395
+ CREATE INDEX IF NOT EXISTS idx_memories_agent ON memories(agent_id);
3396
+ CREATE INDEX IF NOT EXISTS idx_memories_timestamp ON memories(timestamp);
3397
+ CREATE INDEX IF NOT EXISTS idx_memories_agent_project ON memories(agent_id, project_name);
3398
+ `);
3399
+ await client.executeMultiple(`
3400
+ CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
3401
+ raw_text,
3402
+ content='memories',
3403
+ content_rowid='rowid'
3404
+ );
2708
3405
 
2709
- // src/lib/transport.ts
2710
- function getTransport() {
2711
- if (!_transport) {
2712
- const { TmuxTransport: TmuxTransport2 } = (init_tmux_transport(), __toCommonJS(tmux_transport_exports));
2713
- _transport = new TmuxTransport2();
2714
- }
2715
- return _transport;
2716
- }
2717
- var _transport;
2718
- var init_transport = __esm({
2719
- "src/lib/transport.ts"() {
2720
- "use strict";
2721
- _transport = null;
2722
- }
2723
- });
3406
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
3407
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
3408
+ END;
2724
3409
 
2725
- // src/lib/cc-agent-support.ts
2726
- import { execSync as execSync3 } from "child_process";
2727
- var init_cc_agent_support = __esm({
2728
- "src/lib/cc-agent-support.ts"() {
2729
- "use strict";
2730
- }
2731
- });
3410
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
3411
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
3412
+ END;
2732
3413
 
2733
- // src/lib/mcp-prefix.ts
2734
- var MCP_PRIMARY_KEY, MCP_LEGACY_KEY, MCP_TOOL_PREFIXES;
2735
- var init_mcp_prefix = __esm({
2736
- "src/lib/mcp-prefix.ts"() {
2737
- "use strict";
2738
- MCP_PRIMARY_KEY = "exe-os";
2739
- MCP_LEGACY_KEY = "exe-mem";
2740
- MCP_TOOL_PREFIXES = [
2741
- `mcp__${MCP_PRIMARY_KEY}__`,
2742
- `mcp__${MCP_LEGACY_KEY}__`
2743
- ];
3414
+ CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
3415
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
3416
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
3417
+ END;
3418
+ `);
3419
+ for (const col of [
3420
+ "ALTER TABLE memories ADD COLUMN task_id TEXT",
3421
+ "ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
3422
+ "ALTER TABLE memories ADD COLUMN author_device_id TEXT",
3423
+ "ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'",
3424
+ "ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
3425
+ "ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
3426
+ "ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
3427
+ "ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0",
3428
+ "ALTER TABLE memories ADD COLUMN content_hash TEXT",
3429
+ "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT",
3430
+ "ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7",
3431
+ "ALTER TABLE memories ADD COLUMN last_accessed TEXT",
3432
+ // Wiki linkage columns (must match database.ts)
3433
+ "ALTER TABLE memories ADD COLUMN workspace_id TEXT",
3434
+ "ALTER TABLE memories ADD COLUMN document_id TEXT",
3435
+ "ALTER TABLE memories ADD COLUMN user_id TEXT",
3436
+ "ALTER TABLE memories ADD COLUMN char_offset INTEGER",
3437
+ "ALTER TABLE memories ADD COLUMN page_number INTEGER",
3438
+ // Source provenance columns (must match database.ts)
3439
+ "ALTER TABLE memories ADD COLUMN source_path TEXT",
3440
+ "ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'",
3441
+ "ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3",
3442
+ "ALTER TABLE memories ADD COLUMN supersedes_id TEXT",
3443
+ // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
3444
+ "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
3445
+ "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
3446
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
3447
+ // Metadata enrichment columns (must match database.ts)
3448
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
3449
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
3450
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
3451
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
3452
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
3453
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
3454
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
3455
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
3456
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
3457
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
3458
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
3459
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
3460
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
3461
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
3462
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
3463
+ ]) {
3464
+ try {
3465
+ await client.execute(col);
3466
+ } catch {
3467
+ }
2744
3468
  }
2745
- });
2746
-
2747
- // src/lib/provider-table.ts
2748
- var init_provider_table = __esm({
2749
- "src/lib/provider-table.ts"() {
2750
- "use strict";
3469
+ for (const idx of [
3470
+ "CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)",
3471
+ "CREATE INDEX IF NOT EXISTS idx_memories_supersedes ON memories(supersedes_id) WHERE supersedes_id IS NOT NULL"
3472
+ ]) {
3473
+ try {
3474
+ await client.execute(idx);
3475
+ } catch {
3476
+ }
2751
3477
  }
2752
- });
2753
-
2754
- // src/lib/runtime-table.ts
2755
- var RUNTIME_TABLE;
2756
- var init_runtime_table = __esm({
2757
- "src/lib/runtime-table.ts"() {
2758
- "use strict";
2759
- RUNTIME_TABLE = {
2760
- codex: {
2761
- binary: "codex",
2762
- launchMode: "interactive",
2763
- autoApproveFlag: "--dangerously-bypass-approvals-and-sandbox",
2764
- inlineFlag: "--no-alt-screen",
2765
- apiKeyEnv: "OPENAI_API_KEY",
2766
- defaultModel: "gpt-5.4"
2767
- },
2768
- opencode: {
2769
- binary: "opencode",
2770
- launchMode: "exec",
2771
- autoApproveFlag: "--dangerously-skip-permissions",
2772
- inlineFlag: "",
2773
- apiKeyEnv: "ANTHROPIC_API_KEY",
2774
- defaultModel: "anthropic/claude-sonnet-4-6"
2775
- }
2776
- };
3478
+ try {
3479
+ await client.execute("CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)");
3480
+ } catch {
2777
3481
  }
2778
- });
2779
-
2780
- // src/lib/agent-config.ts
2781
- import { readFileSync as readFileSync3, writeFileSync as writeFileSync2, existsSync as existsSync6 } from "fs";
2782
- import path7 from "path";
2783
- var AGENT_CONFIG_PATH, DEFAULT_MODELS;
2784
- var init_agent_config = __esm({
2785
- "src/lib/agent-config.ts"() {
2786
- "use strict";
2787
- init_config();
2788
- init_runtime_table();
2789
- init_secure_files();
2790
- AGENT_CONFIG_PATH = path7.join(EXE_AI_DIR, "agent-config.json");
2791
- DEFAULT_MODELS = {
2792
- claude: "claude-opus-4",
2793
- codex: RUNTIME_TABLE.codex?.defaultModel ?? "gpt-5.4",
2794
- opencode: RUNTIME_TABLE.opencode?.defaultModel ?? "anthropic/claude-sonnet-4-6"
2795
- };
3482
+ for (const idx of [
3483
+ "CREATE INDEX IF NOT EXISTS idx_memories_workspace ON memories(workspace_id)",
3484
+ "CREATE INDEX IF NOT EXISTS idx_memories_document ON memories(document_id)",
3485
+ "CREATE INDEX IF NOT EXISTS idx_memories_user ON memories(user_id)"
3486
+ ]) {
3487
+ try {
3488
+ await client.execute(idx);
3489
+ } catch {
3490
+ }
2796
3491
  }
2797
- });
3492
+ await client.executeMultiple(`
3493
+ CREATE TABLE IF NOT EXISTS entities (
3494
+ id TEXT PRIMARY KEY,
3495
+ name TEXT NOT NULL,
3496
+ type TEXT NOT NULL,
3497
+ first_seen TEXT NOT NULL,
3498
+ last_seen TEXT NOT NULL,
3499
+ properties TEXT DEFAULT '{}',
3500
+ UNIQUE(name, type)
3501
+ );
2798
3502
 
2799
- // src/lib/intercom-queue.ts
2800
- import { readFileSync as readFileSync4, writeFileSync as writeFileSync3, renameSync as renameSync3, existsSync as existsSync7, mkdirSync as mkdirSync3 } from "fs";
2801
- import path8 from "path";
2802
- import os6 from "os";
2803
- var QUEUE_PATH, TTL_MS, INTERCOM_LOG;
2804
- var init_intercom_queue = __esm({
2805
- "src/lib/intercom-queue.ts"() {
2806
- "use strict";
2807
- QUEUE_PATH = path8.join(os6.homedir(), ".exe-os", "intercom-queue.json");
2808
- TTL_MS = 60 * 60 * 1e3;
2809
- INTERCOM_LOG = path8.join(os6.homedir(), ".exe-os", "intercom.log");
2810
- }
2811
- });
3503
+ CREATE TABLE IF NOT EXISTS relationships (
3504
+ id TEXT PRIMARY KEY,
3505
+ source_entity_id TEXT NOT NULL,
3506
+ target_entity_id TEXT NOT NULL,
3507
+ type TEXT NOT NULL,
3508
+ weight REAL DEFAULT 1.0,
3509
+ timestamp TEXT NOT NULL,
3510
+ properties TEXT DEFAULT '{}',
3511
+ UNIQUE(source_entity_id, target_entity_id, type)
3512
+ );
2812
3513
 
2813
- // src/lib/license.ts
2814
- import { readFileSync as readFileSync5, writeFileSync as writeFileSync4, existsSync as existsSync8, mkdirSync as mkdirSync4 } from "fs";
2815
- import { randomUUID as randomUUID2 } from "crypto";
2816
- import { createRequire as createRequire2 } from "module";
2817
- import { pathToFileURL as pathToFileURL2 } from "url";
2818
- import os7 from "os";
2819
- import path9 from "path";
2820
- import { jwtVerify, importSPKI } from "jose";
2821
- var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH;
2822
- var init_license = __esm({
2823
- "src/lib/license.ts"() {
2824
- "use strict";
2825
- init_config();
2826
- LICENSE_PATH = path9.join(EXE_AI_DIR, "license.key");
2827
- CACHE_PATH = path9.join(EXE_AI_DIR, "license-cache.json");
2828
- DEVICE_ID_PATH = path9.join(EXE_AI_DIR, "device-id");
2829
- }
2830
- });
3514
+ CREATE TABLE IF NOT EXISTS entity_memories (
3515
+ entity_id TEXT NOT NULL,
3516
+ memory_id TEXT NOT NULL,
3517
+ PRIMARY KEY (entity_id, memory_id)
3518
+ );
2831
3519
 
2832
- // src/lib/plan-limits.ts
2833
- import { readFileSync as readFileSync6, existsSync as existsSync9 } from "fs";
2834
- import path10 from "path";
2835
- var CACHE_PATH2;
2836
- var init_plan_limits = __esm({
2837
- "src/lib/plan-limits.ts"() {
2838
- "use strict";
2839
- init_database();
2840
- init_employees();
2841
- init_license();
2842
- init_config();
2843
- CACHE_PATH2 = path10.join(EXE_AI_DIR, "license-cache.json");
2844
- }
2845
- });
3520
+ CREATE TABLE IF NOT EXISTS relationship_memories (
3521
+ relationship_id TEXT NOT NULL,
3522
+ memory_id TEXT NOT NULL,
3523
+ PRIMARY KEY (relationship_id, memory_id)
3524
+ );
3525
+
3526
+ CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
3527
+ CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
3528
+ CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
3529
+ CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
3530
+ CREATE INDEX IF NOT EXISTS idx_relationships_type ON relationships(type);
3531
+
3532
+ CREATE TABLE IF NOT EXISTS hyperedges (
3533
+ id TEXT PRIMARY KEY,
3534
+ label TEXT NOT NULL,
3535
+ relation TEXT NOT NULL,
3536
+ confidence REAL DEFAULT 1.0,
3537
+ timestamp TEXT NOT NULL
3538
+ );
2846
3539
 
2847
- // src/lib/tmux-routing.ts
2848
- import { readFileSync as readFileSync7, writeFileSync as writeFileSync5, mkdirSync as mkdirSync5, existsSync as existsSync10, appendFileSync, readdirSync as readdirSync2 } from "fs";
2849
- import path11 from "path";
2850
- import os8 from "os";
2851
- import { fileURLToPath } from "url";
2852
- function getMySession() {
2853
- return getTransport().getMySession();
3540
+ CREATE TABLE IF NOT EXISTS hyperedge_nodes (
3541
+ hyperedge_id TEXT NOT NULL,
3542
+ entity_id TEXT NOT NULL,
3543
+ PRIMARY KEY (hyperedge_id, entity_id)
3544
+ );
3545
+ `);
3546
+ for (const col of [
3547
+ "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
3548
+ "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
3549
+ ]) {
3550
+ try {
3551
+ await client.execute(col);
3552
+ } catch {
3553
+ }
3554
+ }
2854
3555
  }
2855
- function extractRootExe(name) {
2856
- if (!name) return null;
2857
- if (!name.includes("-")) return name;
2858
- const parts = name.split("-").filter(Boolean);
2859
- return parts.length > 0 ? parts[parts.length - 1] : null;
3556
+ async function getReadyShardClient(projectName) {
3557
+ const client = getShardClient(projectName);
3558
+ await ensureShardSchema(client);
3559
+ return client;
2860
3560
  }
2861
- function getParentExe(sessionKey) {
2862
- try {
2863
- const data = JSON.parse(readFileSync7(path11.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
2864
- return data.parentExe || null;
2865
- } catch {
2866
- return null;
3561
+ function evictLRU() {
3562
+ let oldest = null;
3563
+ let oldestTime = Infinity;
3564
+ for (const [name, time] of _shardLastAccess) {
3565
+ if (time < oldestTime) {
3566
+ oldestTime = time;
3567
+ oldest = name;
3568
+ }
3569
+ }
3570
+ if (oldest) {
3571
+ const client = _shards.get(oldest);
3572
+ if (client) {
3573
+ client.close();
3574
+ }
3575
+ _shards.delete(oldest);
3576
+ _shardLastAccess.delete(oldest);
2867
3577
  }
2868
3578
  }
2869
- function resolveExeSession() {
2870
- const mySession = getMySession();
2871
- if (!mySession) return null;
2872
- const fromSessionName = extractRootExe(mySession);
2873
- try {
2874
- const key = getSessionKey();
2875
- const parentExe = getParentExe(key);
2876
- if (parentExe) {
2877
- const fromCache = extractRootExe(parentExe) ?? parentExe;
2878
- if (fromSessionName && fromCache !== fromSessionName) {
2879
- process.stderr.write(
2880
- `[tmux-routing] WARN: cache says "${fromCache}" but session name says "${fromSessionName}". Trusting session name.
2881
- `
2882
- );
2883
- return fromSessionName;
2884
- }
2885
- return fromCache;
3579
+ function evictIdleShards() {
3580
+ const now = Date.now();
3581
+ const toEvict = [];
3582
+ for (const [name, lastAccess] of _shardLastAccess) {
3583
+ if (now - lastAccess > SHARD_IDLE_MS) {
3584
+ toEvict.push(name);
2886
3585
  }
2887
- } catch {
2888
3586
  }
2889
- return fromSessionName ?? mySession;
3587
+ for (const name of toEvict) {
3588
+ const client = _shards.get(name);
3589
+ if (client) {
3590
+ client.close();
3591
+ }
3592
+ _shards.delete(name);
3593
+ _shardLastAccess.delete(name);
3594
+ }
2890
3595
  }
2891
- var SPAWN_LOCK_DIR, SESSION_CACHE, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS;
2892
- var init_tmux_routing = __esm({
2893
- "src/lib/tmux-routing.ts"() {
3596
+ function getOpenShardCount() {
3597
+ return _shards.size;
3598
+ }
3599
+ function disposeShards() {
3600
+ if (_evictionTimer) {
3601
+ clearInterval(_evictionTimer);
3602
+ _evictionTimer = null;
3603
+ }
3604
+ for (const [, client] of _shards) {
3605
+ client.close();
3606
+ }
3607
+ _shards.clear();
3608
+ _shardLastAccess.clear();
3609
+ _shardingEnabled = false;
3610
+ _encryptionKey = null;
3611
+ }
3612
+ var SHARDS_DIR, SHARD_IDLE_MS, MAX_OPEN_SHARDS, EVICTION_INTERVAL_MS, _shards, _shardLastAccess, _evictionTimer, _encryptionKey, _shardingEnabled;
3613
+ var init_shard_manager = __esm({
3614
+ "src/lib/shard-manager.ts"() {
2894
3615
  "use strict";
2895
- init_session_registry();
2896
- init_session_key();
2897
- init_transport();
2898
- init_cc_agent_support();
2899
- init_mcp_prefix();
2900
- init_provider_table();
2901
- init_agent_config();
2902
- init_runtime_table();
2903
- init_intercom_queue();
2904
- init_plan_limits();
2905
- init_employees();
2906
- SPAWN_LOCK_DIR = path11.join(os8.homedir(), ".exe-os", "spawn-locks");
2907
- SESSION_CACHE = path11.join(os8.homedir(), ".exe-os", "session-cache");
2908
- INTERCOM_LOG2 = path11.join(os8.homedir(), ".exe-os", "intercom.log");
2909
- DEBOUNCE_FILE = path11.join(SESSION_CACHE, "intercom-debounce.json");
2910
- DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
3616
+ init_config();
3617
+ SHARDS_DIR = path13.join(EXE_AI_DIR, "shards");
3618
+ SHARD_IDLE_MS = 5 * 60 * 1e3;
3619
+ MAX_OPEN_SHARDS = 10;
3620
+ EVICTION_INTERVAL_MS = 60 * 1e3;
3621
+ _shards = /* @__PURE__ */ new Map();
3622
+ _shardLastAccess = /* @__PURE__ */ new Map();
3623
+ _evictionTimer = null;
3624
+ _encryptionKey = null;
3625
+ _shardingEnabled = false;
3626
+ }
3627
+ });
3628
+
3629
+ // src/lib/platform-procedures.ts
3630
+ var PLATFORM_PROCEDURES, PLATFORM_PROCEDURE_TITLES;
3631
+ var init_platform_procedures = __esm({
3632
+ "src/lib/platform-procedures.ts"() {
3633
+ "use strict";
3634
+ PLATFORM_PROCEDURES = [
3635
+ // --- Foundation: what is exe-os ---
3636
+ {
3637
+ title: "What is exe-os \u2014 the operating model every agent must understand",
3638
+ domain: "architecture",
3639
+ priority: "p0",
3640
+ content: "Exe OS is an AI employee operating system. A founder runs 5-10 AI agents as a real org: COO, CTO, CMO, engineers, and content production specialists. Each agent has identity, expertise, and experience layers \u2014 persistent memory that makes them better over time. All data is local-first, E2EE, owned by the user. The MCP server is the ONLY data interface \u2014 never access the DB directly."
3641
+ },
3642
+ {
3643
+ title: "Mode 1 \u2014 how exe-os runs inside Claude Code",
3644
+ domain: "architecture",
3645
+ priority: "p0",
3646
+ content: "Mode 1: exe-os runs AS hooks + MCP + skills inside Claude Code, Codex, or OpenCode. The founder picks their default tool at setup. The COO manages employees in tmux sessions. Each coordinator session is a separate window/project. Employees run in their own tmux panes via create_task auto-spawn. The founder talks to the COO; the COO orchestrates the team. The tool is the shell, exe-os is the brain."
3647
+ },
3648
+ {
3649
+ title: "Sessions explained \u2014 coordinator session names and projects",
3650
+ domain: "architecture",
3651
+ priority: "p0",
3652
+ content: "Each coordinator session is an isolated project session. One might be exe-os development, another might be exe-wiki. Each session spawns its own employees using {employee}-{coordinatorSession}. Sessions share the same memory DB but tasks are scoped to the session that created them. A founder can run multiple projects simultaneously. Sessions never interfere with each other."
3653
+ },
3654
+ {
3655
+ title: "Runtime settings \u2014 COO can view and change tools per agent",
3656
+ domain: "workflow",
3657
+ priority: "p1",
3658
+ content: "exe-os supports three tools: Claude Code (Anthropic), Codex (OpenAI), and OpenCode (open source, 75+ providers). Each agent can use a different tool and model. COO uses set_agent_config MCP tool to view or change settings. Call with no args to show all agents. Call with agent_id + runtime + model to change. Users can also run `exe-os settings` from terminal for interactive arrow-key selection."
3659
+ },
3660
+ // --- Hierarchy and dispatch ---
3661
+ {
3662
+ title: "Chain of command \u2014 who talks to whom",
3663
+ domain: "workflow",
3664
+ priority: "p0",
3665
+ content: "Founder -> COO -> CTO/CMO. CTO -> engineers. CMO -> content production. Never skip levels: the COO does not bypass managers for specialist work. Specialists report to their manager. If you need cross-team info, use ask_team_memory \u2014 don't read other agents' task folders. Each level owns dispatch downward and review upward."
3666
+ },
3667
+ {
3668
+ title: "Single dispatch path \u2014 create_task only",
3669
+ domain: "workflow",
3670
+ priority: "p0",
3671
+ content: "create_task is the ONLY way to dispatch work to another agent. No direct ensureEmployee calls, no manual tmux spawns, no send_message for actionable work. create_task \u2192 system auto-spawns \u2192 session correctly named. ONE PATH. No backdoors. No exceptions."
3672
+ },
3673
+ // --- Session isolation ---
3674
+ {
3675
+ title: "Session scoping \u2014 stay in your coordinator boundary",
3676
+ domain: "security",
3677
+ priority: "p0",
3678
+ content: "Session scoping is mandatory. Managers dispatch to workers within their own coordinator session ONLY. Employee sessions use {employee}-{coordinatorSession}. Cross-session dispatch is blocked by the system. Verify session names before dispatch. Tasks are scoped to the creating coordinator session."
3679
+ },
3680
+ {
3681
+ title: "Session isolation \u2014 never touch another session's work",
3682
+ domain: "workflow",
3683
+ priority: "p0",
3684
+ content: "Sessions are isolated. A coordinator session owns ONLY tasks it dispatched. (1) Never close/update/cancel tasks from another coordinator session. (2) Never review work from a different session \u2014 report that it belongs to another session and skip. (3) Ignore other sessions' items in list_tasks results. (4) Employees inherit session: employee sessions work ONLY on their parent coordinator session's tasks. Cross-session work is a system violation."
3685
+ },
3686
+ // --- Engineering: session scoping in code ---
3687
+ {
3688
+ title: "Three-dimensional scoping \u2014 session, project, role \u2014 enforced in every query",
3689
+ domain: "architecture",
3690
+ priority: "p0",
3691
+ content: "Every DB query, notification, review count, and task operation MUST be scoped on 3 dimensions: (1) Session \u2014 filter by session_scope matching the current coordinator session. (2) Project \u2014 filter by project_name. (3) Role \u2014 agents only see data at their hierarchy level. When writing ANY function that touches tasks, reviews, messages, or notifications: always accept a sessionScope parameter and pass it to the SQL WHERE clause. Unscoped queries are bugs. Test by running 2+ coordinator sessions simultaneously."
3692
+ },
3693
+ // --- Hard constraints ---
3694
+ {
3695
+ title: "What you CANNOT do in exe-os \u2014 hard constraints",
3696
+ domain: "security",
3697
+ priority: "p0",
3698
+ content: "NEVER: (1) Access the database directly \u2014 it's SQLCipher encrypted, always fails. Use MCP tools only. (2) Manually spawn tmux sessions \u2014 create_task handles it. (3) Run git checkout main \u2014 agents work in worktrees. (4) Modify another agent's in-progress task. (5) Push to remote \u2014 the COO reviews and pushes. (6) Skip update_task(done) \u2014 it's the ONLY way your work gets reviewed. (7) Run git init."
3699
+ },
3700
+ // --- Operations ---
3701
+ {
3702
+ title: "Managers must supervise deployed workers",
3703
+ domain: "workflow",
3704
+ priority: "p0",
3705
+ content: `Every manager (COO/CTO/CMO) who dispatches work to a worker MUST actively monitor them. Check tmux capture-pane every 10 minutes. Verify they're working, not stuck. If idle at prompt with in_progress task \u2192 send intercom. If stuck \u2192 unblock or escalate. "Standing by" without checking is negligence.`
3706
+ },
3707
+ {
3708
+ title: "COO boot health check \u2014 memory, cloud sync, daemon on every launch",
3709
+ domain: "workflow",
3710
+ priority: "p0",
3711
+ content: "On every /exe boot, COO MUST check system health BEFORE other work: (1) daemon \u2014 is exed PID alive, (2) cloud sync \u2014 grep workers.log for recent cloud-sync errors, (3) memory count \u2014 total in DB, (4) sync delta \u2014 local vs cloud storage_bytes. Report as 4-line status table. If ANY check fails, surface to founder immediately. Do not proceed to tasks until health confirmed."
3712
+ },
3713
+ {
3714
+ title: "exe-build-adv mandatory for 3+ files",
3715
+ domain: "workflow",
3716
+ priority: "p0",
3717
+ content: "exe-build-adv is MANDATORY for ALL work touching 3+ files. Run /exe-build-adv --auto BEFORE implementation. Pipeline: Spec \u2192 AC \u2192 Tests \u2192 Evaluate \u2192 Fix. No multi-file feature ships without pipeline artifacts. No exceptions \u2014 managers reject work without them."
3718
+ },
3719
+ {
3720
+ title: "Desktop and TUI are the same product",
3721
+ domain: "architecture",
3722
+ priority: "p0",
3723
+ content: "Desktop and TUI are the SAME product in different renderers. Same data contracts, same interactions, same acceptance criteria. Desktop tab specs in ARCHITECTURE.md ARE the TUI specs. When building TUI, cross-reference Desktop spec. Different tab names, identical behavior. Never treat them as separate products."
3724
+ },
3725
+ // --- Orchestration golden path ---
3726
+ {
3727
+ title: "Task lifecycle \u2014 the golden path every agent follows",
3728
+ domain: "workflow",
3729
+ priority: "p0",
3730
+ content: "create_task is dispatch + delivery. Task lifecycle: open \u2192 in_progress (you start) \u2192 done (update_task when finished) \u2192 needs_review (reviewer nudged) \u2192 closed (COO only via close_task). DB is the reliable delivery \u2014 intercom is just a speedup nudge. If you finish a task, self-chain: check for next task immediately (step 7). Never wait for a nudge. Never say 'standing by.'"
3731
+ },
3732
+ {
3733
+ title: "Intercom is a speedup, not delivery \u2014 DB is the source of truth",
3734
+ domain: "architecture",
3735
+ priority: "p0",
3736
+ 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."
3737
+ },
3738
+ // --- MCP is the ONLY data interface ---
3739
+ {
3740
+ title: "MCP disconnect \u2014 ask the user, never work around it",
3741
+ domain: "workflow",
3742
+ priority: "p0",
3743
+ 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."
3744
+ },
3745
+ // --- MCP Tool Catalog (Layer 0 — every agent knows what tools exist) ---
3746
+ {
3747
+ title: "MCP tools \u2014 memory and search",
3748
+ domain: "tool-use",
3749
+ priority: "p1",
3750
+ 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)."
3751
+ },
3752
+ {
3753
+ title: "MCP tools \u2014 task orchestration",
3754
+ domain: "tool-use",
3755
+ priority: "p1",
3756
+ 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."
3757
+ },
3758
+ {
3759
+ title: "MCP tools \u2014 knowledge graph (GraphRAG)",
3760
+ domain: "tool-use",
3761
+ priority: "p1",
3762
+ 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."
3763
+ },
3764
+ {
3765
+ title: "MCP tools \u2014 identity, behavior, and decisions",
3766
+ domain: "tool-use",
3767
+ priority: "p1",
3768
+ 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."
3769
+ },
3770
+ {
3771
+ title: "MCP tools \u2014 communication and messaging",
3772
+ domain: "tool-use",
3773
+ priority: "p1",
3774
+ 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.)."
3775
+ },
3776
+ {
3777
+ title: "MCP tools \u2014 wiki, documents, and content",
3778
+ domain: "tool-use",
3779
+ priority: "p1",
3780
+ 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."
3781
+ },
3782
+ {
3783
+ title: "MCP tools \u2014 system, operations, and admin",
3784
+ domain: "tool-use",
3785
+ priority: "p1",
3786
+ 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."
3787
+ },
3788
+ {
3789
+ title: "MCP tools \u2014 config, licensing, and team",
3790
+ domain: "tool-use",
3791
+ priority: "p1",
3792
+ 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."
3793
+ },
3794
+ {
3795
+ title: "MCP tools \u2014 advanced (triggers, skills, orchestration)",
3796
+ domain: "tool-use",
3797
+ priority: "p1",
3798
+ 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."
3799
+ }
3800
+ ];
3801
+ PLATFORM_PROCEDURE_TITLES = new Set(
3802
+ PLATFORM_PROCEDURES.map((p) => p.title)
3803
+ );
2911
3804
  }
2912
3805
  });
2913
3806
 
2914
- // src/lib/task-scope.ts
2915
- function getCurrentSessionScope() {
2916
- try {
2917
- return resolveExeSession();
2918
- } catch {
2919
- return null;
3807
+ // src/lib/global-procedures.ts
3808
+ var global_procedures_exports = {};
3809
+ __export(global_procedures_exports, {
3810
+ deactivateGlobalProcedure: () => deactivateGlobalProcedure,
3811
+ getGlobalProceduresBlock: () => getGlobalProceduresBlock,
3812
+ loadGlobalProcedures: () => loadGlobalProcedures,
3813
+ storeGlobalProcedure: () => storeGlobalProcedure
3814
+ });
3815
+ import { randomUUID as randomUUID3 } from "crypto";
3816
+ async function loadGlobalProcedures() {
3817
+ const client = getClient();
3818
+ const result = await client.execute({
3819
+ sql: "SELECT * FROM global_procedures WHERE active = 1 ORDER BY priority ASC, created_at ASC",
3820
+ args: []
3821
+ });
3822
+ const allRows = result.rows;
3823
+ const customerOnly = allRows.filter((p) => !PLATFORM_PROCEDURE_TITLES.has(p.title));
3824
+ if (customerOnly.length > 0) {
3825
+ _customerCache = customerOnly.map((p) => `### ${p.title}
3826
+ ${p.content}`).join("\n\n");
3827
+ } else {
3828
+ _customerCache = "";
2920
3829
  }
3830
+ _cacheLoaded = true;
3831
+ return customerOnly;
2921
3832
  }
2922
- function strictSessionScopeFilter(sessionScope, tableAlias) {
2923
- const scope = sessionScope !== void 0 ? sessionScope : getCurrentSessionScope();
2924
- if (!scope) return { sql: "", args: [] };
2925
- const col = tableAlias ? `${tableAlias}.session_scope` : "session_scope";
2926
- return {
2927
- sql: ` AND ${col} = ?`,
2928
- args: [scope]
2929
- };
2930
- }
2931
- var init_task_scope = __esm({
2932
- "src/lib/task-scope.ts"() {
2933
- "use strict";
2934
- init_tmux_routing();
2935
- }
2936
- });
2937
-
2938
- // src/lib/store.ts
2939
- import { createHash } from "crypto";
2940
- init_database();
3833
+ function getGlobalProceduresBlock() {
3834
+ const sections = [];
3835
+ if (_platformCache) sections.push(_platformCache);
3836
+ if (_cacheLoaded && _customerCache) sections.push(_customerCache);
3837
+ if (sections.length === 0) return "";
3838
+ return `## Organization-Wide Procedures (MANDATORY \u2014 supersedes all other rules)
2941
3839
 
2942
- // src/lib/keychain.ts
2943
- import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
2944
- import { existsSync as existsSync4 } from "fs";
2945
- import path4 from "path";
2946
- import os4 from "os";
2947
- var SERVICE = "exe-mem";
2948
- var ACCOUNT = "master-key";
2949
- function getKeyDir() {
2950
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
3840
+ ${sections.join("\n\n")}
3841
+ `;
2951
3842
  }
2952
- function getKeyPath() {
2953
- return path4.join(getKeyDir(), "master.key");
3843
+ async function storeGlobalProcedure(input) {
3844
+ const id = randomUUID3();
3845
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3846
+ const client = getClient();
3847
+ await client.execute({
3848
+ sql: `INSERT INTO global_procedures (id, title, content, priority, domain, active, created_at, updated_at)
3849
+ VALUES (?, ?, ?, ?, ?, 1, ?, ?)`,
3850
+ args: [id, input.title, input.content, input.priority ?? "p0", input.domain ?? null, now, now]
3851
+ });
3852
+ await loadGlobalProcedures();
3853
+ return id;
2954
3854
  }
2955
- async function tryKeytar() {
2956
- try {
2957
- return await import("keytar");
2958
- } catch {
2959
- return null;
2960
- }
3855
+ async function deactivateGlobalProcedure(id) {
3856
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3857
+ const client = getClient();
3858
+ const result = await client.execute({
3859
+ sql: "UPDATE global_procedures SET active = 0, updated_at = ? WHERE id = ?",
3860
+ args: [now, id]
3861
+ });
3862
+ await loadGlobalProcedures();
3863
+ return result.rowsAffected > 0;
2961
3864
  }
2962
- async function getMasterKey() {
2963
- const keytar = await tryKeytar();
2964
- if (keytar) {
2965
- try {
2966
- const stored = await keytar.getPassword(SERVICE, ACCOUNT);
2967
- if (stored) {
2968
- return Buffer.from(stored, "base64");
2969
- }
2970
- } catch {
2971
- }
2972
- }
2973
- const keyPath = getKeyPath();
2974
- if (!existsSync4(keyPath)) {
2975
- process.stderr.write(
2976
- `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2977
- `
2978
- );
2979
- return null;
2980
- }
2981
- try {
2982
- const content = await readFile3(keyPath, "utf-8");
2983
- return Buffer.from(content.trim(), "base64");
2984
- } catch (err) {
2985
- process.stderr.write(
2986
- `[keychain] Key read failed at ${keyPath}: ${err instanceof Error ? err.message : String(err)}
2987
- `
2988
- );
2989
- return null;
3865
+ var _customerCache, _cacheLoaded, _platformCache;
3866
+ var init_global_procedures = __esm({
3867
+ "src/lib/global-procedures.ts"() {
3868
+ "use strict";
3869
+ init_database();
3870
+ init_platform_procedures();
3871
+ _customerCache = "";
3872
+ _cacheLoaded = false;
3873
+ _platformCache = PLATFORM_PROCEDURES.map((p) => `### ${p.title}
3874
+ ${p.content}`).join("\n\n");
2990
3875
  }
2991
- }
3876
+ });
2992
3877
 
2993
3878
  // src/lib/store.ts
2994
- init_config();
2995
- init_state_bus();
2996
- var INIT_MAX_RETRIES = 3;
2997
- var INIT_RETRY_DELAY_MS = 1e3;
3879
+ var store_exports = {};
3880
+ __export(store_exports, {
3881
+ attachDocumentMetadata: () => attachDocumentMetadata,
3882
+ buildRawVisibilityFilter: () => buildRawVisibilityFilter,
3883
+ buildWikiScopeFilter: () => buildWikiScopeFilter,
3884
+ classifyTier: () => classifyTier,
3885
+ disposeStore: () => disposeStore,
3886
+ flushBatch: () => flushBatch,
3887
+ flushTier3: () => flushTier3,
3888
+ getMemoryCardinality: () => getMemoryCardinality,
3889
+ initStore: () => initStore,
3890
+ reserveVersions: () => reserveVersions,
3891
+ searchMemories: () => searchMemories,
3892
+ updateMemoryStatus: () => updateMemoryStatus,
3893
+ vectorToBlob: () => vectorToBlob,
3894
+ writeMemory: () => writeMemory
3895
+ });
3896
+ import { createHash } from "crypto";
2998
3897
  function isBusyError2(err) {
2999
3898
  if (err instanceof Error) {
3000
3899
  const msg = err.message.toLowerCase();
@@ -3017,12 +3916,6 @@ async function retryOnBusy2(fn, label) {
3017
3916
  }
3018
3917
  throw new Error("unreachable");
3019
3918
  }
3020
- var _pendingRecords = [];
3021
- var _batchSize = 20;
3022
- var _flushIntervalMs = 1e4;
3023
- var _flushTimer = null;
3024
- var _flushing = false;
3025
- var _nextVersion = 1;
3026
3919
  async function initStore(options) {
3027
3920
  if (_flushTimer !== null) {
3028
3921
  clearInterval(_flushTimer);
@@ -3052,6 +3945,11 @@ async function initStore(options) {
3052
3945
  encryptionKey: hexKey
3053
3946
  });
3054
3947
  await retryOnBusy2(() => ensureSchema(), "ensureSchema");
3948
+ try {
3949
+ const { initDaemonClient: initDaemonClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
3950
+ await initDaemonClient2();
3951
+ } catch {
3952
+ }
3055
3953
  if (!options?.lightweight) {
3056
3954
  try {
3057
3955
  const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
@@ -3071,12 +3969,505 @@ async function initStore(options) {
3071
3969
  }
3072
3970
  }
3073
3971
  }
3972
+ function classifyTier(record) {
3973
+ if (record.tool_name === "commit_to_long_term_memory" && (record.importance ?? 0) >= 8) return 1;
3974
+ if (["store_memory", "manual"].includes(record.tool_name ?? "") && (record.importance ?? 0) >= 5) return 2;
3975
+ return 3;
3976
+ }
3977
+ function inferFilePaths(record) {
3978
+ if (!["Read", "Write", "Edit"].includes(record.tool_name)) return null;
3979
+ const firstLine = record.raw_text.split("\n")[0] ?? "";
3980
+ const match = firstLine.match(/(\/[\w./-]+\.\w+)/);
3981
+ return match ? JSON.stringify([match[1]]) : null;
3982
+ }
3983
+ function inferCommitHash(record) {
3984
+ if (record.tool_name !== "Bash") return null;
3985
+ const match = record.raw_text.match(/\b([a-f0-9]{7,40})\b/);
3986
+ return match ? match[1] : null;
3987
+ }
3988
+ function inferLanguageType(record) {
3989
+ const text = record.raw_text;
3990
+ if (!text || text.length < 10) return null;
3991
+ const trimmed = text.trimStart();
3992
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) return "json";
3993
+ if (/\b(SELECT|INSERT|UPDATE|DELETE|CREATE TABLE|ALTER TABLE)\b/i.test(text)) return "sql";
3994
+ if (/\b(function |const |import |export |class |def |async |=>)\b/.test(text)) return "code";
3995
+ if (trimmed.startsWith("#") || trimmed.startsWith("*")) return "prose";
3996
+ return "mixed";
3997
+ }
3998
+ function inferDomain(record) {
3999
+ const proj = (record.project_name ?? "").toLowerCase();
4000
+ if (proj.includes("marketing") || proj.includes("content")) return "marketing";
4001
+ if (proj.includes("crm") || proj.includes("customer")) return "customer";
4002
+ return null;
4003
+ }
4004
+ async function writeMemory(record) {
4005
+ if (record.vector !== null && record.vector.length !== EMBEDDING_DIM) {
4006
+ throw new Error(
4007
+ `Expected ${EMBEDDING_DIM}-dim vector, got ${record.vector.length}`
4008
+ );
4009
+ }
4010
+ const contentHash = createHash("md5").update(record.raw_text).digest("hex");
4011
+ if (_pendingRecords.some((r) => r.content_hash === contentHash && r.agent_id === record.agent_id)) {
4012
+ return;
4013
+ }
4014
+ try {
4015
+ const client = getClient();
4016
+ const existing = await client.execute({
4017
+ sql: "SELECT id FROM memories WHERE content_hash = ? AND agent_id = ? LIMIT 1",
4018
+ args: [contentHash, record.agent_id]
4019
+ });
4020
+ if (existing.rows.length > 0) return;
4021
+ } catch {
4022
+ }
4023
+ const dbRow = {
4024
+ id: record.id,
4025
+ agent_id: record.agent_id,
4026
+ agent_role: record.agent_role,
4027
+ session_id: record.session_id,
4028
+ timestamp: record.timestamp,
4029
+ tool_name: record.tool_name,
4030
+ project_name: record.project_name,
4031
+ has_error: record.has_error ? 1 : 0,
4032
+ raw_text: record.raw_text,
4033
+ vector: record.vector,
4034
+ version: 0,
4035
+ // Placeholder — assigned atomically at flush time
4036
+ task_id: record.task_id ?? null,
4037
+ importance: record.importance ?? 5,
4038
+ status: record.status ?? "active",
4039
+ confidence: record.confidence ?? 0.7,
4040
+ last_accessed: record.last_accessed ?? record.timestamp,
4041
+ workspace_id: record.workspace_id ?? null,
4042
+ document_id: record.document_id ?? null,
4043
+ user_id: record.user_id ?? null,
4044
+ char_offset: record.char_offset ?? null,
4045
+ page_number: record.page_number ?? null,
4046
+ source_path: record.source_path ?? null,
4047
+ source_type: record.source_type ?? null,
4048
+ tier: record.tier ?? classifyTier(record),
4049
+ supersedes_id: record.supersedes_id ?? null,
4050
+ draft: record.draft ? 1 : 0,
4051
+ memory_type: record.memory_type ?? "raw",
4052
+ trajectory: record.trajectory ? JSON.stringify(record.trajectory) : null,
4053
+ content_hash: contentHash,
4054
+ intent: record.intent ?? null,
4055
+ outcome: record.outcome ?? null,
4056
+ domain: record.domain ?? inferDomain(record),
4057
+ referenced_entities: record.referenced_entities ?? null,
4058
+ retrieval_count: record.retrieval_count ?? 0,
4059
+ chain_position: record.chain_position ?? null,
4060
+ review_status: record.review_status ?? null,
4061
+ context_window_pct: record.context_window_pct ?? null,
4062
+ file_paths: record.file_paths ?? inferFilePaths(record),
4063
+ commit_hash: record.commit_hash ?? inferCommitHash(record),
4064
+ duration_ms: record.duration_ms ?? null,
4065
+ token_cost: record.token_cost ?? null,
4066
+ audience: record.audience ?? null,
4067
+ language_type: record.language_type ?? inferLanguageType(record),
4068
+ parent_memory_id: record.parent_memory_id ?? null
4069
+ };
4070
+ _pendingRecords.push(dbRow);
4071
+ orgBus.emit({
4072
+ type: "memory_stored",
4073
+ agentId: record.agent_id,
4074
+ project: record.project_name,
4075
+ timestamp: record.timestamp
4076
+ });
4077
+ const MAX_PENDING = 1e3;
4078
+ if (_pendingRecords.length > MAX_PENDING) {
4079
+ const dropped = _pendingRecords.length - MAX_PENDING;
4080
+ _pendingRecords = _pendingRecords.slice(-MAX_PENDING);
4081
+ console.warn(`[store] Dropped ${dropped} oldest pending records (overflow)`);
4082
+ }
4083
+ if (_flushTimer === null) {
4084
+ _flushTimer = setInterval(() => {
4085
+ void flushBatch();
4086
+ }, _flushIntervalMs);
4087
+ if (_flushTimer && typeof _flushTimer === "object" && "unref" in _flushTimer) {
4088
+ _flushTimer.unref();
4089
+ }
4090
+ }
4091
+ if (_pendingRecords.length >= _batchSize) {
4092
+ await flushBatch();
4093
+ }
4094
+ }
4095
+ async function flushBatch() {
4096
+ if (_flushing || _pendingRecords.length === 0) return 0;
4097
+ _flushing = true;
4098
+ try {
4099
+ const batch = _pendingRecords.slice(0);
4100
+ const client = getClient();
4101
+ const vResult = await client.execute("SELECT MAX(version) as max_v FROM memories");
4102
+ let baseVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
4103
+ for (const row of batch) {
4104
+ row.version = baseVersion++;
4105
+ }
4106
+ _nextVersion = baseVersion;
4107
+ const buildStmt = (row) => {
4108
+ const hasVector = row.vector !== null;
4109
+ const taskId = row.task_id ?? null;
4110
+ const importance = row.importance ?? 5;
4111
+ const status = row.status ?? "active";
4112
+ const confidence = row.confidence ?? 0.7;
4113
+ const lastAccessed = row.last_accessed ?? row.timestamp;
4114
+ const workspaceId = row.workspace_id ?? null;
4115
+ const documentId = row.document_id ?? null;
4116
+ const userId = row.user_id ?? null;
4117
+ const charOffset = row.char_offset ?? null;
4118
+ const pageNumber = row.page_number ?? null;
4119
+ const sourcePath = row.source_path ?? null;
4120
+ const sourceType = row.source_type ?? null;
4121
+ const tier = row.tier ?? 3;
4122
+ const supersedesId = row.supersedes_id ?? null;
4123
+ const draft = row.draft ? 1 : 0;
4124
+ const memoryType = row.memory_type ?? "raw";
4125
+ const trajectory = row.trajectory ?? null;
4126
+ const contentHash = row.content_hash ?? null;
4127
+ const intent = row.intent ?? null;
4128
+ const outcome = row.outcome ?? null;
4129
+ const domain = row.domain ?? null;
4130
+ const referencedEntities = row.referenced_entities ?? null;
4131
+ const retrievalCount = row.retrieval_count ?? 0;
4132
+ const chainPosition = row.chain_position ?? null;
4133
+ const reviewStatus = row.review_status ?? null;
4134
+ const contextWindowPct = row.context_window_pct ?? null;
4135
+ const filePaths = row.file_paths ?? null;
4136
+ const commitHash = row.commit_hash ?? null;
4137
+ const durationMs = row.duration_ms ?? null;
4138
+ const tokenCost = row.token_cost ?? null;
4139
+ const audience = row.audience ?? null;
4140
+ const languageType = row.language_type ?? null;
4141
+ const parentMemoryId = row.parent_memory_id ?? null;
4142
+ const cols = `id, agent_id, agent_role, session_id, timestamp,
4143
+ tool_name, project_name,
4144
+ has_error, raw_text, vector, version, task_id, importance, status,
4145
+ confidence, last_accessed,
4146
+ workspace_id, document_id, user_id, char_offset, page_number,
4147
+ source_path, source_type, tier, supersedes_id, draft, memory_type, trajectory, content_hash,
4148
+ intent, outcome, domain, referenced_entities, retrieval_count,
4149
+ chain_position, review_status, context_window_pct, file_paths, commit_hash,
4150
+ duration_ms, token_cost, audience, language_type, parent_memory_id`;
4151
+ const metaArgs = [
4152
+ intent,
4153
+ outcome,
4154
+ domain,
4155
+ referencedEntities,
4156
+ retrievalCount,
4157
+ chainPosition,
4158
+ reviewStatus,
4159
+ contextWindowPct,
4160
+ filePaths,
4161
+ commitHash,
4162
+ durationMs,
4163
+ tokenCost,
4164
+ audience,
4165
+ languageType,
4166
+ parentMemoryId
4167
+ ];
4168
+ const baseArgs = [
4169
+ row.id,
4170
+ row.agent_id,
4171
+ row.agent_role,
4172
+ row.session_id,
4173
+ row.timestamp,
4174
+ row.tool_name,
4175
+ row.project_name,
4176
+ row.has_error,
4177
+ row.raw_text
4178
+ ];
4179
+ const sharedArgs = [
4180
+ row.version,
4181
+ taskId,
4182
+ importance,
4183
+ status,
4184
+ confidence,
4185
+ lastAccessed,
4186
+ workspaceId,
4187
+ documentId,
4188
+ userId,
4189
+ charOffset,
4190
+ pageNumber,
4191
+ sourcePath,
4192
+ sourceType,
4193
+ tier,
4194
+ supersedesId,
4195
+ draft,
4196
+ memoryType,
4197
+ trajectory,
4198
+ contentHash
4199
+ ];
4200
+ return {
4201
+ sql: hasVector ? `INSERT OR IGNORE INTO memories (${cols})
4202
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, vector32(?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` : `INSERT OR IGNORE INTO memories (${cols})
4203
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
4204
+ args: hasVector ? [...baseArgs, vectorToBlob(row.vector), ...sharedArgs, ...metaArgs] : [...baseArgs, ...sharedArgs, ...metaArgs]
4205
+ };
4206
+ };
4207
+ const globalClient = getClient();
4208
+ const globalStmts = batch.map(buildStmt);
4209
+ await globalClient.batch(globalStmts, "write");
4210
+ _pendingRecords.splice(0, batch.length);
4211
+ try {
4212
+ const { isShardingEnabled: isShardingEnabled2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
4213
+ if (isShardingEnabled2()) {
4214
+ const byProject = /* @__PURE__ */ new Map();
4215
+ for (const row of batch) {
4216
+ const proj = row.project_name || "unknown";
4217
+ if (!byProject.has(proj)) byProject.set(proj, []);
4218
+ byProject.get(proj).push(row);
4219
+ }
4220
+ for (const [project, rows] of byProject) {
4221
+ try {
4222
+ const shardClient = await getReadyShardClient2(project);
4223
+ const shardStmts = rows.map(buildStmt);
4224
+ await shardClient.batch(shardStmts, "write");
4225
+ } catch (err) {
4226
+ process.stderr.write(
4227
+ `[store] Shard write failed for ${project}: ${err instanceof Error ? err.message : String(err)}
4228
+ `
4229
+ );
4230
+ }
4231
+ }
4232
+ }
4233
+ } catch {
4234
+ }
4235
+ return batch.length;
4236
+ } finally {
4237
+ _flushing = false;
4238
+ }
4239
+ }
4240
+ function buildWikiScopeFilter(options, columnPrefix) {
4241
+ const args = [];
4242
+ let clause = "";
4243
+ if (options?.workspaceId !== void 0) {
4244
+ clause += ` AND ${columnPrefix}workspace_id = ?`;
4245
+ args.push(options.workspaceId);
4246
+ }
4247
+ if (options?.userId === void 0) {
4248
+ clause += ` AND ${columnPrefix}user_id IS NULL`;
4249
+ } else if (options.userId === null) {
4250
+ clause += ` AND ${columnPrefix}user_id IS NULL`;
4251
+ } else {
4252
+ clause += ` AND (${columnPrefix}user_id = ? OR ${columnPrefix}user_id IS NULL)`;
4253
+ args.push(options.userId);
4254
+ }
4255
+ return { clause, args };
4256
+ }
4257
+ function buildRawVisibilityFilter(options, columnPrefix) {
4258
+ if (options?.includeRaw === false) {
4259
+ return {
4260
+ clause: ` AND COALESCE(${columnPrefix}memory_type, 'raw') != 'raw'`,
4261
+ args: []
4262
+ };
4263
+ }
4264
+ return { clause: "", args: [] };
4265
+ }
4266
+ async function searchMemories(queryVector, agentId, options) {
4267
+ let client;
4268
+ try {
4269
+ const { isShardingEnabled: isShardingEnabled2, shardExists: shardExists2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
4270
+ if (isShardingEnabled2() && options?.projectName && shardExists2(options.projectName)) {
4271
+ client = await getReadyShardClient2(options.projectName);
4272
+ } else {
4273
+ client = getClient();
4274
+ }
4275
+ } catch {
4276
+ client = getClient();
4277
+ }
4278
+ const limit = options?.limit ?? 10;
4279
+ const statusFilter = options?.includeArchived ? "" : `
4280
+ AND COALESCE(status, 'active') = 'active'`;
4281
+ const draftFilter = options?.includeDrafts ? "" : `
4282
+ AND (draft = 0 OR draft IS NULL)`;
4283
+ let sql = `SELECT id, agent_id, agent_role, session_id, timestamp,
4284
+ tool_name, project_name,
4285
+ has_error, raw_text, vector, importance, status,
4286
+ confidence, last_accessed,
4287
+ workspace_id, document_id, user_id,
4288
+ char_offset, page_number,
4289
+ source_path, source_type
4290
+ FROM memories
4291
+ WHERE agent_id = ?
4292
+ AND vector IS NOT NULL${statusFilter}${draftFilter}
4293
+ AND COALESCE(confidence, 0.7) >= 0.3`;
4294
+ const args = [agentId];
4295
+ const scope = buildWikiScopeFilter(options, "");
4296
+ sql += scope.clause;
4297
+ args.push(...scope.args);
4298
+ const rawVisibility = buildRawVisibilityFilter(options, "");
4299
+ sql += rawVisibility.clause;
4300
+ args.push(...rawVisibility.args);
4301
+ if (options?.projectName) {
4302
+ sql += ` AND project_name = ?`;
4303
+ args.push(options.projectName);
4304
+ }
4305
+ if (options?.toolName) {
4306
+ sql += ` AND tool_name = ?`;
4307
+ args.push(options.toolName);
4308
+ }
4309
+ if (options?.hasError !== void 0) {
4310
+ sql += ` AND has_error = ?`;
4311
+ args.push(options.hasError ? 1 : 0);
4312
+ }
4313
+ if (options?.since) {
4314
+ sql += ` AND timestamp >= ?`;
4315
+ args.push(options.since);
4316
+ }
4317
+ if (options?.memoryType) {
4318
+ sql += ` AND memory_type = ?`;
4319
+ args.push(options.memoryType);
4320
+ }
4321
+ sql += ` ORDER BY vector_distance_cos(vector, vector32(?))`;
4322
+ args.push(vectorToBlob(queryVector));
4323
+ sql += ` LIMIT ?`;
4324
+ args.push(limit);
4325
+ const result = await client.execute({ sql, args });
4326
+ return result.rows.map((row) => ({
4327
+ id: row.id,
4328
+ agent_id: row.agent_id,
4329
+ agent_role: row.agent_role,
4330
+ session_id: row.session_id,
4331
+ timestamp: row.timestamp,
4332
+ tool_name: row.tool_name,
4333
+ project_name: row.project_name,
4334
+ has_error: row.has_error === 1,
4335
+ raw_text: row.raw_text,
4336
+ vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
4337
+ importance: row.importance ?? 5,
4338
+ status: row.status ?? "active",
4339
+ confidence: row.confidence ?? 0.7,
4340
+ last_accessed: row.last_accessed ?? row.timestamp,
4341
+ workspace_id: row.workspace_id ?? null,
4342
+ document_id: row.document_id ?? null,
4343
+ user_id: row.user_id ?? null,
4344
+ char_offset: row.char_offset ?? null,
4345
+ page_number: row.page_number ?? null,
4346
+ source_path: row.source_path ?? null,
4347
+ source_type: row.source_type ?? null
4348
+ }));
4349
+ }
4350
+ async function attachDocumentMetadata(records) {
4351
+ const docIds = [
4352
+ ...new Set(
4353
+ records.map((r) => r.document_id).filter((id) => typeof id === "string" && id.length > 0)
4354
+ )
4355
+ ];
4356
+ if (docIds.length === 0) return records;
4357
+ try {
4358
+ const client = getClient();
4359
+ const placeholders = docIds.map(() => "?").join(",");
4360
+ const result = await client.execute({
4361
+ sql: `SELECT id, filename, mime, source_type, uploaded_at
4362
+ FROM documents
4363
+ WHERE id IN (${placeholders})`,
4364
+ args: docIds
4365
+ });
4366
+ const byId = /* @__PURE__ */ new Map();
4367
+ for (const row of result.rows) {
4368
+ const id = row.id;
4369
+ byId.set(id, {
4370
+ document_id: id,
4371
+ filename: row.filename,
4372
+ mime: row.mime ?? null,
4373
+ source_type: row.source_type ?? null,
4374
+ uploaded_at: row.uploaded_at
4375
+ });
4376
+ }
4377
+ for (const record of records) {
4378
+ if (!record.document_id) continue;
4379
+ record.document_metadata = byId.get(record.document_id) ?? null;
4380
+ }
4381
+ } catch {
4382
+ }
4383
+ return records;
4384
+ }
4385
+ async function flushTier3(agentId, options) {
4386
+ const client = getClient();
4387
+ const maxAge = options?.maxAgeHours ?? 72;
4388
+ const cutoff = new Date(Date.now() - maxAge * 36e5).toISOString();
4389
+ if (options?.dryRun) {
4390
+ const result2 = await client.execute({
4391
+ sql: `SELECT COUNT(*) as cnt FROM memories
4392
+ WHERE agent_id = ? AND tier = 3 AND status = 'active' AND timestamp < ?`,
4393
+ args: [agentId, cutoff]
4394
+ });
4395
+ return { archived: Number(result2.rows[0]?.cnt ?? 0) };
4396
+ }
4397
+ const result = await client.execute({
4398
+ sql: `UPDATE memories SET status = 'archived'
4399
+ WHERE agent_id = ? AND tier = 3 AND status = 'active' AND timestamp < ?`,
4400
+ args: [agentId, cutoff]
4401
+ });
4402
+ return { archived: result.rowsAffected };
4403
+ }
4404
+ async function disposeStore() {
4405
+ if (_flushTimer !== null) {
4406
+ clearInterval(_flushTimer);
4407
+ _flushTimer = null;
4408
+ }
4409
+ if (_pendingRecords.length > 0) {
4410
+ await flushBatch();
4411
+ }
4412
+ await disposeTurso();
4413
+ _pendingRecords = [];
4414
+ _nextVersion = 1;
4415
+ }
4416
+ function vectorToBlob(vector) {
4417
+ const f32 = vector instanceof Float32Array ? vector : new Float32Array(vector);
4418
+ return JSON.stringify(Array.from(f32));
4419
+ }
4420
+ async function updateMemoryStatus(id, status) {
4421
+ const client = getClient();
4422
+ await client.execute({
4423
+ sql: `UPDATE memories SET status = ? WHERE id = ?`,
4424
+ args: [status, id]
4425
+ });
4426
+ }
4427
+ function reserveVersions(count) {
4428
+ const reserved = [];
4429
+ for (let i = 0; i < count; i++) {
4430
+ reserved.push(_nextVersion++);
4431
+ }
4432
+ return reserved;
4433
+ }
4434
+ async function getMemoryCardinality(agentId) {
4435
+ try {
4436
+ const client = getClient();
4437
+ const result = await client.execute({
4438
+ sql: `SELECT COUNT(*) as cnt FROM memories WHERE agent_id = ? AND COALESCE(status, 'active') = 'active'`,
4439
+ args: [agentId]
4440
+ });
4441
+ return Number(result.rows[0]?.cnt) || 0;
4442
+ } catch {
4443
+ return 0;
4444
+ }
4445
+ }
4446
+ var INIT_MAX_RETRIES, INIT_RETRY_DELAY_MS, _pendingRecords, _batchSize, _flushIntervalMs, _flushTimer, _flushing, _nextVersion;
4447
+ var init_store = __esm({
4448
+ "src/lib/store.ts"() {
4449
+ "use strict";
4450
+ init_memory();
4451
+ init_database();
4452
+ init_keychain();
4453
+ init_config();
4454
+ init_state_bus();
4455
+ INIT_MAX_RETRIES = 3;
4456
+ INIT_RETRY_DELAY_MS = 1e3;
4457
+ _pendingRecords = [];
4458
+ _batchSize = 20;
4459
+ _flushIntervalMs = 1e4;
4460
+ _flushTimer = null;
4461
+ _flushing = false;
4462
+ _nextVersion = 1;
4463
+ }
4464
+ });
3074
4465
 
3075
4466
  // src/lib/messaging.ts
3076
4467
  init_database();
3077
4468
  init_tmux_routing();
3078
4469
  init_task_scope();
3079
- import crypto from "crypto";
4470
+ import crypto2 from "crypto";
3080
4471
  function rowToMessage(row) {
3081
4472
  return {
3082
4473
  id: row.id,
@@ -3119,13 +4510,75 @@ async function markRead(messageId, sessionScope) {
3119
4510
  });
3120
4511
  }
3121
4512
 
4513
+ // src/bin/fast-db-init.ts
4514
+ async function fastDbInit() {
4515
+ const { isInitialized: isInitialized2, getClient: getClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
4516
+ if (isInitialized2()) {
4517
+ return getClient2();
4518
+ }
4519
+ try {
4520
+ const { connectEmbedDaemon: connectEmbedDaemon2, sendDaemonRequest: sendDaemonRequest2, isClientConnected: isClientConnected2 } = await Promise.resolve().then(() => (init_exe_daemon_client(), exe_daemon_client_exports));
4521
+ const { deserializeResultSet: deserializeResultSet2 } = await Promise.resolve().then(() => (init_daemon_protocol(), daemon_protocol_exports));
4522
+ await connectEmbedDaemon2();
4523
+ if (isClientConnected2()) {
4524
+ const daemonClient = {
4525
+ async execute(stmt) {
4526
+ const sql = typeof stmt === "string" ? stmt : stmt.sql;
4527
+ const args = typeof stmt === "string" ? [] : Array.isArray(stmt.args) ? stmt.args : [];
4528
+ const resp = await sendDaemonRequest2({ type: "db-execute", sql, args });
4529
+ if (resp.error) throw new Error(String(resp.error));
4530
+ if (resp.db) return deserializeResultSet2(resp.db);
4531
+ throw new Error("Unexpected daemon response");
4532
+ },
4533
+ async batch(stmts, mode) {
4534
+ const statements = stmts.map((s) => {
4535
+ const sql = typeof s === "string" ? s : s.sql;
4536
+ const args = typeof s === "string" ? [] : Array.isArray(s.args) ? s.args : [];
4537
+ return { sql, args };
4538
+ });
4539
+ const resp = await sendDaemonRequest2({ type: "db-batch", statements, mode: mode ?? "deferred" });
4540
+ if (resp.error) throw new Error(String(resp.error));
4541
+ const batchResults = resp["db-batch"];
4542
+ if (batchResults) return batchResults.map(deserializeResultSet2);
4543
+ throw new Error("Unexpected daemon batch response");
4544
+ },
4545
+ async transaction(_mode) {
4546
+ throw new Error("Transactions not supported via daemon socket");
4547
+ },
4548
+ async executeMultiple(_sql) {
4549
+ throw new Error("executeMultiple not supported via daemon socket");
4550
+ },
4551
+ async migrate(_stmts) {
4552
+ throw new Error("migrate not supported via daemon socket");
4553
+ },
4554
+ sync() {
4555
+ return Promise.resolve(void 0);
4556
+ },
4557
+ close() {
4558
+ },
4559
+ get closed() {
4560
+ return false;
4561
+ },
4562
+ get protocol() {
4563
+ return "file";
4564
+ }
4565
+ };
4566
+ return daemonClient;
4567
+ }
4568
+ } catch {
4569
+ }
4570
+ const { initStore: initStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
4571
+ await initStore2({ lightweight: true });
4572
+ return getClient2();
4573
+ }
4574
+
3122
4575
  // src/bin/exe-pending-messages.ts
3123
4576
  async function main() {
3124
4577
  const agentId = process.argv[2];
3125
4578
  if (!agentId) {
3126
4579
  process.exit(0);
3127
4580
  }
3128
- await initStore();
4581
+ await fastDbInit();
3129
4582
  const messages = await getPendingMessages(agentId);
3130
4583
  if (messages.length === 0) {
3131
4584
  process.exit(0);