@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 as fileURLToPath2 } 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(fileURLToPath2(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
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)
1226
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
+ });
1227
1536
 
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
1255
- );
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
+ });
1256
1671
 
1257
- CREATE INDEX IF NOT EXISTS idx_notifications_read
1258
- ON notifications(read);
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
+ );
1259
1790
 
1260
- CREATE INDEX IF NOT EXISTS idx_notifications_agent
1261
- ON notifications(agent_id, session_scope);
1791
+ CREATE INDEX IF NOT EXISTS idx_memories_agent
1792
+ ON memories(agent_id);
1262
1793
 
1263
- CREATE INDEX IF NOT EXISTS idx_notifications_task_file
1264
- ON notifications(task_file);
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,1159 +2747,1258 @@ 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 fileURLToPath3 } 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
- }
2205
- }
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
- );
2253
-
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
- }
2268
- }
2269
- }
2270
- async function getReadyShardClient(projectName) {
2271
- const client = getShardClient(projectName);
2272
- await ensureShardSchema(client);
2273
- return client;
3147
+ return fromSessionName ?? mySession;
2274
3148
  }
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
- }
2283
- }
2284
- if (oldest) {
2285
- const client = _shards.get(oldest);
2286
- if (client) {
2287
- client.close();
2288
- }
2289
- _shards.delete(oldest);
2290
- _shardLastAccess.delete(oldest);
2291
- }
3149
+ function isExeSession(sessionName) {
3150
+ const matchesBaseWithInstance = (baseName) => sessionName === baseName || sessionName.startsWith(baseName) && /^\d+$/.test(sessionName.slice(baseName.length));
3151
+ const coordinatorName = getCoordinatorName();
3152
+ return matchesBaseWithInstance(coordinatorName);
2292
3153
  }
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
- }
3154
+ var SPAWN_LOCK_DIR, SESSION_CACHE, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS;
3155
+ var init_tmux_routing = __esm({
3156
+ "src/lib/tmux-routing.ts"() {
3157
+ "use strict";
3158
+ init_session_registry();
3159
+ init_session_key();
3160
+ init_transport();
3161
+ init_cc_agent_support();
3162
+ init_mcp_prefix();
3163
+ init_provider_table();
3164
+ init_agent_config();
3165
+ init_runtime_table();
3166
+ init_intercom_queue();
3167
+ init_plan_limits();
3168
+ init_employees();
3169
+ SPAWN_LOCK_DIR = path11.join(os8.homedir(), ".exe-os", "spawn-locks");
3170
+ SESSION_CACHE = path11.join(os8.homedir(), ".exe-os", "session-cache");
3171
+ INTERCOM_LOG2 = path11.join(os8.homedir(), ".exe-os", "intercom.log");
3172
+ DEBOUNCE_FILE = path11.join(SESSION_CACHE, "intercom-debounce.json");
3173
+ DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
2300
3174
  }
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);
3175
+ });
3176
+
3177
+ // src/lib/task-scope.ts
3178
+ function getCurrentSessionScope() {
3179
+ try {
3180
+ return resolveExeSession();
3181
+ } catch {
3182
+ return null;
2308
3183
  }
2309
3184
  }
