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