2310
- function getOpenShardCount() {
2311
- return _shards.size;
3185
+ function strictSessionScopeFilter(sessionScope, tableAlias) {
3186
+ const scope = sessionScope !== void 0 ? sessionScope : getCurrentSessionScope();
3187
+ if (!scope) return { sql: "", args: [] };
3188
+ const col = tableAlias ? `${tableAlias}.session_scope` : "session_scope";
3189
+ return {
3190
+ sql: ` AND ${col} = ?`,
3191
+ args: [scope]
3192
+ };
2312
3193
  }
2313
- function disposeShards() {
2314
- if (_evictionTimer) {
2315
- clearInterval(_evictionTimer);
2316
- _evictionTimer = null;
2317
- }
2318
- for (const [, client] of _shards) {
2319
- client.close();
3194
+ var init_task_scope = __esm({
3195
+ "src/lib/task-scope.ts"() {
3196
+ "use strict";
3197
+ init_tmux_routing();
2320
3198
  }
2321
- _shards.clear();
2322
- _shardLastAccess.clear();
2323
- _shardingEnabled = false;
2324
- _encryptionKey = null;
2325
- }
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"() {
3199
+ });
3200
+
3201
+ // src/lib/notifications.ts
3202
+ import crypto2 from "crypto";
3203
+ import path12 from "path";
3204
+ import os9 from "os";
3205
+ import {
3206
+ readFileSync as readFileSync10,
3207
+ readdirSync as readdirSync2,
3208
+ unlinkSync as unlinkSync3,
3209
+ existsSync as existsSync11,
3210
+ rmdirSync
3211
+ } from "fs";
3212
+ var init_notifications = __esm({
3213
+ "src/lib/notifications.ts"() {
2329
3214
  "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;
3215
+ init_database();
3216
+ init_task_scope();
2340
3217
  }
2341
3218
  });
2342
3219
 
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"() {
3220
+ // src/lib/state-bus.ts
3221
+ var StateBus, orgBus;
3222
+ var init_state_bus = __esm({
3223
+ "src/lib/state-bus.ts"() {
2347
3224
  "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."
3225
+ StateBus = class {
3226
+ handlers = /* @__PURE__ */ new Map();
3227
+ globalHandlers = /* @__PURE__ */ new Set();
3228
+ /** Emit an event to all subscribers */
3229
+ emit(event) {
3230
+ const typeHandlers = this.handlers.get(event.type);
3231
+ if (typeHandlers) {
3232
+ for (const handler of typeHandlers) {
3233
+ try {
3234
+ handler(event);
3235
+ } catch {
3236
+ }
3237
+ }
3238
+ }
3239
+ for (const handler of this.globalHandlers) {
3240
+ try {
3241
+ handler(event);
3242
+ } catch {
3243
+ }
3244
+ }
2451
3245
  }
2452
- ];
2453
- PLATFORM_PROCEDURE_TITLES = new Set(
2454
- PLATFORM_PROCEDURES.map((p) => p.title)
2455
- );
3246
+ /** Subscribe to a specific event type */
3247
+ on(type, handler) {
3248
+ if (!this.handlers.has(type)) {
3249
+ this.handlers.set(type, /* @__PURE__ */ new Set());
3250
+ }
3251
+ this.handlers.get(type).add(handler);
3252
+ }
3253
+ /** Subscribe to ALL events */
3254
+ onAny(handler) {
3255
+ this.globalHandlers.add(handler);
3256
+ }
3257
+ /** Unsubscribe from a specific event type */
3258
+ off(type, handler) {
3259
+ this.handlers.get(type)?.delete(handler);
3260
+ }
3261
+ /** Unsubscribe from ALL events */
3262
+ offAny(handler) {
3263
+ this.globalHandlers.delete(handler);
3264
+ }
3265
+ /** Remove all listeners */
3266
+ clear() {
3267
+ this.handlers.clear();
3268
+ this.globalHandlers.clear();
3269
+ }
3270
+ };
3271
+ orgBus = new StateBus();
2456
3272
  }
2457
3273
  });
2458
3274
 
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
2466
- });
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 = "";
2481
- }
2482
- _cacheLoaded = true;
2483
- return customerOnly;
3275
+ // src/lib/tasks-review.ts
3276
+ import path13 from "path";
3277
+ import { existsSync as existsSync12, readdirSync as readdirSync3, unlinkSync as unlinkSync4 } from "fs";
3278
+ function formatAge(isoTimestamp) {
3279
+ if (!isoTimestamp) return "";
3280
+ const ms = Date.now() - new Date(isoTimestamp).getTime();
3281
+ if (ms < 0) return "just now";
3282
+ const minutes = Math.floor(ms / 6e4);
3283
+ if (minutes < 60) return `${minutes}m ago`;
3284
+ const hours = Math.floor(minutes / 60);
3285
+ if (hours < 24) return `${hours}h ago`;
3286
+ const days = Math.floor(hours / 24);
3287
+ return `${days}d ago`;
2484
3288
  }
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
- `;
3289
+ function isStale(isoTimestamp) {
3290
+ if (!isoTimestamp) return false;
3291
+ return Date.now() - new Date(isoTimestamp).getTime() > 24 * 60 * 60 * 1e3;
2494
3292
  }
2495
- async function storeGlobalProcedure(input) {
2496
- const id = randomUUID();
2497
- const now = (/* @__PURE__ */ new Date()).toISOString();
3293
+ async function listPendingReviews(limit, sessionScope) {
2498
3294
  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]
3295
+ const scope = strictSessionScopeFilter(
3296
+ sessionScope === void 0 ? getCurrentSessionScope() : sessionScope
3297
+ );
3298
+ const result = await client.execute({
3299
+ sql: `SELECT title, assigned_to, project_name, updated_at FROM tasks
3300
+ WHERE status = 'needs_review'${scope.sql}
3301
+ ORDER BY updated_at ASC LIMIT ?`,
3302
+ args: [...scope.args, limit]
2503
3303
  });
2504
- await loadGlobalProcedures();
2505
- return id;
3304
+ return result.rows;
2506
3305
  }
2507
- async function deactivateGlobalProcedure(id) {
2508
- const now = (/* @__PURE__ */ new Date()).toISOString();
3306
+ async function cleanupOrphanedReviews() {
2509
3307
  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]
3308
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3309
+ const r1 = await client.execute({
3310
+ sql: `UPDATE tasks SET status = 'cancelled', updated_at = ?
3311
+ WHERE status IN ('open', 'needs_review', 'in_progress')
3312
+ AND assigned_by = 'system'
3313
+ AND title LIKE 'Review:%'
3314
+ AND parent_task_id IN (SELECT id FROM tasks WHERE status IN ('done', 'cancelled', 'closed'))`,
3315
+ args: [now]
2513
3316
  });
2514
- await loadGlobalProcedures();
2515
- return result.rowsAffected > 0;
3317
+ const r1b = await client.execute({
3318
+ sql: `UPDATE tasks SET status = 'cancelled', updated_at = ?
3319
+ WHERE status IN ('open', 'needs_review')
3320
+ AND title LIKE 'Review:%completed%'
3321
+ AND (parent_task_id IS NULL OR parent_task_id NOT IN (SELECT id FROM tasks WHERE status IN ('open', 'in_progress', 'needs_review', 'blocked')))`,
3322
+ args: [now]
3323
+ });
3324
+ const staleThreshold = new Date(Date.now() - 60 * 60 * 1e3).toISOString();
3325
+ const r2 = await client.execute({
3326
+ sql: `UPDATE tasks SET status = 'done', updated_at = ?
3327
+ WHERE status = 'needs_review'
3328
+ AND result IS NOT NULL
3329
+ AND updated_at < ?`,
3330
+ args: [now, staleThreshold]
3331
+ });
3332
+ const total = r1.rowsAffected + (r1b?.rowsAffected ?? 0) + r2.rowsAffected;
3333
+ if (total > 0) {
3334
+ process.stderr.write(
3335
+ `[cleanup] Closed ${total} orphaned review(s): ${r1.rowsAffected} cascade + ${r1b?.rowsAffected ?? 0} orphan + ${r2.rowsAffected} stale
3336
+ `
3337
+ );
3338
+ }
3339
+ return total;
2516
3340
  }
2517
- var _customerCache, _cacheLoaded, _platformCache;
2518
- var init_global_procedures = __esm({
2519
- "src/lib/global-procedures.ts"() {
3341
+ var init_tasks_review = __esm({
3342
+ "src/lib/tasks-review.ts"() {
2520
3343
  "use strict";
2521
3344
  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");
2527
- }
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");
3345
+ init_config();
3346
+ init_employees();
3347
+ init_notifications();
3348
+ init_tmux_routing();
3349
+ init_session_key();
3350
+ init_state_bus();
3351
+ init_task_scope();
2538
3352
  }
2539
3353
  });
2540
3354
 
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;
3355
+ // src/lib/keychain.ts
3356
+ import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
3357
+ import { existsSync as existsSync13 } from "fs";
3358
+ import path14 from "path";
3359
+ import os10 from "os";
3360
+ function getKeyDir() {
3361
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path14.join(os10.homedir(), ".exe-os");
2547
3362
  }
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
- }
3363
+ function getKeyPath() {
3364
+ return path14.join(getKeyDir(), "master.key");
3365
+ }
3366
+ async function tryKeytar() {
3367
+ try {
3368
+ return await import("keytar");
3369
+ } catch {
3370
+ return null;
2554
3371
  }
2555
- return null;
2556
3372
  }
2557
- function resolveRuntimeProcess() {
2558
- let pid = process.ppid;
2559
- for (let i = 0; i < 10; i++) {
2560
- 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 };
3373
+ async function getMasterKey() {
3374
+ const keytar = await tryKeytar();
3375
+ if (keytar) {
3376
+ try {
3377
+ const stored = await keytar.getPassword(SERVICE, ACCOUNT);
3378
+ if (stored) {
3379
+ return Buffer.from(stored, "base64");
2571
3380
  }
2572
- pid = parseInt(ppid, 10);
2573
- if (pid <= 1) break;
2574
3381
  } catch {
2575
- break;
2576
3382
  }
2577
3383
  }
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;
3384
+ const keyPath = getKeyPath();
3385
+ if (!existsSync13(keyPath)) {
3386
+ process.stderr.write(
3387
+ `[keychain] Key not found at ${keyPath} (HOME=${os10.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
3388
+ `
3389
+ );
3390
+ return null;
2585
3391
  }
2586
- const resolved = resolveRuntimeProcess();
2587
- if (resolved) {
2588
- _cachedRuntime = resolved.runtime;
2589
- _cached = resolved.pid;
2590
- return _cached;
3392
+ try {
3393
+ const content = await readFile3(keyPath, "utf-8");
3394
+ return Buffer.from(content.trim(), "base64");
3395
+ } catch (err) {
3396
+ process.stderr.write(
3397
+ `[keychain] Key read failed at ${keyPath}: ${err instanceof Error ? err.message : String(err)}
3398
+ `
3399
+ );
3400
+ return null;
2591
3401
  }
2592
- _cached = process.env.CLAUDE_CODE_SSE_PORT ?? String(process.ppid);
2593
- return _cached;
2594
3402
  }
2595
- var _cached, _cachedRuntime, RUNTIME_COMMANDS;
2596
- var init_session_key = __esm({
2597
- "src/lib/session-key.ts"() {
3403
+ var SERVICE, ACCOUNT;
3404
+ var init_keychain = __esm({
3405
+ "src/lib/keychain.ts"() {
2598
3406
  "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
- };
3407
+ SERVICE = "exe-mem";
3408
+ ACCOUNT = "master-key";
2606
3409
  }
2607
3410
  });
2608
3411
 
2609
- // src/lib/tmux-transport.ts
2610
- var tmux_transport_exports = {};
2611
- __export(tmux_transport_exports, {
2612
- TmuxTransport: () => TmuxTransport
3412
+ // src/lib/shard-manager.ts
3413
+ var shard_manager_exports = {};
3414
+ __export(shard_manager_exports, {
3415
+ disposeShards: () => disposeShards,
3416
+ ensureShardSchema: () => ensureShardSchema,
3417
+ getOpenShardCount: () => getOpenShardCount,
3418
+ getReadyShardClient: () => getReadyShardClient,
3419
+ getShardClient: () => getShardClient,
3420
+ getShardsDir: () => getShardsDir,
3421
+ initShardManager: () => initShardManager,
3422
+ isShardingEnabled: () => isShardingEnabled,
3423
+ listShards: () => listShards,
3424
+ shardExists: () => shardExists
2613
3425
  });
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
- };
3426
+ import path15 from "path";
3427
+ import { existsSync as existsSync14, mkdirSync as mkdirSync5, readdirSync as readdirSync4 } from "fs";
3428
+ import { createClient as createClient2 } from "@libsql/client";
3429
+ function initShardManager(encryptionKey) {
3430
+ _encryptionKey = encryptionKey;
3431
+ if (!existsSync14(SHARDS_DIR)) {
3432
+ mkdirSync5(SHARDS_DIR, { recursive: true });
2707
3433
  }
2708
- });
3434
+ _shardingEnabled = true;
3435
+ if (_evictionTimer) clearInterval(_evictionTimer);
3436
+ _evictionTimer = setInterval(evictIdleShards, EVICTION_INTERVAL_MS);
3437
+ _evictionTimer.unref();
3438
+ }
3439
+ function isShardingEnabled() {
3440
+ return _shardingEnabled;
3441
+ }
3442
+ function getShardsDir() {
3443
+ return SHARDS_DIR;
3444
+ }
3445
+ function getShardClient(projectName) {
3446
+ if (!_encryptionKey) {
3447
+ throw new Error("Shard manager not initialized. Call initShardManager() first.");
3448
+ }
3449
+ const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
3450
+ if (!safeName) {
3451
+ throw new Error(`Invalid project name for shard: "${projectName}"`);
3452
+ }
3453
+ const cached = _shards.get(safeName);
3454
+ if (cached) {
3455
+ _shardLastAccess.set(safeName, Date.now());
3456
+ return cached;
3457
+ }
3458
+ while (_shards.size >= MAX_OPEN_SHARDS) {
3459
+ evictLRU();
3460
+ }
3461
+ const dbPath = path15.join(SHARDS_DIR, `${safeName}.db`);
3462
+ const client = createClient2({
3463
+ url: `file:${dbPath}`,
3464
+ encryptionKey: _encryptionKey
3465
+ });
3466
+ _shards.set(safeName, client);
3467
+ _shardLastAccess.set(safeName, Date.now());
3468
+ return client;
3469
+ }
3470
+ function shardExists(projectName) {
3471
+ const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
3472
+ return existsSync14(path15.join(SHARDS_DIR, `${safeName}.db`));
3473
+ }
3474
+ function listShards() {
3475
+ if (!existsSync14(SHARDS_DIR)) return [];
3476
+ return readdirSync4(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
3477
+ }
3478
+ async function ensureShardSchema(client) {
3479
+ await client.execute("PRAGMA journal_mode = WAL");
3480
+ await client.execute("PRAGMA busy_timeout = 30000");
3481
+ try {
3482
+ await client.execute("PRAGMA libsql_vector_search_ef = 128");
3483
+ } catch {
3484
+ }
3485
+ await client.executeMultiple(`
3486
+ CREATE TABLE IF NOT EXISTS memories (
3487
+ id TEXT PRIMARY KEY,
3488
+ agent_id TEXT NOT NULL,
3489
+ agent_role TEXT NOT NULL,
3490
+ session_id TEXT NOT NULL,
3491
+ timestamp TEXT NOT NULL,
3492
+ tool_name TEXT NOT NULL,
3493
+ project_name TEXT NOT NULL,
3494
+ has_error INTEGER NOT NULL DEFAULT 0,
3495
+ raw_text TEXT NOT NULL,
3496
+ vector F32_BLOB(1024),
3497
+ version INTEGER NOT NULL DEFAULT 0
3498
+ );
2709
3499
 
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();
3500
+ CREATE INDEX IF NOT EXISTS idx_memories_agent ON memories(agent_id);
3501
+ CREATE INDEX IF NOT EXISTS idx_memories_timestamp ON memories(timestamp);
3502
+ CREATE INDEX IF NOT EXISTS idx_memories_agent_project ON memories(agent_id, project_name);
3503
+ `);
3504
+ await client.executeMultiple(`
3505
+ CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
3506
+ raw_text,
3507
+ content='memories',
3508
+ content_rowid='rowid'
3509
+ );
3510
+
3511
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
3512
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
3513
+ END;
3514
+
3515
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
3516
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
3517
+ END;
3518
+
3519
+ CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
3520
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
3521
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
3522
+ END;
3523
+ `);
3524
+ for (const col of [
3525
+ "ALTER TABLE memories ADD COLUMN task_id TEXT",
3526
+ "ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
3527
+ "ALTER TABLE memories ADD COLUMN author_device_id TEXT",
3528
+ "ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'",
3529
+ "ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
3530
+ "ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
3531
+ "ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
3532
+ "ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0",
3533
+ "ALTER TABLE memories ADD COLUMN content_hash TEXT",
3534
+ "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT",
3535
+ "ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7",
3536
+ "ALTER TABLE memories ADD COLUMN last_accessed TEXT",
3537
+ // Wiki linkage columns (must match database.ts)
3538
+ "ALTER TABLE memories ADD COLUMN workspace_id TEXT",
3539
+ "ALTER TABLE memories ADD COLUMN document_id TEXT",
3540
+ "ALTER TABLE memories ADD COLUMN user_id TEXT",
3541
+ "ALTER TABLE memories ADD COLUMN char_offset INTEGER",
3542
+ "ALTER TABLE memories ADD COLUMN page_number INTEGER",
3543
+ // Source provenance columns (must match database.ts)
3544
+ "ALTER TABLE memories ADD COLUMN source_path TEXT",
3545
+ "ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'",
3546
+ "ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3",
3547
+ "ALTER TABLE memories ADD COLUMN supersedes_id TEXT",
3548
+ // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
3549
+ "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
3550
+ "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
3551
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT",
3552
+ // Metadata enrichment columns (must match database.ts)
3553
+ "ALTER TABLE memories ADD COLUMN intent TEXT",
3554
+ "ALTER TABLE memories ADD COLUMN outcome TEXT",
3555
+ "ALTER TABLE memories ADD COLUMN domain TEXT",
3556
+ "ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
3557
+ "ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
3558
+ "ALTER TABLE memories ADD COLUMN chain_position TEXT",
3559
+ "ALTER TABLE memories ADD COLUMN review_status TEXT",
3560
+ "ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
3561
+ "ALTER TABLE memories ADD COLUMN file_paths TEXT",
3562
+ "ALTER TABLE memories ADD COLUMN commit_hash TEXT",
3563
+ "ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
3564
+ "ALTER TABLE memories ADD COLUMN token_cost REAL",
3565
+ "ALTER TABLE memories ADD COLUMN audience TEXT",
3566
+ "ALTER TABLE memories ADD COLUMN language_type TEXT",
3567
+ "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
3568
+ ]) {
3569
+ try {
3570
+ await client.execute(col);
3571
+ } catch {
3572
+ }
2715
3573
  }
2716
- return _transport;
2717
- }
2718
- var _transport;
2719
- var init_transport = __esm({
2720
- "src/lib/transport.ts"() {
2721
- "use strict";
2722
- _transport = null;
3574
+ for (const idx of [
3575
+ "CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)",
3576
+ "CREATE INDEX IF NOT EXISTS idx_memories_supersedes ON memories(supersedes_id) WHERE supersedes_id IS NOT NULL"
3577
+ ]) {
3578
+ try {
3579
+ await client.execute(idx);
3580
+ } catch {
3581
+ }
2723
3582
  }
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";
3583
+ try {
3584
+ await client.execute("CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)");
3585
+ } catch {
2731
3586
  }
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
- ];
3587
+ for (const idx of [
3588
+ "CREATE INDEX IF NOT EXISTS idx_memories_workspace ON memories(workspace_id)",
3589
+ "CREATE INDEX IF NOT EXISTS idx_memories_document ON memories(document_id)",
3590
+ "CREATE INDEX IF NOT EXISTS idx_memories_user ON memories(user_id)"
3591
+ ]) {
3592
+ try {
3593
+ await client.execute(idx);
3594
+ } catch {
3595
+ }
2745
3596
  }
2746
- });
3597
+ await client.executeMultiple(`
3598
+ CREATE TABLE IF NOT EXISTS entities (
3599
+ id TEXT PRIMARY KEY,
3600
+ name TEXT NOT NULL,
3601
+ type TEXT NOT NULL,
3602
+ first_seen TEXT NOT NULL,
3603
+ last_seen TEXT NOT NULL,
3604
+ properties TEXT DEFAULT '{}',
3605
+ UNIQUE(name, type)
3606
+ );
2747
3607
 
2748
- // src/lib/provider-table.ts
2749
- var init_provider_table = __esm({
2750
- "src/lib/provider-table.ts"() {
2751
- "use strict";
2752
- }
2753
- });
3608
+ CREATE TABLE IF NOT EXISTS relationships (
3609
+ id TEXT PRIMARY KEY,
3610
+ source_entity_id TEXT NOT NULL,
3611
+ target_entity_id TEXT NOT NULL,
3612
+ type TEXT NOT NULL,
3613
+ weight REAL DEFAULT 1.0,
3614
+ timestamp TEXT NOT NULL,
3615
+ properties TEXT DEFAULT '{}',
3616
+ UNIQUE(source_entity_id, target_entity_id, type)
3617
+ );
2754
3618
 
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
- };
2778
- }
2779
- });
3619
+ CREATE TABLE IF NOT EXISTS entity_memories (
3620
+ entity_id TEXT NOT NULL,
3621
+ memory_id TEXT NOT NULL,
3622
+ PRIMARY KEY (entity_id, memory_id)
3623
+ );
2780
3624
 
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"() {
2787
- "use strict";
2788
- 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
- };
2797
- }
2798
- });
3625
+ CREATE TABLE IF NOT EXISTS relationship_memories (
3626
+ relationship_id TEXT NOT NULL,
3627
+ memory_id TEXT NOT NULL,
3628
+ PRIMARY KEY (relationship_id, memory_id)
3629
+ );
2799
3630
 
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"() {
2807
- "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
- });
3631
+ CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
3632
+ CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
3633
+ CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
3634
+ CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
3635
+ CREATE INDEX IF NOT EXISTS idx_relationships_type ON relationships(type);
2813
3636
 
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
- });
3637
+ CREATE TABLE IF NOT EXISTS hyperedges (
3638
+ id TEXT PRIMARY KEY,
3639
+ label TEXT NOT NULL,
3640
+ relation TEXT NOT NULL,
3641
+ confidence REAL DEFAULT 1.0,
3642
+ timestamp TEXT NOT NULL
3643
+ );
2832
3644
 
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");
3645
+ CREATE TABLE IF NOT EXISTS hyperedge_nodes (
3646
+ hyperedge_id TEXT NOT NULL,
3647
+ entity_id TEXT NOT NULL,
3648
+ PRIMARY KEY (hyperedge_id, entity_id)
3649
+ );
3650
+ `);
3651
+ for (const col of [
3652
+ "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
3653
+ "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
3654
+ ]) {
3655
+ try {
3656
+ await client.execute(col);
3657
+ } catch {
3658
+ }
2845
3659
  }
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 as fileURLToPath2 } from "url";
2853
- function getMySession() {
2854
- return getTransport().getMySession();
2855
3660
  }
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;
3661
+ async function getReadyShardClient(projectName) {
3662
+ const client = getShardClient(projectName);
3663
+ await ensureShardSchema(client);
3664
+ return client;
2861
3665
  }
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;
3666
+ function evictLRU() {
3667
+ let oldest = null;
3668
+ let oldestTime = Infinity;
3669
+ for (const [name, time] of _shardLastAccess) {
3670
+ if (time < oldestTime) {
3671
+ oldestTime = time;
3672
+ oldest = name;
3673
+ }
3674
+ }
3675
+ if (oldest) {
3676
+ const client = _shards.get(oldest);
3677
+ if (client) {
3678
+ client.close();
3679
+ }
3680
+ _shards.delete(oldest);
3681
+ _shardLastAccess.delete(oldest);
2868
3682
  }
2869
3683
  }
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;
2885
- }
2886
- return fromCache;
3684
+ function evictIdleShards() {
3685
+ const now = Date.now();
3686
+ const toEvict = [];
3687
+ for (const [name, lastAccess] of _shardLastAccess) {
3688
+ if (now - lastAccess > SHARD_IDLE_MS) {
3689
+ toEvict.push(name);
2887
3690
  }
2888
- } catch {
2889
3691
  }
2890
- return fromSessionName ?? mySession;
3692
+ for (const name of toEvict) {
3693
+ const client = _shards.get(name);
3694
+ if (client) {
3695
+ client.close();
3696
+ }
3697
+ _shards.delete(name);
3698
+ _shardLastAccess.delete(name);
3699
+ }
2891
3700
  }
2892
- function isExeSession(sessionName) {
2893
- const matchesBaseWithInstance = (baseName) => sessionName === baseName || sessionName.startsWith(baseName) && /^\d+$/.test(sessionName.slice(baseName.length));
2894
- const coordinatorName = getCoordinatorName();
2895
- return matchesBaseWithInstance(coordinatorName) || matchesBaseWithInstance("exe");
3701
+ function getOpenShardCount() {
3702
+ return _shards.size;
2896
3703
  }
2897
- var SPAWN_LOCK_DIR, SESSION_CACHE, INTERCOM_LOG2, DEBOUNCE_FILE, DEBOUNCE_CLEANUP_AGE_MS;
2898
- var init_tmux_routing = __esm({
2899
- "src/lib/tmux-routing.ts"() {
2900
- "use strict";
2901
- init_session_registry();
2902
- init_session_key();
2903
- init_transport();
2904
- init_cc_agent_support();
2905
- init_mcp_prefix();
2906
- init_provider_table();
2907
- init_agent_config();
2908
- init_runtime_table();
2909
- init_intercom_queue();
2910
- init_plan_limits();
2911
- init_employees();
2912
- SPAWN_LOCK_DIR = path11.join(os8.homedir(), ".exe-os", "spawn-locks");
2913
- SESSION_CACHE = path11.join(os8.homedir(), ".exe-os", "session-cache");
2914
- INTERCOM_LOG2 = path11.join(os8.homedir(), ".exe-os", "intercom.log");
2915
- DEBOUNCE_FILE = path11.join(SESSION_CACHE, "intercom-debounce.json");
2916
- DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
3704
+ function disposeShards() {
3705
+ if (_evictionTimer) {
3706
+ clearInterval(_evictionTimer);
3707
+ _evictionTimer = null;
2917
3708
  }
2918
- });
2919
-
2920
- // src/lib/task-scope.ts
2921
- function getCurrentSessionScope() {
2922
- try {
2923
- return resolveExeSession();
2924
- } catch {
2925
- return null;
3709
+ for (const [, client] of _shards) {
3710
+ client.close();
2926
3711
  }
3712
+ _shards.clear();
3713
+ _shardLastAccess.clear();
3714
+ _shardingEnabled = false;
3715
+ _encryptionKey = null;
2927
3716
  }
2928
- function strictSessionScopeFilter(sessionScope, tableAlias) {
2929
- const scope = sessionScope !== void 0 ? sessionScope : getCurrentSessionScope();
2930
- if (!scope) return { sql: "", args: [] };
2931
- const col = tableAlias ? `${tableAlias}.session_scope` : "session_scope";
2932
- return {
2933
- sql: ` AND ${col} = ?`,
2934
- args: [scope]
2935
- };
2936
- }
2937
- var init_task_scope = __esm({
2938
- "src/lib/task-scope.ts"() {
3717
+ var SHARDS_DIR, SHARD_IDLE_MS, MAX_OPEN_SHARDS, EVICTION_INTERVAL_MS, _shards, _shardLastAccess, _evictionTimer, _encryptionKey, _shardingEnabled;
3718
+ var init_shard_manager = __esm({
3719
+ "src/lib/shard-manager.ts"() {
2939
3720
  "use strict";
2940
- init_tmux_routing();
3721
+ init_config();
3722
+ SHARDS_DIR = path15.join(EXE_AI_DIR, "shards");
3723
+ SHARD_IDLE_MS = 5 * 60 * 1e3;
3724
+ MAX_OPEN_SHARDS = 10;
3725
+ EVICTION_INTERVAL_MS = 60 * 1e3;
3726
+ _shards = /* @__PURE__ */ new Map();
3727
+ _shardLastAccess = /* @__PURE__ */ new Map();
3728
+ _evictionTimer = null;
3729
+ _encryptionKey = null;
3730
+ _shardingEnabled = false;
2941
3731
  }
2942
3732
  });
2943
3733
 
2944
- // src/lib/notifications.ts
2945
- import crypto from "crypto";
2946
- import path12 from "path";
2947
- import os9 from "os";
2948
- import {
2949
- readFileSync as readFileSync8,
2950
- readdirSync as readdirSync3,
2951
- unlinkSync as unlinkSync2,
2952
- existsSync as existsSync11,
2953
- rmdirSync
2954
- } from "fs";
2955
- var init_notifications = __esm({
2956
- "src/lib/notifications.ts"() {
3734
+ // src/lib/platform-procedures.ts
3735
+ var PLATFORM_PROCEDURES, PLATFORM_PROCEDURE_TITLES;
3736
+ var init_platform_procedures = __esm({
3737
+ "src/lib/platform-procedures.ts"() {
2957
3738
  "use strict";
2958
- init_database();
2959
- init_task_scope();
3739
+ PLATFORM_PROCEDURES = [
3740
+ // --- Foundation: what is exe-os ---
3741
+ {
3742
+ title: "What is exe-os \u2014 the operating model every agent must understand",
3743
+ domain: "architecture",
3744
+ priority: "p0",
3745
+ 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."
3746
+ },
3747
+ {
3748
+ title: "Mode 1 \u2014 how exe-os runs inside Claude Code",
3749
+ domain: "architecture",
3750
+ priority: "p0",
3751
+ 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."
3752
+ },
3753
+ {
3754
+ title: "Sessions explained \u2014 coordinator session names and projects",
3755
+ domain: "architecture",
3756
+ priority: "p0",
3757
+ 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."
3758
+ },
3759
+ {
3760
+ title: "Runtime settings \u2014 COO can view and change tools per agent",
3761
+ domain: "workflow",
3762
+ priority: "p1",
3763
+ 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."
3764
+ },
3765
+ // --- Hierarchy and dispatch ---
3766
+ {
3767
+ title: "Chain of command \u2014 who talks to whom",
3768
+ domain: "workflow",
3769
+ priority: "p0",
3770
+ 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."
3771
+ },
3772
+ {
3773
+ title: "Single dispatch path \u2014 create_task only",
3774
+ domain: "workflow",
3775
+ priority: "p0",
3776
+ 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."
3777
+ },
3778
+ // --- Session isolation ---
3779
+ {
3780
+ title: "Session scoping \u2014 stay in your coordinator boundary",
3781
+ domain: "security",
3782
+ priority: "p0",
3783
+ 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."
3784
+ },
3785
+ {
3786
+ title: "Session isolation \u2014 never touch another session's work",
3787
+ domain: "workflow",
3788
+ priority: "p0",
3789
+ 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."
3790
+ },
3791
+ // --- Engineering: session scoping in code ---
3792
+ {
3793
+ title: "Three-dimensional scoping \u2014 session, project, role \u2014 enforced in every query",
3794
+ domain: "architecture",
3795
+ priority: "p0",
3796
+ 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."
3797
+ },
3798
+ // --- Hard constraints ---
3799
+ {
3800
+ title: "What you CANNOT do in exe-os \u2014 hard constraints",
3801
+ domain: "security",
3802
+ priority: "p0",
3803
+ 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."
3804
+ },
3805
+ // --- Operations ---
3806
+ {
3807
+ title: "Managers must supervise deployed workers",
3808
+ domain: "workflow",
3809
+ priority: "p0",
3810
+ 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.`
3811
+ },
3812
+ {
3813
+ title: "COO boot health check \u2014 memory, cloud sync, daemon on every launch",
3814
+ domain: "workflow",
3815
+ priority: "p0",
3816
+ 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."
3817
+ },
3818
+ {
3819
+ title: "exe-build-adv mandatory for 3+ files",
3820
+ domain: "workflow",
3821
+ priority: "p0",
3822
+ 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."
3823
+ },
3824
+ {
3825
+ title: "Desktop and TUI are the same product",
3826
+ domain: "architecture",
3827
+ priority: "p0",
3828
+ 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."
3829
+ },
3830
+ // --- Orchestration golden path ---
3831
+ {
3832
+ title: "Task lifecycle \u2014 the golden path every agent follows",
3833
+ domain: "workflow",
3834
+ priority: "p0",
3835
+ 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.'"
3836
+ },
3837
+ {
3838
+ title: "Intercom is a speedup, not delivery \u2014 DB is the source of truth",
3839
+ domain: "architecture",
3840
+ priority: "p0",
3841
+ 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."
3842
+ },
3843
+ // --- MCP is the ONLY data interface ---
3844
+ {
3845
+ title: "MCP disconnect \u2014 ask the user, never work around it",
3846
+ domain: "workflow",
3847
+ priority: "p0",
3848
+ 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."
3849
+ },
3850
+ // --- MCP Tool Catalog (Layer 0 — every agent knows what tools exist) ---
3851
+ {
3852
+ title: "MCP tools \u2014 memory and search",
3853
+ domain: "tool-use",
3854
+ priority: "p1",
3855
+ 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)."
3856
+ },
3857
+ {
3858
+ title: "MCP tools \u2014 task orchestration",
3859
+ domain: "tool-use",
3860
+ priority: "p1",
3861
+ 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."
3862
+ },
3863
+ {
3864
+ title: "MCP tools \u2014 knowledge graph (GraphRAG)",
3865
+ domain: "tool-use",
3866
+ priority: "p1",
3867
+ 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."
3868
+ },
3869
+ {
3870
+ title: "MCP tools \u2014 identity, behavior, and decisions",
3871
+ domain: "tool-use",
3872
+ priority: "p1",
3873
+ 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."
3874
+ },
3875
+ {
3876
+ title: "MCP tools \u2014 communication and messaging",
3877
+ domain: "tool-use",
3878
+ priority: "p1",
3879
+ 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.)."
3880
+ },
3881
+ {
3882
+ title: "MCP tools \u2014 wiki, documents, and content",
3883
+ domain: "tool-use",
3884
+ priority: "p1",
3885
+ 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."
3886
+ },
3887
+ {
3888
+ title: "MCP tools \u2014 system, operations, and admin",
3889
+ domain: "tool-use",
3890
+ priority: "p1",
3891
+ 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."
3892
+ },
3893
+ {
3894
+ title: "MCP tools \u2014 config, licensing, and team",
3895
+ domain: "tool-use",
3896
+ priority: "p1",
3897
+ 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."
3898
+ },
3899
+ {
3900
+ title: "MCP tools \u2014 advanced (triggers, skills, orchestration)",
3901
+ domain: "tool-use",
3902
+ priority: "p1",
3903
+ 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."
3904
+ }
3905
+ ];
3906
+ PLATFORM_PROCEDURE_TITLES = new Set(
3907
+ PLATFORM_PROCEDURES.map((p) => p.title)
3908
+ );
2960
3909
  }
2961
3910
  });
2962
3911
 
2963
- // src/lib/tasks-review.ts
2964
- import path13 from "path";
2965
- import { existsSync as existsSync12, readdirSync as readdirSync4, unlinkSync as unlinkSync3 } from "fs";
2966
- function formatAge(isoTimestamp) {
2967
- if (!isoTimestamp) return "";
2968
- const ms = Date.now() - new Date(isoTimestamp).getTime();
2969
- if (ms < 0) return "just now";
2970
- const minutes = Math.floor(ms / 6e4);
2971
- if (minutes < 60) return `${minutes}m ago`;
2972
- const hours = Math.floor(minutes / 60);
2973
- if (hours < 24) return `${hours}h ago`;
2974
- const days = Math.floor(hours / 24);
2975
- return `${days}d ago`;
2976
- }
2977
- function isStale(isoTimestamp) {
2978
- if (!isoTimestamp) return false;
2979
- return Date.now() - new Date(isoTimestamp).getTime() > 24 * 60 * 60 * 1e3;
2980
- }
2981
- async function listPendingReviews(limit, sessionScope) {
3912
+ // src/lib/global-procedures.ts
3913
+ var global_procedures_exports = {};
3914
+ __export(global_procedures_exports, {
3915
+ deactivateGlobalProcedure: () => deactivateGlobalProcedure,
3916
+ getGlobalProceduresBlock: () => getGlobalProceduresBlock,
3917
+ loadGlobalProcedures: () => loadGlobalProcedures,
3918
+ storeGlobalProcedure: () => storeGlobalProcedure
3919
+ });
3920
+ import { randomUUID as randomUUID3 } from "crypto";
3921
+ async function loadGlobalProcedures() {
2982
3922
  const client = getClient();
2983
- const scope = strictSessionScopeFilter(
2984
- sessionScope === void 0 ? getCurrentSessionScope() : sessionScope
2985
- );
2986
3923
  const result = await client.execute({
2987
- sql: `SELECT title, assigned_to, project_name, updated_at FROM tasks
2988
- WHERE status = 'needs_review'${scope.sql}
2989
- ORDER BY updated_at ASC LIMIT ?`,
2990
- args: [...scope.args, limit]
3924
+ sql: "SELECT * FROM global_procedures WHERE active = 1 ORDER BY priority ASC, created_at ASC",
3925
+ args: []
2991
3926
  });
2992
- return result.rows;
3927
+ const allRows = result.rows;
3928
+ const customerOnly = allRows.filter((p) => !PLATFORM_PROCEDURE_TITLES.has(p.title));
3929
+ if (customerOnly.length > 0) {
3930
+ _customerCache = customerOnly.map((p) => `### ${p.title}
3931
+ ${p.content}`).join("\n\n");
3932
+ } else {
3933
+ _customerCache = "";
3934
+ }
3935
+ _cacheLoaded = true;
3936
+ return customerOnly;
2993
3937
  }
2994
- async function cleanupOrphanedReviews() {
2995
- const client = getClient();
3938
+ function getGlobalProceduresBlock() {
3939
+ const sections = [];
3940
+ if (_platformCache) sections.push(_platformCache);
3941
+ if (_cacheLoaded && _customerCache) sections.push(_customerCache);
3942
+ if (sections.length === 0) return "";
3943
+ return `## Organization-Wide Procedures (MANDATORY \u2014 supersedes all other rules)
3944
+
3945
+ ${sections.join("\n\n")}
3946
+ `;
3947
+ }
3948
+ async function storeGlobalProcedure(input) {
3949
+ const id = randomUUID3();
2996
3950
  const now = (/* @__PURE__ */ new Date()).toISOString();
2997
- const r1 = await client.execute({
2998
- sql: `UPDATE tasks SET status = 'cancelled', updated_at = ?
2999
- WHERE status IN ('open', 'needs_review', 'in_progress')
3000
- AND assigned_by = 'system'
3001
- AND title LIKE 'Review:%'
3002
- AND parent_task_id IN (SELECT id FROM tasks WHERE status IN ('done', 'cancelled', 'closed'))`,
3003
- args: [now]
3004
- });
3005
- const r1b = await client.execute({
3006
- sql: `UPDATE tasks SET status = 'cancelled', updated_at = ?
3007
- WHERE status IN ('open', 'needs_review')
3008
- AND title LIKE 'Review:%completed%'
3009
- AND (parent_task_id IS NULL OR parent_task_id NOT IN (SELECT id FROM tasks WHERE status IN ('open', 'in_progress', 'needs_review', 'blocked')))`,
3010
- args: [now]
3951
+ const client = getClient();
3952
+ await client.execute({
3953
+ sql: `INSERT INTO global_procedures (id, title, content, priority, domain, active, created_at, updated_at)
3954
+ VALUES (?, ?, ?, ?, ?, 1, ?, ?)`,
3955
+ args: [id, input.title, input.content, input.priority ?? "p0", input.domain ?? null, now, now]
3011
3956
  });
3012
- const staleThreshold = new Date(Date.now() - 60 * 60 * 1e3).toISOString();
3013
- const r2 = await client.execute({
3014
- sql: `UPDATE tasks SET status = 'done', updated_at = ?
3015
- WHERE status = 'needs_review'
3016
- AND result IS NOT NULL
3017
- AND updated_at < ?`,
3018
- args: [now, staleThreshold]
3957
+ await loadGlobalProcedures();
3958
+ return id;
3959
+ }
3960
+ async function deactivateGlobalProcedure(id) {
3961
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3962
+ const client = getClient();
3963
+ const result = await client.execute({
3964
+ sql: "UPDATE global_procedures SET active = 0, updated_at = ? WHERE id = ?",
3965
+ args: [now, id]
3019
3966
  });
3020
- const total = r1.rowsAffected + (r1b?.rowsAffected ?? 0) + r2.rowsAffected;
3021
- if (total > 0) {
3022
- process.stderr.write(
3023
- `[cleanup] Closed ${total} orphaned review(s): ${r1.rowsAffected} cascade + ${r1b?.rowsAffected ?? 0} orphan + ${r2.rowsAffected} stale
3024
- `
3025
- );
3026
- }
3027
- return total;
3967
+ await loadGlobalProcedures();
3968
+ return result.rowsAffected > 0;
3028
3969
  }
3029
- var init_tasks_review = __esm({
3030
- "src/lib/tasks-review.ts"() {
3970
+ var _customerCache, _cacheLoaded, _platformCache;
3971
+ var init_global_procedures = __esm({
3972
+ "src/lib/global-procedures.ts"() {
3031
3973
  "use strict";
3032
3974
  init_database();
3033
- init_config();
3034
- init_employees();
3035
- init_notifications();
3036
- init_tmux_routing();
3037
- init_session_key();
3038
- init_state_bus();
3039
- init_task_scope();
3975
+ init_platform_procedures();
3976
+ _customerCache = "";
3977
+ _cacheLoaded = false;
3978
+ _platformCache = PLATFORM_PROCEDURES.map((p) => `### ${p.title}
3979
+ ${p.content}`).join("\n\n");
3040
3980
  }
3041
3981
  });
3042
3982
 
3043
3983
  // src/lib/store.ts
3984
+ var store_exports = {};
3985
+ __export(store_exports, {
3986
+ attachDocumentMetadata: () => attachDocumentMetadata,
3987
+ buildRawVisibilityFilter: () => buildRawVisibilityFilter,
3988
+ buildWikiScopeFilter: () => buildWikiScopeFilter,
3989
+ classifyTier: () => classifyTier,
3990
+ disposeStore: () => disposeStore,
3991
+ flushBatch: () => flushBatch,
3992
+ flushTier3: () => flushTier3,
3993
+ getMemoryCardinality: () => getMemoryCardinality,
3994
+ initStore: () => initStore,
3995
+ reserveVersions: () => reserveVersions,
3996
+ searchMemories: () => searchMemories,
3997
+ updateMemoryStatus: () => updateMemoryStatus,
3998
+ vectorToBlob: () => vectorToBlob,
3999
+ writeMemory: () => writeMemory
4000
+ });
3044
4001
  import { createHash } from "crypto";
3045
- init_database();
3046
-
3047
- // src/lib/keychain.ts
3048
- import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
3049
- import { existsSync as existsSync4 } from "fs";
3050
- import path4 from "path";
3051
- import os4 from "os";
3052
- var SERVICE = "exe-mem";
3053
- var ACCOUNT = "master-key";
3054
- function getKeyDir() {
3055
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
3056
- }
3057
- function getKeyPath() {
3058
- return path4.join(getKeyDir(), "master.key");
3059
- }
3060
- async function tryKeytar() {
3061
- try {
3062
- return await import("keytar");
3063
- } catch {
3064
- return null;
3065
- }
3066
- }
3067
- async function getMasterKey() {
3068
- const keytar = await tryKeytar();
3069
- if (keytar) {
3070
- try {
3071
- const stored = await keytar.getPassword(SERVICE, ACCOUNT);
3072
- if (stored) {
3073
- return Buffer.from(stored, "base64");
3074
- }
3075
- } catch {
3076
- }
3077
- }
3078
- const keyPath = getKeyPath();
3079
- if (!existsSync4(keyPath)) {
3080
- process.stderr.write(
3081
- `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
3082
- `
3083
- );
3084
- return null;
3085
- }
3086
- try {
3087
- const content = await readFile3(keyPath, "utf-8");
3088
- return Buffer.from(content.trim(), "base64");
3089
- } catch (err) {
3090
- process.stderr.write(
3091
- `[keychain] Key read failed at ${keyPath}: ${err instanceof Error ? err.message : String(err)}
3092
- `
3093
- );
3094
- return null;
3095
- }
3096
- }
3097
-
3098
- // src/lib/store.ts
3099
- init_config();
3100
- init_state_bus();
3101
- var INIT_MAX_RETRIES = 3;
3102
- var INIT_RETRY_DELAY_MS = 1e3;
3103
4002
  function isBusyError2(err) {
3104
4003
  if (err instanceof Error) {
3105
4004
  const msg = err.message.toLowerCase();
@@ -3122,12 +4021,6 @@ async function retryOnBusy2(fn, label) {
3122
4021
  }
3123
4022
  throw new Error("unreachable");
3124
4023
  }
3125
- var _pendingRecords = [];
3126
- var _batchSize = 20;
3127
- var _flushIntervalMs = 1e4;
3128
- var _flushTimer = null;
3129
- var _flushing = false;
3130
- var _nextVersion = 1;
3131
4024
  async function initStore(options) {
3132
4025
  if (_flushTimer !== null) {
3133
4026
  clearInterval(_flushTimer);
@@ -3157,6 +4050,11 @@ async function initStore(options) {
3157
4050
  encryptionKey: hexKey
3158
4051
  });
3159
4052
  await retryOnBusy2(() => ensureSchema(), "ensureSchema");
4053
+ try {
4054
+ const { initDaemonClient: initDaemonClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
4055
+ await initDaemonClient2();
4056
+ } catch {
4057
+ }
3160
4058
  if (!options?.lightweight) {
3161
4059
  try {
3162
4060
  const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
@@ -3176,6 +4074,499 @@ async function initStore(options) {
3176
4074
  }
3177
4075
  }
3178
4076
  }
4077
+ function classifyTier(record) {
4078
+ if (record.tool_name === "commit_to_long_term_memory" && (record.importance ?? 0) >= 8) return 1;
4079
+ if (["store_memory", "manual"].includes(record.tool_name ?? "") && (record.importance ?? 0) >= 5) return 2;
4080
+ return 3;
4081
+ }
4082
+ function inferFilePaths(record) {
4083
+ if (!["Read", "Write", "Edit"].includes(record.tool_name)) return null;
4084
+ const firstLine = record.raw_text.split("\n")[0] ?? "";
4085
+ const match = firstLine.match(/(\/[\w./-]+\.\w+)/);
4086
+ return match ? JSON.stringify([match[1]]) : null;
4087
+ }
4088
+ function inferCommitHash(record) {
4089
+ if (record.tool_name !== "Bash") return null;
4090
+ const match = record.raw_text.match(/\b([a-f0-9]{7,40})\b/);
4091
+ return match ? match[1] : null;
4092
+ }
4093
+ function inferLanguageType(record) {
4094
+ const text = record.raw_text;
4095
+ if (!text || text.length < 10) return null;
4096
+ const trimmed = text.trimStart();
4097
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) return "json";
4098
+ if (/\b(SELECT|INSERT|UPDATE|DELETE|CREATE TABLE|ALTER TABLE)\b/i.test(text)) return "sql";
4099
+ if (/\b(function |const |import |export |class |def |async |=>)\b/.test(text)) return "code";
4100
+ if (trimmed.startsWith("#") || trimmed.startsWith("*")) return "prose";
4101
+ return "mixed";
4102
+ }
4103
+ function inferDomain(record) {
4104
+ const proj = (record.project_name ?? "").toLowerCase();
4105
+ if (proj.includes("marketing") || proj.includes("content")) return "marketing";
4106
+ if (proj.includes("crm") || proj.includes("customer")) return "customer";
4107
+ return null;
4108
+ }
4109
+ async function writeMemory(record) {
4110
+ if (record.vector !== null && record.vector.length !== EMBEDDING_DIM) {
4111
+ throw new Error(
4112
+ `Expected ${EMBEDDING_DIM}-dim vector, got ${record.vector.length}`
4113
+ );
4114
+ }
4115
+ const contentHash = createHash("md5").update(record.raw_text).digest("hex");
4116
+ if (_pendingRecords.some((r) => r.content_hash === contentHash && r.agent_id === record.agent_id)) {
4117
+ return;
4118
+ }
4119
+ try {
4120
+ const client = getClient();
4121
+ const existing = await client.execute({
4122
+ sql: "SELECT id FROM memories WHERE content_hash = ? AND agent_id = ? LIMIT 1",
4123
+ args: [contentHash, record.agent_id]
4124
+ });
4125
+ if (existing.rows.length > 0) return;
4126
+ } catch {
4127
+ }
4128
+ const dbRow = {
4129
+ id: record.id,
4130
+ agent_id: record.agent_id,
4131
+ agent_role: record.agent_role,
4132
+ session_id: record.session_id,
4133
+ timestamp: record.timestamp,
4134
+ tool_name: record.tool_name,
4135
+ project_name: record.project_name,
4136
+ has_error: record.has_error ? 1 : 0,
4137
+ raw_text: record.raw_text,
4138
+ vector: record.vector,
4139
+ version: 0,
4140
+ // Placeholder — assigned atomically at flush time
4141
+ task_id: record.task_id ?? null,
4142
+ importance: record.importance ?? 5,
4143
+ status: record.status ?? "active",
4144
+ confidence: record.confidence ?? 0.7,
4145
+ last_accessed: record.last_accessed ?? record.timestamp,
4146
+ workspace_id: record.workspace_id ?? null,
4147
+ document_id: record.document_id ?? null,
4148
+ user_id: record.user_id ?? null,
4149
+ char_offset: record.char_offset ?? null,
4150
+ page_number: record.page_number ?? null,
4151
+ source_path: record.source_path ?? null,
4152
+ source_type: record.source_type ?? null,
4153
+ tier: record.tier ?? classifyTier(record),
4154
+ supersedes_id: record.supersedes_id ?? null,
4155
+ draft: record.draft ? 1 : 0,
4156
+ memory_type: record.memory_type ?? "raw",
4157
+ trajectory: record.trajectory ? JSON.stringify(record.trajectory) : null,
4158
+ content_hash: contentHash,
4159
+ intent: record.intent ?? null,
4160
+ outcome: record.outcome ?? null,
4161
+ domain: record.domain ?? inferDomain(record),
4162
+ referenced_entities: record.referenced_entities ?? null,
4163
+ retrieval_count: record.retrieval_count ?? 0,
4164
+ chain_position: record.chain_position ?? null,
4165
+ review_status: record.review_status ?? null,
4166
+ context_window_pct: record.context_window_pct ?? null,
4167
+ file_paths: record.file_paths ?? inferFilePaths(record),
4168
+ commit_hash: record.commit_hash ?? inferCommitHash(record),
4169
+ duration_ms: record.duration_ms ?? null,
4170
+ token_cost: record.token_cost ?? null,
4171
+ audience: record.audience ?? null,
4172
+ language_type: record.language_type ?? inferLanguageType(record),
4173
+ parent_memory_id: record.parent_memory_id ?? null
4174
+ };
4175
+ _pendingRecords.push(dbRow);
4176
+ orgBus.emit({
4177
+ type: "memory_stored",
4178
+ agentId: record.agent_id,
4179
+ project: record.project_name,
4180
+ timestamp: record.timestamp
4181
+ });
4182
+ const MAX_PENDING = 1e3;
4183
+ if (_pendingRecords.length > MAX_PENDING) {
4184
+ const dropped = _pendingRecords.length - MAX_PENDING;
4185
+ _pendingRecords = _pendingRecords.slice(-MAX_PENDING);
4186
+ console.warn(`[store] Dropped ${dropped} oldest pending records (overflow)`);
4187
+ }
4188
+ if (_flushTimer === null) {
4189
+ _flushTimer = setInterval(() => {
4190
+ void flushBatch();
4191
+ }, _flushIntervalMs);
4192
+ if (_flushTimer && typeof _flushTimer === "object" && "unref" in _flushTimer) {
4193
+ _flushTimer.unref();
4194
+ }
4195
+ }
4196
+ if (_pendingRecords.length >= _batchSize) {
4197
+ await flushBatch();
4198
+ }
4199
+ }
4200
+ async function flushBatch() {
4201
+ if (_flushing || _pendingRecords.length === 0) return 0;
4202
+ _flushing = true;
4203
+ try {
4204
+ const batch = _pendingRecords.slice(0);
4205
+ const client = getClient();
4206
+ const vResult = await client.execute("SELECT MAX(version) as max_v FROM memories");
4207
+ let baseVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
4208
+ for (const row of batch) {
4209
+ row.version = baseVersion++;
4210
+ }
4211
+ _nextVersion = baseVersion;
4212
+ const buildStmt = (row) => {
4213
+ const hasVector = row.vector !== null;
4214
+ const taskId = row.task_id ?? null;
4215
+ const importance = row.importance ?? 5;
4216
+ const status = row.status ?? "active";
4217
+ const confidence = row.confidence ?? 0.7;
4218
+ const lastAccessed = row.last_accessed ?? row.timestamp;
4219
+ const workspaceId = row.workspace_id ?? null;
4220
+ const documentId = row.document_id ?? null;
4221
+ const userId = row.user_id ?? null;
4222
+ const charOffset = row.char_offset ?? null;
4223
+ const pageNumber = row.page_number ?? null;
4224
+ const sourcePath = row.source_path ?? null;
4225
+ const sourceType = row.source_type ?? null;
4226
+ const tier = row.tier ?? 3;
4227
+ const supersedesId = row.supersedes_id ?? null;
4228
+ const draft = row.draft ? 1 : 0;
4229
+ const memoryType = row.memory_type ?? "raw";
4230
+ const trajectory = row.trajectory ?? null;
4231
+ const contentHash = row.content_hash ?? null;
4232
+ const intent = row.intent ?? null;
4233
+ const outcome = row.outcome ?? null;
4234
+ const domain = row.domain ?? null;
4235
+ const referencedEntities = row.referenced_entities ?? null;
4236
+ const retrievalCount = row.retrieval_count ?? 0;
4237
+ const chainPosition = row.chain_position ?? null;
4238
+ const reviewStatus = row.review_status ?? null;
4239
+ const contextWindowPct = row.context_window_pct ?? null;
4240
+ const filePaths = row.file_paths ?? null;
4241
+ const commitHash = row.commit_hash ?? null;
4242
+ const durationMs = row.duration_ms ?? null;
4243
+ const tokenCost = row.token_cost ?? null;
4244
+ const audience = row.audience ?? null;
4245
+ const languageType = row.language_type ?? null;
4246
+ const parentMemoryId = row.parent_memory_id ?? null;
4247
+ const cols = `id, agent_id, agent_role, session_id, timestamp,
4248
+ tool_name, project_name,
4249
+ has_error, raw_text, vector, version, task_id, importance, status,
4250
+ confidence, last_accessed,
4251
+ workspace_id, document_id, user_id, char_offset, page_number,
4252
+ source_path, source_type, tier, supersedes_id, draft, memory_type, trajectory, content_hash,
4253
+ intent, outcome, domain, referenced_entities, retrieval_count,
4254
+ chain_position, review_status, context_window_pct, file_paths, commit_hash,
4255
+ duration_ms, token_cost, audience, language_type, parent_memory_id`;
4256
+ const metaArgs = [
4257
+ intent,
4258
+ outcome,
4259
+ domain,
4260
+ referencedEntities,
4261
+ retrievalCount,
4262
+ chainPosition,
4263
+ reviewStatus,
4264
+ contextWindowPct,
4265
+ filePaths,
4266
+ commitHash,
4267
+ durationMs,
4268
+ tokenCost,
4269
+ audience,
4270
+ languageType,
4271
+ parentMemoryId
4272
+ ];
4273
+ const baseArgs = [
4274
+ row.id,
4275
+ row.agent_id,
4276
+ row.agent_role,
4277
+ row.session_id,
4278
+ row.timestamp,
4279
+ row.tool_name,
4280
+ row.project_name,
4281
+ row.has_error,
4282
+ row.raw_text
4283
+ ];
4284
+ const sharedArgs = [
4285
+ row.version,
4286
+ taskId,
4287
+ importance,
4288
+ status,
4289
+ confidence,
4290
+ lastAccessed,
4291
+ workspaceId,
4292
+ documentId,
4293
+ userId,
4294
+ charOffset,
4295
+ pageNumber,
4296
+ sourcePath,
4297
+ sourceType,
4298
+ tier,
4299
+ supersedesId,
4300
+ draft,
4301
+ memoryType,
4302
+ trajectory,
4303
+ contentHash
4304
+ ];
4305
+ return {
4306
+ sql: hasVector ? `INSERT OR IGNORE INTO memories (${cols})
4307
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, vector32(?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` : `INSERT OR IGNORE INTO memories (${cols})
4308
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
4309
+ args: hasVector ? [...baseArgs, vectorToBlob(row.vector), ...sharedArgs, ...metaArgs] : [...baseArgs, ...sharedArgs, ...metaArgs]
4310
+ };
4311
+ };
4312
+ const globalClient = getClient();
4313
+ const globalStmts = batch.map(buildStmt);
4314
+ await globalClient.batch(globalStmts, "write");
4315
+ _pendingRecords.splice(0, batch.length);
4316
+ try {
4317
+ const { isShardingEnabled: isShardingEnabled2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
4318
+ if (isShardingEnabled2()) {
4319
+ const byProject = /* @__PURE__ */ new Map();
4320
+ for (const row of batch) {
4321
+ const proj = row.project_name || "unknown";
4322
+ if (!byProject.has(proj)) byProject.set(proj, []);
4323
+ byProject.get(proj).push(row);
4324
+ }
4325
+ for (const [project, rows] of byProject) {
4326
+ try {
4327
+ const shardClient = await getReadyShardClient2(project);
4328
+ const shardStmts = rows.map(buildStmt);
4329
+ await shardClient.batch(shardStmts, "write");
4330
+ } catch (err) {
4331
+ process.stderr.write(
4332
+ `[store] Shard write failed for ${project}: ${err instanceof Error ? err.message : String(err)}
4333
+ `
4334
+ );
4335
+ }
4336
+ }
4337
+ }
4338
+ } catch {
4339
+ }
4340
+ return batch.length;
4341
+ } finally {
4342
+ _flushing = false;
4343
+ }
4344
+ }
4345
+ function buildWikiScopeFilter(options, columnPrefix) {
4346
+ const args = [];
4347
+ let clause = "";
4348
+ if (options?.workspaceId !== void 0) {
4349
+ clause += ` AND ${columnPrefix}workspace_id = ?`;
4350
+ args.push(options.workspaceId);
4351
+ }
4352
+ if (options?.userId === void 0) {
4353
+ clause += ` AND ${columnPrefix}user_id IS NULL`;
4354
+ } else if (options.userId === null) {
4355
+ clause += ` AND ${columnPrefix}user_id IS NULL`;
4356
+ } else {
4357
+ clause += ` AND (${columnPrefix}user_id = ? OR ${columnPrefix}user_id IS NULL)`;
4358
+ args.push(options.userId);
4359
+ }
4360
+ return { clause, args };
4361
+ }
4362
+ function buildRawVisibilityFilter(options, columnPrefix) {
4363
+ if (options?.includeRaw === false) {
4364
+ return {
4365
+ clause: ` AND COALESCE(${columnPrefix}memory_type, 'raw') != 'raw'`,
4366
+ args: []
4367
+ };
4368
+ }
4369
+ return { clause: "", args: [] };
4370
+ }
4371
+ async function searchMemories(queryVector, agentId, options) {
4372
+ let client;
4373
+ try {
4374
+ const { isShardingEnabled: isShardingEnabled2, shardExists: shardExists2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
4375
+ if (isShardingEnabled2() && options?.projectName && shardExists2(options.projectName)) {
4376
+ client = await getReadyShardClient2(options.projectName);
4377
+ } else {
4378
+ client = getClient();
4379
+ }
4380
+ } catch {
4381
+ client = getClient();
4382
+ }
4383
+ const limit = options?.limit ?? 10;
4384
+ const statusFilter = options?.includeArchived ? "" : `
4385
+ AND COALESCE(status, 'active') = 'active'`;
4386
+ const draftFilter = options?.includeDrafts ? "" : `
4387
+ AND (draft = 0 OR draft IS NULL)`;
4388
+ let sql = `SELECT id, agent_id, agent_role, session_id, timestamp,
4389
+ tool_name, project_name,
4390
+ has_error, raw_text, vector, importance, status,
4391
+ confidence, last_accessed,
4392
+ workspace_id, document_id, user_id,
4393
+ char_offset, page_number,
4394
+ source_path, source_type
4395
+ FROM memories
4396
+ WHERE agent_id = ?
4397
+ AND vector IS NOT NULL${statusFilter}${draftFilter}
4398
+ AND COALESCE(confidence, 0.7) >= 0.3`;
4399
+ const args = [agentId];
4400
+ const scope = buildWikiScopeFilter(options, "");
4401
+ sql += scope.clause;
4402
+ args.push(...scope.args);
4403
+ const rawVisibility = buildRawVisibilityFilter(options, "");
4404
+ sql += rawVisibility.clause;
4405
+ args.push(...rawVisibility.args);
4406
+ if (options?.projectName) {
4407
+ sql += ` AND project_name = ?`;
4408
+ args.push(options.projectName);
4409
+ }
4410
+ if (options?.toolName) {
4411
+ sql += ` AND tool_name = ?`;
4412
+ args.push(options.toolName);
4413
+ }
4414
+ if (options?.hasError !== void 0) {
4415
+ sql += ` AND has_error = ?`;
4416
+ args.push(options.hasError ? 1 : 0);
4417
+ }
4418
+ if (options?.since) {
4419
+ sql += ` AND timestamp >= ?`;
4420
+ args.push(options.since);
4421
+ }
4422
+ if (options?.memoryType) {
4423
+ sql += ` AND memory_type = ?`;
4424
+ args.push(options.memoryType);
4425
+ }
4426
+ sql += ` ORDER BY vector_distance_cos(vector, vector32(?))`;
4427
+ args.push(vectorToBlob(queryVector));
4428
+ sql += ` LIMIT ?`;
4429
+ args.push(limit);
4430
+ const result = await client.execute({ sql, args });
4431
+ return result.rows.map((row) => ({
4432
+ id: row.id,
4433
+ agent_id: row.agent_id,
4434
+ agent_role: row.agent_role,
4435
+ session_id: row.session_id,
4436
+ timestamp: row.timestamp,
4437
+ tool_name: row.tool_name,
4438
+ project_name: row.project_name,
4439
+ has_error: row.has_error === 1,
4440
+ raw_text: row.raw_text,
4441
+ vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
4442
+ importance: row.importance ?? 5,
4443
+ status: row.status ?? "active",
4444
+ confidence: row.confidence ?? 0.7,
4445
+ last_accessed: row.last_accessed ?? row.timestamp,
4446
+ workspace_id: row.workspace_id ?? null,
4447
+ document_id: row.document_id ?? null,
4448
+ user_id: row.user_id ?? null,
4449
+ char_offset: row.char_offset ?? null,
4450
+ page_number: row.page_number ?? null,
4451
+ source_path: row.source_path ?? null,
4452
+ source_type: row.source_type ?? null
4453
+ }));
4454
+ }
4455
+ async function attachDocumentMetadata(records) {
4456
+ const docIds = [
4457
+ ...new Set(
4458
+ records.map((r) => r.document_id).filter((id) => typeof id === "string" && id.length > 0)
4459
+ )
4460
+ ];
4461
+ if (docIds.length === 0) return records;
4462
+ try {
4463
+ const client = getClient();
4464
+ const placeholders = docIds.map(() => "?").join(",");
4465
+ const result = await client.execute({
4466
+ sql: `SELECT id, filename, mime, source_type, uploaded_at
4467
+ FROM documents
4468
+ WHERE id IN (${placeholders})`,
4469
+ args: docIds
4470
+ });
4471
+ const byId = /* @__PURE__ */ new Map();
4472
+ for (const row of result.rows) {
4473
+ const id = row.id;
4474
+ byId.set(id, {
4475
+ document_id: id,
4476
+ filename: row.filename,
4477
+ mime: row.mime ?? null,
4478
+ source_type: row.source_type ?? null,
4479
+ uploaded_at: row.uploaded_at
4480
+ });
4481
+ }
4482
+ for (const record of records) {
4483
+ if (!record.document_id) continue;
4484
+ record.document_metadata = byId.get(record.document_id) ?? null;
4485
+ }
4486
+ } catch {
4487
+ }
4488
+ return records;
4489
+ }
4490
+ async function flushTier3(agentId, options) {
4491
+ const client = getClient();
4492
+ const maxAge = options?.maxAgeHours ?? 72;
4493
+ const cutoff = new Date(Date.now() - maxAge * 36e5).toISOString();
4494
+ if (options?.dryRun) {
4495
+ const result2 = await client.execute({
4496
+ sql: `SELECT COUNT(*) as cnt FROM memories
4497
+ WHERE agent_id = ? AND tier = 3 AND status = 'active' AND timestamp < ?`,
4498
+ args: [agentId, cutoff]
4499
+ });
4500
+ return { archived: Number(result2.rows[0]?.cnt ?? 0) };
4501
+ }
4502
+ const result = await client.execute({
4503
+ sql: `UPDATE memories SET status = 'archived'
4504
+ WHERE agent_id = ? AND tier = 3 AND status = 'active' AND timestamp < ?`,
4505
+ args: [agentId, cutoff]
4506
+ });
4507
+ return { archived: result.rowsAffected };
4508
+ }
4509
+ async function disposeStore() {
4510
+ if (_flushTimer !== null) {
4511
+ clearInterval(_flushTimer);
4512
+ _flushTimer = null;
4513
+ }
4514
+ if (_pendingRecords.length > 0) {
4515
+ await flushBatch();
4516
+ }
4517
+ await disposeTurso();
4518
+ _pendingRecords = [];
4519
+ _nextVersion = 1;
4520
+ }
4521
+ function vectorToBlob(vector) {
4522
+ const f32 = vector instanceof Float32Array ? vector : new Float32Array(vector);
4523
+ return JSON.stringify(Array.from(f32));
4524
+ }
4525
+ async function updateMemoryStatus(id, status) {
4526
+ const client = getClient();
4527
+ await client.execute({
4528
+ sql: `UPDATE memories SET status = ? WHERE id = ?`,
4529
+ args: [status, id]
4530
+ });
4531
+ }
4532
+ function reserveVersions(count) {
4533
+ const reserved = [];
4534
+ for (let i = 0; i < count; i++) {
4535
+ reserved.push(_nextVersion++);
4536
+ }
4537
+ return reserved;
4538
+ }
4539
+ async function getMemoryCardinality(agentId) {
4540
+ try {
4541
+ const client = getClient();
4542
+ const result = await client.execute({
4543
+ sql: `SELECT COUNT(*) as cnt FROM memories WHERE agent_id = ? AND COALESCE(status, 'active') = 'active'`,
4544
+ args: [agentId]
4545
+ });
4546
+ return Number(result.rows[0]?.cnt) || 0;
4547
+ } catch {
4548
+ return 0;
4549
+ }
4550
+ }
4551
+ var INIT_MAX_RETRIES, INIT_RETRY_DELAY_MS, _pendingRecords, _batchSize, _flushIntervalMs, _flushTimer, _flushing, _nextVersion;
4552
+ var init_store = __esm({
4553
+ "src/lib/store.ts"() {
4554
+ "use strict";
4555
+ init_memory();
4556
+ init_database();
4557
+ init_keychain();
4558
+ init_config();
4559
+ init_state_bus();
4560
+ INIT_MAX_RETRIES = 3;
4561
+ INIT_RETRY_DELAY_MS = 1e3;
4562
+ _pendingRecords = [];
4563
+ _batchSize = 20;
4564
+ _flushIntervalMs = 1e4;
4565
+ _flushTimer = null;
4566
+ _flushing = false;
4567
+ _nextVersion = 1;
4568
+ }
4569
+ });
3179
4570
 
3180
4571
  // src/lib/is-main.ts
3181
4572
  import { realpathSync } from "fs";
@@ -3195,9 +4586,73 @@ function isMainModule(importMetaUrl) {
3195
4586
  // src/bin/exe-pending-reviews.ts
3196
4587
  init_tasks_review();
3197
4588
  init_tmux_routing();
4589
+
4590
+ // src/bin/fast-db-init.ts
4591
+ async function fastDbInit() {
4592
+ const { isInitialized: isInitialized2, getClient: getClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
4593
+ if (isInitialized2()) {
4594
+ return getClient2();
4595
+ }
4596
+ try {
4597
+ const { connectEmbedDaemon: connectEmbedDaemon2, sendDaemonRequest: sendDaemonRequest2, isClientConnected: isClientConnected2 } = await Promise.resolve().then(() => (init_exe_daemon_client(), exe_daemon_client_exports));
4598
+ const { deserializeResultSet: deserializeResultSet2 } = await Promise.resolve().then(() => (init_daemon_protocol(), daemon_protocol_exports));
4599
+ await connectEmbedDaemon2();
4600
+ if (isClientConnected2()) {
4601
+ const daemonClient = {
4602
+ async execute(stmt) {
4603
+ const sql = typeof stmt === "string" ? stmt : stmt.sql;
4604
+ const args = typeof stmt === "string" ? [] : Array.isArray(stmt.args) ? stmt.args : [];
4605
+ const resp = await sendDaemonRequest2({ type: "db-execute", sql, args });
4606
+ if (resp.error) throw new Error(String(resp.error));
4607
+ if (resp.db) return deserializeResultSet2(resp.db);
4608
+ throw new Error("Unexpected daemon response");
4609
+ },
4610
+ async batch(stmts, mode) {
4611
+ const statements = stmts.map((s) => {
4612
+ const sql = typeof s === "string" ? s : s.sql;
4613
+ const args = typeof s === "string" ? [] : Array.isArray(s.args) ? s.args : [];
4614
+ return { sql, args };
4615
+ });
4616
+ const resp = await sendDaemonRequest2({ type: "db-batch", statements, mode: mode ?? "deferred" });
4617
+ if (resp.error) throw new Error(String(resp.error));
4618
+ const batchResults = resp["db-batch"];
4619
+ if (batchResults) return batchResults.map(deserializeResultSet2);
4620
+ throw new Error("Unexpected daemon batch response");
4621
+ },
4622
+ async transaction(_mode) {
4623
+ throw new Error("Transactions not supported via daemon socket");
4624
+ },
4625
+ async executeMultiple(_sql) {
4626
+ throw new Error("executeMultiple not supported via daemon socket");
4627
+ },
4628
+ async migrate(_stmts) {
4629
+ throw new Error("migrate not supported via daemon socket");
4630
+ },
4631
+ sync() {
4632
+ return Promise.resolve(void 0);
4633
+ },
4634
+ close() {
4635
+ },
4636
+ get closed() {
4637
+ return false;
4638
+ },
4639
+ get protocol() {
4640
+ return "file";
4641
+ }
4642
+ };
4643
+ return daemonClient;
4644
+ }
4645
+ } catch {
4646
+ }
4647
+ const { initStore: initStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
4648
+ await initStore2({ lightweight: true });
4649
+ return getClient2();
4650
+ }
4651
+
4652
+ // src/bin/exe-pending-reviews.ts
3198
4653
  var PENDING_REVIEW_LIMIT = 10;
3199
4654
  async function main() {
3200
- await initStore();
4655
+ await fastDbInit();
3201
4656
  await cleanupOrphanedReviews();
3202
4657
  let sessionScope = process.env.EXE_SESSION ? extractRootExe(process.env.EXE_SESSION) ?? void 0 : void 0;
3203
4658
  if (!sessionScope) {