@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
  };
@@ -30,12 +36,25 @@ async function ensurePrivateDir(dirPath) {
30
36
  } catch {
31
37
  }
32
38
  }
39
+ function ensurePrivateDirSync(dirPath) {
40
+ mkdirSync(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
41
+ try {
42
+ chmodSync(dirPath, PRIVATE_DIR_MODE);
43
+ } catch {
44
+ }
45
+ }
33
46
  async function enforcePrivateFile(filePath) {
34
47
  try {
35
48
  await chmod(filePath, PRIVATE_FILE_MODE);
36
49
  } catch {
37
50
  }
38
51
  }
52
+ function enforcePrivateFileSync(filePath) {
53
+ try {
54
+ if (existsSync(filePath)) chmodSync(filePath, PRIVATE_FILE_MODE);
55
+ } catch {
56
+ }
57
+ }
39
58
  var PRIVATE_DIR_MODE, PRIVATE_FILE_MODE;
40
59
  var init_secure_files = __esm({
41
60
  "src/lib/secure-files.ts"() {
@@ -328,9 +347,9 @@ var MAX_RETRIES, BASE_DELAY_MS, MAX_JITTER_MS;
328
347
  var init_db_retry = __esm({
329
348
  "src/lib/db-retry.ts"() {
330
349
  "use strict";
331
- MAX_RETRIES = 3;
332
- BASE_DELAY_MS = 200;
333
- MAX_JITTER_MS = 300;
350
+ MAX_RETRIES = 5;
351
+ BASE_DELAY_MS = 250;
352
+ MAX_JITTER_MS = 400;
334
353
  }
335
354
  });
336
355
 
@@ -918,207 +937,988 @@ var init_database_adapter = __esm({
918
937
  }
919
938
  });
920
939
 
921
- // src/lib/database.ts
922
- import { createClient } from "@libsql/client";
923
- async function initDatabase(config) {
924
- if (_walCheckpointTimer) {
925
- clearInterval(_walCheckpointTimer);
926
- _walCheckpointTimer = null;
940
+ // src/types/memory.ts
941
+ var EMBEDDING_DIM;
942
+ var init_memory = __esm({
943
+ "src/types/memory.ts"() {
944
+ "use strict";
945
+ EMBEDDING_DIM = 1024;
927
946
  }
928
- if (_daemonClient) {
929
- _daemonClient.close();
930
- _daemonClient = null;
947
+ });
948
+
949
+ // src/lib/daemon-auth.ts
950
+ import crypto from "crypto";
951
+ import path4 from "path";
952
+ import { existsSync as existsSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
953
+ function normalizeToken(token) {
954
+ if (!token) return null;
955
+ const trimmed = token.trim();
956
+ return trimmed.length > 0 ? trimmed : null;
957
+ }
958
+ function readDaemonToken() {
959
+ try {
960
+ if (!existsSync4(DAEMON_TOKEN_PATH)) return null;
961
+ return normalizeToken(readFileSync3(DAEMON_TOKEN_PATH, "utf8"));
962
+ } catch {
963
+ return null;
931
964
  }
932
- if (_adapterClient && _adapterClient !== _resilientClient) {
933
- _adapterClient.close();
965
+ }
966
+ function ensureDaemonToken(seed) {
967
+ const existing = readDaemonToken();
968
+ if (existing) return existing;
969
+ const token = normalizeToken(seed) ?? crypto.randomBytes(32).toString("hex");
970
+ ensurePrivateDirSync(EXE_AI_DIR);
971
+ writeFileSync2(DAEMON_TOKEN_PATH, `${token}
972
+ `, "utf8");
973
+ enforcePrivateFileSync(DAEMON_TOKEN_PATH);
974
+ return token;
975
+ }
976
+ var DAEMON_TOKEN_PATH;
977
+ var init_daemon_auth = __esm({
978
+ "src/lib/daemon-auth.ts"() {
979
+ "use strict";
980
+ init_config();
981
+ init_secure_files();
982
+ DAEMON_TOKEN_PATH = path4.join(EXE_AI_DIR, "exed.token");
934
983
  }
935
- _adapterClient = null;
936
- if (_client) {
937
- _client.close();
938
- _client = null;
939
- _resilientClient = null;
984
+ });
985
+
986
+ // src/lib/exe-daemon-client.ts
987
+ var exe_daemon_client_exports = {};
988
+ __export(exe_daemon_client_exports, {
989
+ connectEmbedDaemon: () => connectEmbedDaemon,
990
+ disconnectClient: () => disconnectClient,
991
+ embedBatchViaClient: () => embedBatchViaClient,
992
+ embedViaClient: () => embedViaClient,
993
+ isClientConnected: () => isClientConnected,
994
+ pingDaemon: () => pingDaemon,
995
+ sendDaemonRequest: () => sendDaemonRequest,
996
+ sendIngestRequest: () => sendIngestRequest
997
+ });
998
+ import net from "net";
999
+ import os4 from "os";
1000
+ import { spawn } from "child_process";
1001
+ import { randomUUID } from "crypto";
1002
+ import { existsSync as existsSync5, unlinkSync as unlinkSync2, readFileSync as readFileSync4, openSync, closeSync, statSync } from "fs";
1003
+ import path5 from "path";
1004
+ import { fileURLToPath } from "url";
1005
+ function handleData(chunk) {
1006
+ _buffer += chunk.toString();
1007
+ if (_buffer.length > MAX_BUFFER) {
1008
+ _buffer = "";
1009
+ return;
1010
+ }
1011
+ let newlineIdx;
1012
+ while ((newlineIdx = _buffer.indexOf("\n")) !== -1) {
1013
+ const line = _buffer.slice(0, newlineIdx).trim();
1014
+ _buffer = _buffer.slice(newlineIdx + 1);
1015
+ if (!line) continue;
1016
+ try {
1017
+ const response = JSON.parse(line);
1018
+ const id = response.id;
1019
+ if (!id) continue;
1020
+ const entry = _pending.get(id);
1021
+ if (entry) {
1022
+ clearTimeout(entry.timer);
1023
+ _pending.delete(id);
1024
+ entry.resolve(response);
1025
+ }
1026
+ } catch {
1027
+ }
940
1028
  }
941
- const opts = {
942
- url: `file:${config.dbPath}`
943
- };
944
- if (config.encryptionKey) {
945
- opts.encryptionKey = config.encryptionKey;
1029
+ }
1030
+ function cleanupStaleFiles() {
1031
+ if (existsSync5(PID_PATH)) {
1032
+ try {
1033
+ const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
1034
+ if (pid > 0) {
1035
+ try {
1036
+ process.kill(pid, 0);
1037
+ return;
1038
+ } catch {
1039
+ }
1040
+ }
1041
+ } catch {
1042
+ }
1043
+ try {
1044
+ unlinkSync2(PID_PATH);
1045
+ } catch {
1046
+ }
1047
+ try {
1048
+ unlinkSync2(SOCKET_PATH);
1049
+ } catch {
1050
+ }
946
1051
  }
947
- _client = createClient(opts);
948
- _resilientClient = wrapWithRetry(_client);
949
- _adapterClient = _resilientClient;
950
- _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
951
- });
952
- _client.execute("PRAGMA journal_mode = WAL").catch(() => {
953
- });
954
- if (_walCheckpointTimer) clearInterval(_walCheckpointTimer);
955
- _walCheckpointTimer = setInterval(() => {
956
- _client?.execute("PRAGMA wal_checkpoint(PASSIVE)").catch(() => {
957
- });
958
- }, 3e4);
959
- _walCheckpointTimer.unref();
960
- if (process.env.DATABASE_URL) {
961
- _adapterClient = await createPrismaDbAdapter(_resilientClient);
1052
+ }
1053
+ function findPackageRoot() {
1054
+ let dir = path5.dirname(fileURLToPath(import.meta.url));
1055
+ const { root } = path5.parse(dir);
1056
+ while (dir !== root) {
1057
+ if (existsSync5(path5.join(dir, "package.json"))) return dir;
1058
+ dir = path5.dirname(dir);
962
1059
  }
1060
+ return null;
963
1061
  }
964
- function getClient() {
965
- if (!_adapterClient) {
966
- throw new Error("Database client not initialized. Call initDatabase() first.");
1062
+ function getAvailableMemoryGB() {
1063
+ if (process.platform === "darwin") {
1064
+ try {
1065
+ const { execSync: execSync5 } = __require("child_process");
1066
+ const vmstat = execSync5("vm_stat", { encoding: "utf8" });
1067
+ const pageSize = 16384;
1068
+ const pageSizeMatch = vmstat.match(/page size of (\d+) bytes/);
1069
+ const actualPageSize = pageSizeMatch ? parseInt(pageSizeMatch[1], 10) : pageSize;
1070
+ const free = vmstat.match(/Pages free:\s+(\d+)/);
1071
+ const inactive = vmstat.match(/Pages inactive:\s+(\d+)/);
1072
+ const speculative = vmstat.match(/Pages speculative:\s+(\d+)/);
1073
+ const freePages = free ? parseInt(free[1], 10) : 0;
1074
+ const inactivePages = inactive ? parseInt(inactive[1], 10) : 0;
1075
+ const speculativePages = speculative ? parseInt(speculative[1], 10) : 0;
1076
+ return (freePages + inactivePages + speculativePages) * actualPageSize / (1024 * 1024 * 1024);
1077
+ } catch {
1078
+ return os4.freemem() / (1024 * 1024 * 1024);
1079
+ }
967
1080
  }
968
- if (process.env.DATABASE_URL) {
969
- return _adapterClient;
1081
+ return os4.freemem() / (1024 * 1024 * 1024);
1082
+ }
1083
+ function spawnDaemon() {
1084
+ const freeGB = getAvailableMemoryGB();
1085
+ const totalGB = os4.totalmem() / (1024 * 1024 * 1024);
1086
+ if (totalGB <= 8) {
1087
+ process.stderr.write(
1088
+ `[exed-client] SKIP: ${totalGB.toFixed(0)}GB system \u2014 embedding daemon disabled. Using keyword search only. Minimum 16GB recommended for vector search.
1089
+ `
1090
+ );
1091
+ return;
970
1092
  }
971
- if (process.env.EXE_IS_DAEMON === "1") {
972
- return _resilientClient;
1093
+ if (totalGB <= 16 && freeGB < 2) {
1094
+ process.stderr.write(
1095
+ `[exed-client] SKIP: low memory (${freeGB.toFixed(1)}GB available / ${totalGB.toFixed(0)}GB total). Embedding daemon not started \u2014 using keyword search only.
1096
+ `
1097
+ );
1098
+ return;
973
1099
  }
974
- if (_daemonClient && _daemonClient._isDaemonActive()) {
975
- return _daemonClient;
1100
+ const pkgRoot = findPackageRoot();
1101
+ if (!pkgRoot) {
1102
+ process.stderr.write("[exed-client] WARN: cannot find package root\n");
1103
+ return;
976
1104
  }
977
- return _resilientClient;
978
- }
979
- function getRawClient() {
980
- if (!_client) {
981
- throw new Error("Database client not initialized. Call initDatabase() first.");
1105
+ const daemonPath = path5.join(pkgRoot, "dist", "lib", "exe-daemon.js");
1106
+ if (!existsSync5(daemonPath)) {
1107
+ process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
1108
+ `);
1109
+ return;
982
1110
  }
983
- return _client;
984
- }
985
- async function ensureSchema() {
986
- const client = getRawClient();
987
- await client.execute("PRAGMA journal_mode = WAL");
988
- await client.execute("PRAGMA busy_timeout = 30000");
989
- await client.execute("PRAGMA wal_autocheckpoint = 1000");
1111
+ const resolvedPath = daemonPath;
1112
+ const daemonToken = ensureDaemonToken(process.env[DAEMON_TOKEN_ENV] ?? null);
1113
+ process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
1114
+ `);
1115
+ const logPath = path5.join(path5.dirname(SOCKET_PATH), "exed.log");
1116
+ let stderrFd = "ignore";
990
1117
  try {
991
- await client.execute("PRAGMA libsql_vector_search_ef = 128");
1118
+ stderrFd = openSync(logPath, "a");
992
1119
  } catch {
993
1120
  }
994
- await client.executeMultiple(`
995
- CREATE TABLE IF NOT EXISTS memories (
996
- id TEXT PRIMARY KEY,
997
- agent_id TEXT NOT NULL,
998
- agent_role TEXT NOT NULL,
999
- session_id TEXT NOT NULL,
1000
- timestamp TEXT NOT NULL,
1001
- tool_name TEXT NOT NULL,
1002
- project_name TEXT NOT NULL,
1003
- has_error INTEGER NOT NULL DEFAULT 0,
1004
- raw_text TEXT NOT NULL,
1005
- vector F32_BLOB(1024),
1006
- version INTEGER NOT NULL DEFAULT 0
1007
- );
1008
-
1009
- CREATE INDEX IF NOT EXISTS idx_memories_agent
1010
- ON memories(agent_id);
1011
-
1012
- CREATE INDEX IF NOT EXISTS idx_memories_timestamp
1013
- ON memories(timestamp);
1014
-
1015
- CREATE INDEX IF NOT EXISTS idx_memories_session
1016
- ON memories(session_id);
1017
-
1018
- CREATE INDEX IF NOT EXISTS idx_memories_project
1019
- ON memories(project_name);
1020
-
1021
- CREATE INDEX IF NOT EXISTS idx_memories_tool
1022
- ON memories(tool_name);
1023
-
1024
- CREATE INDEX IF NOT EXISTS idx_memories_version
1025
- ON memories(version);
1026
-
1027
- CREATE INDEX IF NOT EXISTS idx_memories_agent_project
1028
- ON memories(agent_id, project_name);
1029
- `);
1030
- await client.executeMultiple(`
1031
- CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
1032
- raw_text,
1033
- content='memories',
1034
- content_rowid='rowid'
1035
- );
1036
-
1037
- CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
1038
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1039
- END;
1040
-
1041
- CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
1042
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1043
- END;
1044
-
1045
- CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
1046
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1047
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1048
- END;
1049
- `);
1050
- await client.executeMultiple(`
1051
- CREATE TABLE IF NOT EXISTS sync_meta (
1052
- key TEXT PRIMARY KEY,
1053
- value TEXT NOT NULL
1054
- );
1055
- `);
1056
- await client.executeMultiple(`
1057
- CREATE TABLE IF NOT EXISTS tasks (
1058
- id TEXT PRIMARY KEY,
1059
- title TEXT NOT NULL,
1060
- assigned_to TEXT NOT NULL,
1061
- assigned_by TEXT NOT NULL,
1062
- project_name TEXT NOT NULL,
1063
- priority TEXT NOT NULL DEFAULT 'p1',
1064
- status TEXT NOT NULL DEFAULT 'open',
1065
- task_file TEXT,
1066
- created_at TEXT NOT NULL,
1067
- updated_at TEXT NOT NULL
1068
- );
1069
-
1070
- CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
1071
- ON tasks(assigned_to, status);
1072
- `);
1073
- await client.executeMultiple(`
1074
- CREATE TABLE IF NOT EXISTS behaviors (
1075
- id TEXT PRIMARY KEY,
1076
- agent_id TEXT NOT NULL,
1077
- project_name TEXT,
1078
- domain TEXT,
1079
- content TEXT NOT NULL,
1080
- active INTEGER NOT NULL DEFAULT 1,
1081
- created_at TEXT NOT NULL,
1082
- updated_at TEXT NOT NULL
1083
- );
1084
-
1085
- CREATE INDEX IF NOT EXISTS idx_behaviors_agent
1086
- ON behaviors(agent_id, active);
1087
- `);
1088
- try {
1089
- const coordinatorName = getCoordinatorName();
1090
- const existing = await client.execute({
1091
- sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = ?",
1092
- args: [coordinatorName]
1093
- });
1094
- if (Number(existing.rows[0]?.cnt) === 0) {
1095
- const seededAt = "2026-03-25T00:00:00Z";
1096
- for (const [domain, content] of [
1097
- ["workflow", `Don't ask "keep going?" \u2014 just keep executing phases/plans autonomously`],
1098
- ["tool-use", "Always use create_task MCP tool, never write .md files directly for task creation"],
1099
- ["workflow", "Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission"]
1100
- ]) {
1101
- await client.execute({
1102
- sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
1103
- VALUES (hex(randomblob(16)), ?, NULL, ?, ?, 1, ?, ?)`,
1104
- args: [coordinatorName, domain, content, seededAt, seededAt]
1105
- });
1106
- }
1121
+ const heapCapMB = totalGB <= 8 ? 256 : 512;
1122
+ const nodeArgs = [`--max-old-space-size=${heapCapMB}`, resolvedPath];
1123
+ const child = spawn(process.execPath, nodeArgs, {
1124
+ detached: true,
1125
+ stdio: ["ignore", "ignore", stderrFd],
1126
+ env: {
1127
+ ...process.env,
1128
+ TMUX: void 0,
1129
+ // Daemon is global — must not inherit session scope
1130
+ TMUX_PANE: void 0,
1131
+ // Prevents resolveExeSession() from scoping to one session
1132
+ EXE_DAEMON_SOCK: SOCKET_PATH,
1133
+ EXE_DAEMON_PID: PID_PATH,
1134
+ [DAEMON_TOKEN_ENV]: daemonToken
1135
+ }
1136
+ });
1137
+ child.unref();
1138
+ if (typeof stderrFd === "number") {
1139
+ try {
1140
+ closeSync(stderrFd);
1141
+ } catch {
1107
1142
  }
1108
- } catch {
1109
1143
  }
1144
+ }
1145
+ function acquireSpawnLock() {
1110
1146
  try {
1111
- await client.execute({
1112
- sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
1113
- args: []
1114
- });
1147
+ const fd = openSync(SPAWN_LOCK_PATH, "wx");
1148
+ closeSync(fd);
1149
+ return true;
1115
1150
  } catch {
1151
+ try {
1152
+ const stat = statSync(SPAWN_LOCK_PATH);
1153
+ if (Date.now() - stat.mtimeMs > SPAWN_LOCK_STALE_MS) {
1154
+ try {
1155
+ unlinkSync2(SPAWN_LOCK_PATH);
1156
+ } catch {
1157
+ }
1158
+ try {
1159
+ const fd = openSync(SPAWN_LOCK_PATH, "wx");
1160
+ closeSync(fd);
1161
+ return true;
1162
+ } catch {
1163
+ }
1164
+ }
1165
+ } catch {
1166
+ }
1167
+ return false;
1116
1168
  }
1169
+ }
1170
+ function releaseSpawnLock() {
1117
1171
  try {
1118
- await client.execute({
1119
- sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
1120
- args: []
1121
- });
1172
+ unlinkSync2(SPAWN_LOCK_PATH);
1173
+ } catch {
1174
+ }
1175
+ }
1176
+ function connectToSocket() {
1177
+ return new Promise((resolve) => {
1178
+ if (_socket && _connected) {
1179
+ resolve(true);
1180
+ return;
1181
+ }
1182
+ const socket = net.createConnection({ path: SOCKET_PATH });
1183
+ const connectTimeout = setTimeout(() => {
1184
+ socket.destroy();
1185
+ resolve(false);
1186
+ }, 2e3);
1187
+ socket.on("connect", () => {
1188
+ clearTimeout(connectTimeout);
1189
+ _socket = socket;
1190
+ _connected = true;
1191
+ _buffer = "";
1192
+ socket.on("data", handleData);
1193
+ socket.on("close", () => {
1194
+ _connected = false;
1195
+ _socket = null;
1196
+ for (const [id, entry] of _pending) {
1197
+ clearTimeout(entry.timer);
1198
+ _pending.delete(id);
1199
+ entry.resolve({ error: "Connection closed" });
1200
+ }
1201
+ });
1202
+ socket.on("error", () => {
1203
+ _connected = false;
1204
+ _socket = null;
1205
+ });
1206
+ resolve(true);
1207
+ });
1208
+ socket.on("error", () => {
1209
+ clearTimeout(connectTimeout);
1210
+ resolve(false);
1211
+ });
1212
+ });
1213
+ }
1214
+ async function connectEmbedDaemon() {
1215
+ if (_socket && _connected) return true;
1216
+ if (await connectToSocket()) return true;
1217
+ if (acquireSpawnLock()) {
1218
+ try {
1219
+ cleanupStaleFiles();
1220
+ spawnDaemon();
1221
+ } finally {
1222
+ releaseSpawnLock();
1223
+ }
1224
+ }
1225
+ const start = Date.now();
1226
+ let delay2 = 100;
1227
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1228
+ await new Promise((r) => setTimeout(r, delay2));
1229
+ if (await connectToSocket()) return true;
1230
+ delay2 = Math.min(delay2 * 2, 3e3);
1231
+ }
1232
+ return false;
1233
+ }
1234
+ function sendRequest(texts, priority) {
1235
+ return sendDaemonRequest({ texts, priority });
1236
+ }
1237
+ function sendDaemonRequest(payload, timeoutMs = REQUEST_TIMEOUT_MS) {
1238
+ return new Promise((resolve) => {
1239
+ if (!_socket || !_connected) {
1240
+ resolve({ error: "Not connected" });
1241
+ return;
1242
+ }
1243
+ const id = randomUUID();
1244
+ const token = process.env[DAEMON_TOKEN_ENV] ?? readDaemonToken();
1245
+ const timer = setTimeout(() => {
1246
+ _pending.delete(id);
1247
+ resolve({ error: "Request timeout" });
1248
+ }, timeoutMs);
1249
+ _pending.set(id, { resolve, timer });
1250
+ try {
1251
+ _socket.write(JSON.stringify({ id, token, ...payload }) + "\n");
1252
+ } catch {
1253
+ clearTimeout(timer);
1254
+ _pending.delete(id);
1255
+ resolve({ error: "Write failed" });
1256
+ }
1257
+ });
1258
+ }
1259
+ async function pingDaemon() {
1260
+ if (!_socket || !_connected) return null;
1261
+ const response = await sendDaemonRequest({ type: "health" }, 5e3);
1262
+ if (response.health) {
1263
+ return response.health;
1264
+ }
1265
+ return null;
1266
+ }
1267
+ function killAndRespawnDaemon() {
1268
+ if (!acquireSpawnLock()) {
1269
+ process.stderr.write("[exed-client] Another process is already restarting daemon \u2014 skipping\n");
1270
+ if (_socket) {
1271
+ _socket.destroy();
1272
+ _socket = null;
1273
+ }
1274
+ _connected = false;
1275
+ _buffer = "";
1276
+ return;
1277
+ }
1278
+ try {
1279
+ process.stderr.write("[exed-client] Killing daemon for restart...\n");
1280
+ if (existsSync5(PID_PATH)) {
1281
+ try {
1282
+ const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
1283
+ if (pid > 0) {
1284
+ try {
1285
+ process.kill(pid, "SIGKILL");
1286
+ } catch {
1287
+ }
1288
+ }
1289
+ } catch {
1290
+ }
1291
+ }
1292
+ if (_socket) {
1293
+ _socket.destroy();
1294
+ _socket = null;
1295
+ }
1296
+ _connected = false;
1297
+ _buffer = "";
1298
+ try {
1299
+ unlinkSync2(PID_PATH);
1300
+ } catch {
1301
+ }
1302
+ try {
1303
+ unlinkSync2(SOCKET_PATH);
1304
+ } catch {
1305
+ }
1306
+ spawnDaemon();
1307
+ } finally {
1308
+ releaseSpawnLock();
1309
+ }
1310
+ }
1311
+ function isDaemonTooYoung() {
1312
+ try {
1313
+ const stat = statSync(PID_PATH);
1314
+ return Date.now() - stat.mtimeMs < MIN_DAEMON_AGE_MS;
1315
+ } catch {
1316
+ return false;
1317
+ }
1318
+ }
1319
+ async function retryThenRestart(doRequest, label) {
1320
+ const result = await doRequest();
1321
+ if (!result.error) {
1322
+ _consecutiveFailures = 0;
1323
+ return result;
1324
+ }
1325
+ _consecutiveFailures++;
1326
+ for (let i = 0; i < MAX_RETRIES_BEFORE_RESTART; i++) {
1327
+ const delayMs = RETRY_DELAYS_MS[i] ?? 5e3;
1328
+ process.stderr.write(`[exed-client] ${label} failed (${result.error}), retry ${i + 1}/${MAX_RETRIES_BEFORE_RESTART} in ${delayMs}ms
1329
+ `);
1330
+ await new Promise((r) => setTimeout(r, delayMs));
1331
+ if (!_connected) {
1332
+ if (!await connectToSocket()) continue;
1333
+ }
1334
+ const retry = await doRequest();
1335
+ if (!retry.error) {
1336
+ _consecutiveFailures = 0;
1337
+ return retry;
1338
+ }
1339
+ _consecutiveFailures++;
1340
+ }
1341
+ if (isDaemonTooYoung()) {
1342
+ process.stderr.write(`[exed-client] ${label}: daemon too young (< ${MIN_DAEMON_AGE_MS / 1e3}s) \u2014 skipping restart
1343
+ `);
1344
+ return { error: result.error };
1345
+ }
1346
+ process.stderr.write(`[exed-client] ${label}: ${_consecutiveFailures} consecutive failures \u2014 restarting daemon
1347
+ `);
1348
+ killAndRespawnDaemon();
1349
+ const start = Date.now();
1350
+ let delay2 = 200;
1351
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1352
+ await new Promise((r) => setTimeout(r, delay2));
1353
+ if (await connectToSocket()) break;
1354
+ delay2 = Math.min(delay2 * 2, 3e3);
1355
+ }
1356
+ if (!_connected) return { error: "Daemon restart failed" };
1357
+ const final = await doRequest();
1358
+ if (!final.error) _consecutiveFailures = 0;
1359
+ return final;
1360
+ }
1361
+ async function embedViaClient(text, priority = "high") {
1362
+ if (!_connected && !await connectEmbedDaemon()) return null;
1363
+ _requestCount++;
1364
+ if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
1365
+ const health = await pingDaemon();
1366
+ if (!health && !isDaemonTooYoung()) {
1367
+ process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
1368
+ `);
1369
+ killAndRespawnDaemon();
1370
+ const start = Date.now();
1371
+ let d = 200;
1372
+ while (Date.now() - start < CONNECT_TIMEOUT_MS) {
1373
+ await new Promise((r) => setTimeout(r, d));
1374
+ if (await connectToSocket()) break;
1375
+ d = Math.min(d * 2, 3e3);
1376
+ }
1377
+ if (!_connected) return null;
1378
+ }
1379
+ }
1380
+ const result = await retryThenRestart(
1381
+ () => sendRequest([text], priority),
1382
+ "Embed"
1383
+ );
1384
+ return !result.error && result.vectors?.[0] ? result.vectors[0] : null;
1385
+ }
1386
+ async function embedBatchViaClient(texts, priority = "high") {
1387
+ if (!_connected && !await connectEmbedDaemon()) return null;
1388
+ _requestCount++;
1389
+ const result = await retryThenRestart(
1390
+ () => sendRequest(texts, priority),
1391
+ "Batch embed"
1392
+ );
1393
+ return !result.error && result.vectors ? result.vectors : null;
1394
+ }
1395
+ function disconnectClient() {
1396
+ if (_socket) {
1397
+ _socket.destroy();
1398
+ _socket = null;
1399
+ }
1400
+ _connected = false;
1401
+ _buffer = "";
1402
+ for (const [id, entry] of _pending) {
1403
+ clearTimeout(entry.timer);
1404
+ _pending.delete(id);
1405
+ entry.resolve({ error: "Client disconnected" });
1406
+ }
1407
+ }
1408
+ function isClientConnected() {
1409
+ return _connected;
1410
+ }
1411
+ function sendIngestRequest(payload) {
1412
+ if (!_socket || !_connected) return false;
1413
+ try {
1414
+ const id = randomUUID();
1415
+ const token = process.env[DAEMON_TOKEN_ENV] ?? readDaemonToken();
1416
+ _socket.write(JSON.stringify({ id, token, type: "ingest", ...payload }) + "\n");
1417
+ return true;
1418
+ } catch {
1419
+ return false;
1420
+ }
1421
+ }
1422
+ 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;
1423
+ var init_exe_daemon_client = __esm({
1424
+ "src/lib/exe-daemon-client.ts"() {
1425
+ "use strict";
1426
+ init_config();
1427
+ init_daemon_auth();
1428
+ SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path5.join(EXE_AI_DIR, "exed.sock");
1429
+ PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path5.join(EXE_AI_DIR, "exed.pid");
1430
+ SPAWN_LOCK_PATH = path5.join(EXE_AI_DIR, "exed-spawn.lock");
1431
+ SPAWN_LOCK_STALE_MS = 3e4;
1432
+ CONNECT_TIMEOUT_MS = 15e3;
1433
+ REQUEST_TIMEOUT_MS = 3e4;
1434
+ DAEMON_TOKEN_ENV = "EXE_DAEMON_TOKEN";
1435
+ _socket = null;
1436
+ _connected = false;
1437
+ _buffer = "";
1438
+ _requestCount = 0;
1439
+ _consecutiveFailures = 0;
1440
+ HEALTH_CHECK_INTERVAL = 100;
1441
+ MAX_RETRIES_BEFORE_RESTART = 3;
1442
+ RETRY_DELAYS_MS = [1e3, 3e3, 5e3];
1443
+ MIN_DAEMON_AGE_MS = 3e4;
1444
+ _pending = /* @__PURE__ */ new Map();
1445
+ MAX_BUFFER = 1e7;
1446
+ }
1447
+ });
1448
+
1449
+ // src/lib/daemon-protocol.ts
1450
+ var daemon_protocol_exports = {};
1451
+ __export(daemon_protocol_exports, {
1452
+ deserializeArgs: () => deserializeArgs,
1453
+ deserializeResultSet: () => deserializeResultSet,
1454
+ deserializeValue: () => deserializeValue,
1455
+ serializeArgs: () => serializeArgs,
1456
+ serializeResultSet: () => serializeResultSet,
1457
+ serializeValue: () => serializeValue
1458
+ });
1459
+ function serializeValue(v) {
1460
+ if (v === null || v === void 0) return null;
1461
+ if (typeof v === "bigint") return Number(v);
1462
+ if (typeof v === "boolean") return v ? 1 : 0;
1463
+ if (v instanceof Uint8Array) {
1464
+ return { __blob: Buffer.from(v).toString("base64") };
1465
+ }
1466
+ if (ArrayBuffer.isView(v)) {
1467
+ return { __blob: Buffer.from(v.buffer, v.byteOffset, v.byteLength).toString("base64") };
1468
+ }
1469
+ if (v instanceof ArrayBuffer) {
1470
+ return { __blob: Buffer.from(v).toString("base64") };
1471
+ }
1472
+ if (typeof v === "string" || typeof v === "number") return v;
1473
+ return String(v);
1474
+ }
1475
+ function deserializeValue(v) {
1476
+ if (v === null) return null;
1477
+ if (typeof v === "object" && v !== null && "__blob" in v) {
1478
+ const buf = Buffer.from(v.__blob, "base64");
1479
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
1480
+ }
1481
+ return v;
1482
+ }
1483
+ function serializeArgs(args) {
1484
+ return args.map(serializeValue);
1485
+ }
1486
+ function deserializeArgs(args) {
1487
+ return args.map(deserializeValue);
1488
+ }
1489
+ function serializeResultSet(rs) {
1490
+ const rows = [];
1491
+ for (const row of rs.rows) {
1492
+ const obj = {};
1493
+ for (let i = 0; i < rs.columns.length; i++) {
1494
+ const col = rs.columns[i];
1495
+ if (col !== void 0) {
1496
+ obj[col] = serializeValue(row[i]);
1497
+ }
1498
+ }
1499
+ rows.push(obj);
1500
+ }
1501
+ return {
1502
+ columns: [...rs.columns],
1503
+ columnTypes: [...rs.columnTypes ?? []],
1504
+ rows,
1505
+ rowsAffected: typeof rs.rowsAffected === "bigint" ? Number(rs.rowsAffected) : rs.rowsAffected ?? 0,
1506
+ lastInsertRowid: rs.lastInsertRowid != null ? typeof rs.lastInsertRowid === "bigint" ? Number(rs.lastInsertRowid) : rs.lastInsertRowid : null
1507
+ };
1508
+ }
1509
+ function deserializeResultSet(srs) {
1510
+ const rows = srs.rows.map((obj) => {
1511
+ const values = srs.columns.map(
1512
+ (col) => deserializeValue(obj[col] ?? null)
1513
+ );
1514
+ const row = values;
1515
+ for (let i = 0; i < srs.columns.length; i++) {
1516
+ const col = srs.columns[i];
1517
+ if (col !== void 0) {
1518
+ row[col] = values[i] ?? null;
1519
+ }
1520
+ }
1521
+ Object.defineProperty(row, "length", {
1522
+ value: values.length,
1523
+ enumerable: false
1524
+ });
1525
+ return row;
1526
+ });
1527
+ return {
1528
+ columns: srs.columns,
1529
+ columnTypes: srs.columnTypes ?? [],
1530
+ rows,
1531
+ rowsAffected: srs.rowsAffected,
1532
+ lastInsertRowid: srs.lastInsertRowid != null ? BigInt(srs.lastInsertRowid) : void 0,
1533
+ toJSON: () => ({
1534
+ columns: srs.columns,
1535
+ columnTypes: srs.columnTypes ?? [],
1536
+ rows: srs.rows,
1537
+ rowsAffected: srs.rowsAffected,
1538
+ lastInsertRowid: srs.lastInsertRowid
1539
+ })
1540
+ };
1541
+ }
1542
+ var init_daemon_protocol = __esm({
1543
+ "src/lib/daemon-protocol.ts"() {
1544
+ "use strict";
1545
+ }
1546
+ });
1547
+
1548
+ // src/lib/db-daemon-client.ts
1549
+ var db_daemon_client_exports = {};
1550
+ __export(db_daemon_client_exports, {
1551
+ createDaemonDbClient: () => createDaemonDbClient,
1552
+ initDaemonDbClient: () => initDaemonDbClient
1553
+ });
1554
+ function normalizeStatement2(stmt) {
1555
+ if (typeof stmt === "string") {
1556
+ return { sql: stmt, args: [] };
1557
+ }
1558
+ const sql = stmt.sql;
1559
+ let args = [];
1560
+ if (Array.isArray(stmt.args)) {
1561
+ args = stmt.args.map((v) => serializeValue(v));
1562
+ } else if (stmt.args && typeof stmt.args === "object") {
1563
+ const named = {};
1564
+ for (const [key, val] of Object.entries(stmt.args)) {
1565
+ named[key] = serializeValue(val);
1566
+ }
1567
+ return { sql, args: named };
1568
+ }
1569
+ return { sql, args };
1570
+ }
1571
+ function createDaemonDbClient(fallbackClient) {
1572
+ let _useDaemon = false;
1573
+ const client = {
1574
+ async execute(stmt) {
1575
+ if (!_useDaemon || !isClientConnected()) {
1576
+ return fallbackClient.execute(stmt);
1577
+ }
1578
+ const { sql, args } = normalizeStatement2(stmt);
1579
+ const response = await sendDaemonRequest({
1580
+ type: "db-execute",
1581
+ sql,
1582
+ args
1583
+ });
1584
+ if (response.error) {
1585
+ const errMsg = String(response.error);
1586
+ if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
1587
+ process.stderr.write(`[db-daemon] Transport error (${errMsg}), falling back to direct
1588
+ `);
1589
+ return fallbackClient.execute(stmt);
1590
+ }
1591
+ throw new Error(errMsg);
1592
+ }
1593
+ if (response.db) {
1594
+ return deserializeResultSet(response.db);
1595
+ }
1596
+ process.stderr.write("[db-daemon] Unexpected response shape, falling back to direct\n");
1597
+ return fallbackClient.execute(stmt);
1598
+ },
1599
+ async batch(stmts, mode) {
1600
+ if (!_useDaemon || !isClientConnected()) {
1601
+ return fallbackClient.batch(stmts, mode);
1602
+ }
1603
+ const statements = stmts.map(normalizeStatement2);
1604
+ const response = await sendDaemonRequest({
1605
+ type: "db-batch",
1606
+ statements,
1607
+ mode: mode ?? "deferred"
1608
+ });
1609
+ if (response.error) {
1610
+ const errMsg = String(response.error);
1611
+ if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
1612
+ process.stderr.write(`[db-daemon] Batch transport error (${errMsg}), falling back to direct
1613
+ `);
1614
+ return fallbackClient.batch(stmts, mode);
1615
+ }
1616
+ throw new Error(errMsg);
1617
+ }
1618
+ const batchResults = response["db-batch"];
1619
+ if (batchResults) {
1620
+ return batchResults.map(deserializeResultSet);
1621
+ }
1622
+ process.stderr.write("[db-daemon] Unexpected batch response shape, falling back to direct\n");
1623
+ return fallbackClient.batch(stmts, mode);
1624
+ },
1625
+ // Transaction support — delegate to fallback (transactions need direct connection)
1626
+ async transaction(mode) {
1627
+ return fallbackClient.transaction(mode);
1628
+ },
1629
+ // executeMultiple — delegate to fallback (used only for schema migrations)
1630
+ async executeMultiple(sql) {
1631
+ return fallbackClient.executeMultiple(sql);
1632
+ },
1633
+ // migrate — delegate to fallback
1634
+ async migrate(stmts) {
1635
+ return fallbackClient.migrate(stmts);
1636
+ },
1637
+ // Sync mode — delegate to fallback
1638
+ sync() {
1639
+ return fallbackClient.sync();
1640
+ },
1641
+ close() {
1642
+ _useDaemon = false;
1643
+ },
1644
+ get closed() {
1645
+ return fallbackClient.closed;
1646
+ },
1647
+ get protocol() {
1648
+ return fallbackClient.protocol;
1649
+ }
1650
+ };
1651
+ return {
1652
+ ...client,
1653
+ /** Enable daemon routing (call after confirming daemon is connected) */
1654
+ _enableDaemon() {
1655
+ _useDaemon = true;
1656
+ },
1657
+ /** Check if daemon routing is active */
1658
+ _isDaemonActive() {
1659
+ return _useDaemon && isClientConnected();
1660
+ }
1661
+ };
1662
+ }
1663
+ async function initDaemonDbClient(fallbackClient) {
1664
+ if (process.env.EXE_IS_DAEMON === "1") return null;
1665
+ const connected = await connectEmbedDaemon();
1666
+ if (!connected) {
1667
+ process.stderr.write("[db-daemon] Daemon unavailable \u2014 using direct SQLite\n");
1668
+ return null;
1669
+ }
1670
+ const client = createDaemonDbClient(fallbackClient);
1671
+ client._enableDaemon();
1672
+ process.stderr.write("[db-daemon] DB routing through daemon (single-writer)\n");
1673
+ return client;
1674
+ }
1675
+ var init_db_daemon_client = __esm({
1676
+ "src/lib/db-daemon-client.ts"() {
1677
+ "use strict";
1678
+ init_exe_daemon_client();
1679
+ init_daemon_protocol();
1680
+ }
1681
+ });
1682
+
1683
+ // src/lib/database.ts
1684
+ var database_exports = {};
1685
+ __export(database_exports, {
1686
+ disposeDatabase: () => disposeDatabase,
1687
+ disposeTurso: () => disposeTurso,
1688
+ ensureSchema: () => ensureSchema,
1689
+ getClient: () => getClient,
1690
+ getRawClient: () => getRawClient,
1691
+ initDaemonClient: () => initDaemonClient,
1692
+ initDatabase: () => initDatabase,
1693
+ initTurso: () => initTurso,
1694
+ isInitialized: () => isInitialized
1695
+ });
1696
+ import { createClient } from "@libsql/client";
1697
+ async function initDatabase(config) {
1698
+ if (_walCheckpointTimer) {
1699
+ clearInterval(_walCheckpointTimer);
1700
+ _walCheckpointTimer = null;
1701
+ }
1702
+ if (_daemonClient) {
1703
+ _daemonClient.close();
1704
+ _daemonClient = null;
1705
+ }
1706
+ if (_adapterClient && _adapterClient !== _resilientClient) {
1707
+ _adapterClient.close();
1708
+ }
1709
+ _adapterClient = null;
1710
+ if (_client) {
1711
+ _client.close();
1712
+ _client = null;
1713
+ _resilientClient = null;
1714
+ }
1715
+ const opts = {
1716
+ url: `file:${config.dbPath}`
1717
+ };
1718
+ if (config.encryptionKey) {
1719
+ opts.encryptionKey = config.encryptionKey;
1720
+ }
1721
+ _client = createClient(opts);
1722
+ _resilientClient = wrapWithRetry(_client);
1723
+ _adapterClient = _resilientClient;
1724
+ _client.execute("PRAGMA busy_timeout = 30000").catch(() => {
1725
+ });
1726
+ _client.execute("PRAGMA journal_mode = WAL").catch(() => {
1727
+ });
1728
+ if (_walCheckpointTimer) clearInterval(_walCheckpointTimer);
1729
+ _walCheckpointTimer = setInterval(() => {
1730
+ _client?.execute("PRAGMA wal_checkpoint(PASSIVE)").catch(() => {
1731
+ });
1732
+ }, 3e4);
1733
+ _walCheckpointTimer.unref();
1734
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
1735
+ _adapterClient = await createPrismaDbAdapter(_resilientClient);
1736
+ }
1737
+ }
1738
+ function isInitialized() {
1739
+ return _adapterClient !== null || _client !== null;
1740
+ }
1741
+ function getClient() {
1742
+ if (!_adapterClient) {
1743
+ throw new Error("Database client not initialized. Call initDatabase() first.");
1744
+ }
1745
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
1746
+ return _adapterClient;
1747
+ }
1748
+ if (process.env.EXE_IS_DAEMON === "1") {
1749
+ return _resilientClient;
1750
+ }
1751
+ if (_daemonClient && _daemonClient._isDaemonActive()) {
1752
+ return _daemonClient;
1753
+ }
1754
+ return _resilientClient;
1755
+ }
1756
+ async function initDaemonClient() {
1757
+ if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") return;
1758
+ if (process.env.EXE_IS_DAEMON === "1") return;
1759
+ if (process.env.VITEST) return;
1760
+ if (!_resilientClient) return;
1761
+ if (_daemonClient) return;
1762
+ try {
1763
+ const { initDaemonDbClient: initDaemonDbClient2 } = await Promise.resolve().then(() => (init_db_daemon_client(), db_daemon_client_exports));
1764
+ _daemonClient = await initDaemonDbClient2(_resilientClient);
1765
+ } catch (err) {
1766
+ process.stderr.write(
1767
+ `[database] Daemon client init failed (non-fatal): ${err instanceof Error ? err.message : String(err)}
1768
+ `
1769
+ );
1770
+ }
1771
+ }
1772
+ function getRawClient() {
1773
+ if (!_client) {
1774
+ throw new Error("Database client not initialized. Call initDatabase() first.");
1775
+ }
1776
+ return _client;
1777
+ }
1778
+ async function ensureSchema() {
1779
+ const client = getRawClient();
1780
+ await client.execute("PRAGMA journal_mode = WAL");
1781
+ await client.execute("PRAGMA busy_timeout = 30000");
1782
+ await client.execute("PRAGMA wal_autocheckpoint = 1000");
1783
+ try {
1784
+ await client.execute("PRAGMA libsql_vector_search_ef = 128");
1785
+ } catch {
1786
+ }
1787
+ await client.executeMultiple(`
1788
+ CREATE TABLE IF NOT EXISTS memories (
1789
+ id TEXT PRIMARY KEY,
1790
+ agent_id TEXT NOT NULL,
1791
+ agent_role TEXT NOT NULL,
1792
+ session_id TEXT NOT NULL,
1793
+ timestamp TEXT NOT NULL,
1794
+ tool_name TEXT NOT NULL,
1795
+ project_name TEXT NOT NULL,
1796
+ has_error INTEGER NOT NULL DEFAULT 0,
1797
+ raw_text TEXT NOT NULL,
1798
+ vector F32_BLOB(1024),
1799
+ version INTEGER NOT NULL DEFAULT 0
1800
+ );
1801
+
1802
+ CREATE INDEX IF NOT EXISTS idx_memories_agent
1803
+ ON memories(agent_id);
1804
+
1805
+ CREATE INDEX IF NOT EXISTS idx_memories_timestamp
1806
+ ON memories(timestamp);
1807
+
1808
+ CREATE INDEX IF NOT EXISTS idx_memories_session
1809
+ ON memories(session_id);
1810
+
1811
+ CREATE INDEX IF NOT EXISTS idx_memories_project
1812
+ ON memories(project_name);
1813
+
1814
+ CREATE INDEX IF NOT EXISTS idx_memories_tool
1815
+ ON memories(tool_name);
1816
+
1817
+ CREATE INDEX IF NOT EXISTS idx_memories_version
1818
+ ON memories(version);
1819
+
1820
+ CREATE INDEX IF NOT EXISTS idx_memories_agent_project
1821
+ ON memories(agent_id, project_name);
1822
+ `);
1823
+ await client.executeMultiple(`
1824
+ CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
1825
+ raw_text,
1826
+ content='memories',
1827
+ content_rowid='rowid'
1828
+ );
1829
+
1830
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
1831
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1832
+ END;
1833
+
1834
+ CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
1835
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1836
+ END;
1837
+
1838
+ CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
1839
+ INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1840
+ INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1841
+ END;
1842
+ `);
1843
+ await client.executeMultiple(`
1844
+ CREATE TABLE IF NOT EXISTS sync_meta (
1845
+ key TEXT PRIMARY KEY,
1846
+ value TEXT NOT NULL
1847
+ );
1848
+ `);
1849
+ await client.executeMultiple(`
1850
+ CREATE TABLE IF NOT EXISTS tasks (
1851
+ id TEXT PRIMARY KEY,
1852
+ title TEXT NOT NULL,
1853
+ assigned_to TEXT NOT NULL,
1854
+ assigned_by TEXT NOT NULL,
1855
+ project_name TEXT NOT NULL,
1856
+ priority TEXT NOT NULL DEFAULT 'p1',
1857
+ status TEXT NOT NULL DEFAULT 'open',
1858
+ task_file TEXT,
1859
+ created_at TEXT NOT NULL,
1860
+ updated_at TEXT NOT NULL
1861
+ );
1862
+
1863
+ CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
1864
+ ON tasks(assigned_to, status);
1865
+ `);
1866
+ await client.executeMultiple(`
1867
+ CREATE TABLE IF NOT EXISTS behaviors (
1868
+ id TEXT PRIMARY KEY,
1869
+ agent_id TEXT NOT NULL,
1870
+ project_name TEXT,
1871
+ domain TEXT,
1872
+ content TEXT NOT NULL,
1873
+ active INTEGER NOT NULL DEFAULT 1,
1874
+ created_at TEXT NOT NULL,
1875
+ updated_at TEXT NOT NULL
1876
+ );
1877
+
1878
+ CREATE INDEX IF NOT EXISTS idx_behaviors_agent
1879
+ ON behaviors(agent_id, active);
1880
+ `);
1881
+ try {
1882
+ const coordinatorName = getCoordinatorName();
1883
+ const existing = await client.execute({
1884
+ sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = ?",
1885
+ args: [coordinatorName]
1886
+ });
1887
+ if (Number(existing.rows[0]?.cnt) === 0) {
1888
+ const seededAt = "2026-03-25T00:00:00Z";
1889
+ for (const [domain, content] of [
1890
+ ["workflow", `Don't ask "keep going?" \u2014 just keep executing phases/plans autonomously`],
1891
+ ["tool-use", "Always use create_task MCP tool, never write .md files directly for task creation"],
1892
+ ["workflow", "Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission"]
1893
+ ]) {
1894
+ await client.execute({
1895
+ sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
1896
+ VALUES (hex(randomblob(16)), ?, NULL, ?, ?, 1, ?, ?)`,
1897
+ args: [coordinatorName, domain, content, seededAt, seededAt]
1898
+ });
1899
+ }
1900
+ }
1901
+ } catch {
1902
+ }
1903
+ try {
1904
+ await client.execute({
1905
+ sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
1906
+ args: []
1907
+ });
1908
+ } catch {
1909
+ }
1910
+ try {
1911
+ await client.execute({
1912
+ sql: `ALTER TABLE behaviors ADD COLUMN vector F32_BLOB(${EMBEDDING_DIM})`,
1913
+ args: []
1914
+ });
1915
+ } catch {
1916
+ }
1917
+ try {
1918
+ await client.execute({
1919
+ sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
1920
+ args: []
1921
+ });
1122
1922
  } catch {
1123
1923
  }
1124
1924
  try {
@@ -1946,31 +2746,109 @@ async function ensureSchema() {
1946
2746
  "ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
1947
2747
  ]) {
1948
2748
  try {
1949
- await client.execute(col);
2749
+ await client.execute(col);
2750
+ } catch {
2751
+ }
2752
+ }
2753
+ try {
2754
+ await client.execute({
2755
+ sql: `UPDATE tasks SET status = 'closed' WHERE status = 'done' AND result IS NOT NULL`,
2756
+ args: []
2757
+ });
2758
+ } catch {
2759
+ }
2760
+ }
2761
+ async function disposeDatabase() {
2762
+ if (_walCheckpointTimer) {
2763
+ clearInterval(_walCheckpointTimer);
2764
+ _walCheckpointTimer = null;
2765
+ }
2766
+ if (_daemonClient) {
2767
+ _daemonClient.close();
2768
+ _daemonClient = null;
2769
+ }
2770
+ if (_adapterClient && _adapterClient !== _resilientClient) {
2771
+ _adapterClient.close();
2772
+ }
2773
+ _adapterClient = null;
2774
+ if (_client) {
2775
+ _client.close();
2776
+ _client = null;
2777
+ _resilientClient = null;
2778
+ }
2779
+ }
2780
+ var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso, disposeTurso;
2781
+ var init_database = __esm({
2782
+ "src/lib/database.ts"() {
2783
+ "use strict";
2784
+ init_db_retry();
2785
+ init_employees();
2786
+ init_database_adapter();
2787
+ init_memory();
2788
+ _client = null;
2789
+ _resilientClient = null;
2790
+ _walCheckpointTimer = null;
2791
+ _daemonClient = null;
2792
+ _adapterClient = null;
2793
+ initTurso = initDatabase;
2794
+ disposeTurso = disposeDatabase;
2795
+ }
2796
+ });
2797
+
2798
+ // src/lib/keychain.ts
2799
+ import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
2800
+ import { existsSync as existsSync6 } from "fs";
2801
+ import path6 from "path";
2802
+ import os5 from "os";
2803
+ function getKeyDir() {
2804
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path6.join(os5.homedir(), ".exe-os");
2805
+ }
2806
+ function getKeyPath() {
2807
+ return path6.join(getKeyDir(), "master.key");
2808
+ }
2809
+ async function tryKeytar() {
2810
+ try {
2811
+ return await import("keytar");
2812
+ } catch {
2813
+ return null;
2814
+ }
2815
+ }
2816
+ async function getMasterKey() {
2817
+ const keytar = await tryKeytar();
2818
+ if (keytar) {
2819
+ try {
2820
+ const stored = await keytar.getPassword(SERVICE, ACCOUNT);
2821
+ if (stored) {
2822
+ return Buffer.from(stored, "base64");
2823
+ }
1950
2824
  } catch {
1951
2825
  }
1952
2826
  }
2827
+ const keyPath = getKeyPath();
2828
+ if (!existsSync6(keyPath)) {
2829
+ process.stderr.write(
2830
+ `[keychain] Key not found at ${keyPath} (HOME=${os5.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2831
+ `
2832
+ );
2833
+ return null;
2834
+ }
1953
2835
  try {
1954
- await client.execute({
1955
- sql: `UPDATE tasks SET status = 'closed' WHERE status = 'done' AND result IS NOT NULL`,
1956
- args: []
1957
- });
1958
- } catch {
2836
+ const content = await readFile3(keyPath, "utf-8");
2837
+ return Buffer.from(content.trim(), "base64");
2838
+ } catch (err) {
2839
+ process.stderr.write(
2840
+ `[keychain] Key read failed at ${keyPath}: ${err instanceof Error ? err.message : String(err)}
2841
+ `
2842
+ );
2843
+ return null;
1959
2844
  }
1960
2845
  }
1961
- var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
1962
- var init_database = __esm({
1963
- "src/lib/database.ts"() {
2846
+ var SERVICE, ACCOUNT;
2847
+ var init_keychain = __esm({
2848
+ "src/lib/keychain.ts"() {
1964
2849
  "use strict";
1965
- init_db_retry();
1966
- init_employees();
1967
- init_database_adapter();
1968
- _client = null;
1969
- _resilientClient = null;
1970
- _walCheckpointTimer = null;
1971
- _daemonClient = null;
1972
- _adapterClient = null;
1973
- initTurso = initDatabase;
2850
+ SERVICE = "exe-mem";
2851
+ ACCOUNT = "master-key";
1974
2852
  }
1975
2853
  });
1976
2854
 
@@ -2043,12 +2921,12 @@ __export(shard_manager_exports, {
2043
2921
  listShards: () => listShards,
2044
2922
  shardExists: () => shardExists
2045
2923
  });
2046
- import path5 from "path";
2047
- import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync } from "fs";
2924
+ import path7 from "path";
2925
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, readdirSync } from "fs";
2048
2926
  import { createClient as createClient2 } from "@libsql/client";
2049
2927
  function initShardManager(encryptionKey) {
2050
2928
  _encryptionKey = encryptionKey;
2051
- if (!existsSync5(SHARDS_DIR)) {
2929
+ if (!existsSync7(SHARDS_DIR)) {
2052
2930
  mkdirSync2(SHARDS_DIR, { recursive: true });
2053
2931
  }
2054
2932
  _shardingEnabled = true;
@@ -2078,7 +2956,7 @@ function getShardClient(projectName) {
2078
2956
  while (_shards.size >= MAX_OPEN_SHARDS) {
2079
2957
  evictLRU();
2080
2958
  }
2081
- const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
2959
+ const dbPath = path7.join(SHARDS_DIR, `${safeName}.db`);
2082
2960
  const client = createClient2({
2083
2961
  url: `file:${dbPath}`,
2084
2962
  encryptionKey: _encryptionKey
@@ -2089,10 +2967,10 @@ function getShardClient(projectName) {
2089
2967
  }
2090
2968
  function shardExists(projectName) {
2091
2969
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
2092
- return existsSync5(path5.join(SHARDS_DIR, `${safeName}.db`));
2970
+ return existsSync7(path7.join(SHARDS_DIR, `${safeName}.db`));
2093
2971
  }
2094
2972
  function listShards() {
2095
- if (!existsSync5(SHARDS_DIR)) return [];
2973
+ if (!existsSync7(SHARDS_DIR)) return [];
2096
2974
  return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
2097
2975
  }
2098
2976
  async function ensureShardSchema(client) {
@@ -2339,7 +3217,7 @@ var init_shard_manager = __esm({
2339
3217
  "src/lib/shard-manager.ts"() {
2340
3218
  "use strict";
2341
3219
  init_config();
2342
- SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
3220
+ SHARDS_DIR = path7.join(EXE_AI_DIR, "shards");
2343
3221
  SHARD_IDLE_MS = 5 * 60 * 1e3;
2344
3222
  MAX_OPEN_SHARDS = 10;
2345
3223
  EVICTION_INTERVAL_MS = 60 * 1e3;
@@ -2459,93 +3337,743 @@ var init_platform_procedures = __esm({
2459
3337
  domain: "architecture",
2460
3338
  priority: "p0",
2461
3339
  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."
3340
+ },
3341
+ // --- MCP is the ONLY data interface ---
3342
+ {
3343
+ title: "MCP disconnect \u2014 ask the user, never work around it",
3344
+ domain: "workflow",
3345
+ priority: "p0",
3346
+ 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."
3347
+ },
3348
+ // --- MCP Tool Catalog (Layer 0 — every agent knows what tools exist) ---
3349
+ {
3350
+ title: "MCP tools \u2014 memory and search",
3351
+ domain: "tool-use",
3352
+ priority: "p1",
3353
+ 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)."
3354
+ },
3355
+ {
3356
+ title: "MCP tools \u2014 task orchestration",
3357
+ domain: "tool-use",
3358
+ priority: "p1",
3359
+ 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."
3360
+ },
3361
+ {
3362
+ title: "MCP tools \u2014 knowledge graph (GraphRAG)",
3363
+ domain: "tool-use",
3364
+ priority: "p1",
3365
+ 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."
3366
+ },
3367
+ {
3368
+ title: "MCP tools \u2014 identity, behavior, and decisions",
3369
+ domain: "tool-use",
3370
+ priority: "p1",
3371
+ 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."
3372
+ },
3373
+ {
3374
+ title: "MCP tools \u2014 communication and messaging",
3375
+ domain: "tool-use",
3376
+ priority: "p1",
3377
+ 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.)."
3378
+ },
3379
+ {
3380
+ title: "MCP tools \u2014 wiki, documents, and content",
3381
+ domain: "tool-use",
3382
+ priority: "p1",
3383
+ 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."
3384
+ },
3385
+ {
3386
+ title: "MCP tools \u2014 system, operations, and admin",
3387
+ domain: "tool-use",
3388
+ priority: "p1",
3389
+ 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."
3390
+ },
3391
+ {
3392
+ title: "MCP tools \u2014 config, licensing, and team",
3393
+ domain: "tool-use",
3394
+ priority: "p1",
3395
+ 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."
3396
+ },
3397
+ {
3398
+ title: "MCP tools \u2014 advanced (triggers, skills, orchestration)",
3399
+ domain: "tool-use",
3400
+ priority: "p1",
3401
+ 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."
3402
+ }
3403
+ ];
3404
+ PLATFORM_PROCEDURE_TITLES = new Set(
3405
+ PLATFORM_PROCEDURES.map((p) => p.title)
3406
+ );
3407
+ }
3408
+ });
3409
+
3410
+ // src/lib/global-procedures.ts
3411
+ var global_procedures_exports = {};
3412
+ __export(global_procedures_exports, {
3413
+ deactivateGlobalProcedure: () => deactivateGlobalProcedure,
3414
+ getGlobalProceduresBlock: () => getGlobalProceduresBlock,
3415
+ loadGlobalProcedures: () => loadGlobalProcedures,
3416
+ storeGlobalProcedure: () => storeGlobalProcedure
3417
+ });
3418
+ import { randomUUID as randomUUID2 } from "crypto";
3419
+ async function loadGlobalProcedures() {
3420
+ const client = getClient();
3421
+ const result = await client.execute({
3422
+ sql: "SELECT * FROM global_procedures WHERE active = 1 ORDER BY priority ASC, created_at ASC",
3423
+ args: []
3424
+ });
3425
+ const allRows = result.rows;
3426
+ const customerOnly = allRows.filter((p) => !PLATFORM_PROCEDURE_TITLES.has(p.title));
3427
+ if (customerOnly.length > 0) {
3428
+ _customerCache = customerOnly.map((p) => `### ${p.title}
3429
+ ${p.content}`).join("\n\n");
3430
+ } else {
3431
+ _customerCache = "";
3432
+ }
3433
+ _cacheLoaded = true;
3434
+ return customerOnly;
3435
+ }
3436
+ function getGlobalProceduresBlock() {
3437
+ const sections = [];
3438
+ if (_platformCache) sections.push(_platformCache);
3439
+ if (_cacheLoaded && _customerCache) sections.push(_customerCache);
3440
+ if (sections.length === 0) return "";
3441
+ return `## Organization-Wide Procedures (MANDATORY \u2014 supersedes all other rules)
3442
+
3443
+ ${sections.join("\n\n")}
3444
+ `;
3445
+ }
3446
+ async function storeGlobalProcedure(input) {
3447
+ const id = randomUUID2();
3448
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3449
+ const client = getClient();
3450
+ await client.execute({
3451
+ sql: `INSERT INTO global_procedures (id, title, content, priority, domain, active, created_at, updated_at)
3452
+ VALUES (?, ?, ?, ?, ?, 1, ?, ?)`,
3453
+ args: [id, input.title, input.content, input.priority ?? "p0", input.domain ?? null, now, now]
3454
+ });
3455
+ await loadGlobalProcedures();
3456
+ return id;
3457
+ }
3458
+ async function deactivateGlobalProcedure(id) {
3459
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3460
+ const client = getClient();
3461
+ const result = await client.execute({
3462
+ sql: "UPDATE global_procedures SET active = 0, updated_at = ? WHERE id = ?",
3463
+ args: [now, id]
3464
+ });
3465
+ await loadGlobalProcedures();
3466
+ return result.rowsAffected > 0;
3467
+ }
3468
+ var _customerCache, _cacheLoaded, _platformCache;
3469
+ var init_global_procedures = __esm({
3470
+ "src/lib/global-procedures.ts"() {
3471
+ "use strict";
3472
+ init_database();
3473
+ init_platform_procedures();
3474
+ _customerCache = "";
3475
+ _cacheLoaded = false;
3476
+ _platformCache = PLATFORM_PROCEDURES.map((p) => `### ${p.title}
3477
+ ${p.content}`).join("\n\n");
3478
+ }
3479
+ });
3480
+
3481
+ // src/lib/store.ts
3482
+ var store_exports = {};
3483
+ __export(store_exports, {
3484
+ attachDocumentMetadata: () => attachDocumentMetadata,
3485
+ buildRawVisibilityFilter: () => buildRawVisibilityFilter,
3486
+ buildWikiScopeFilter: () => buildWikiScopeFilter,
3487
+ classifyTier: () => classifyTier,
3488
+ disposeStore: () => disposeStore,
3489
+ flushBatch: () => flushBatch,
3490
+ flushTier3: () => flushTier3,
3491
+ getMemoryCardinality: () => getMemoryCardinality,
3492
+ initStore: () => initStore,
3493
+ reserveVersions: () => reserveVersions,
3494
+ searchMemories: () => searchMemories,
3495
+ updateMemoryStatus: () => updateMemoryStatus,
3496
+ vectorToBlob: () => vectorToBlob,
3497
+ writeMemory: () => writeMemory
3498
+ });
3499
+ import { createHash } from "crypto";
3500
+ function isBusyError2(err) {
3501
+ if (err instanceof Error) {
3502
+ const msg = err.message.toLowerCase();
3503
+ return msg.includes("sqlite_busy") || msg.includes("database is locked");
3504
+ }
3505
+ return false;
3506
+ }
3507
+ async function retryOnBusy2(fn, label) {
3508
+ for (let attempt = 0; attempt <= INIT_MAX_RETRIES; attempt++) {
3509
+ try {
3510
+ return await fn();
3511
+ } catch (err) {
3512
+ if (!isBusyError2(err) || attempt === INIT_MAX_RETRIES) throw err;
3513
+ process.stderr.write(
3514
+ `[store] SQLITE_BUSY during ${label}, retry ${attempt + 1}/${INIT_MAX_RETRIES}
3515
+ `
3516
+ );
3517
+ await new Promise((r) => setTimeout(r, INIT_RETRY_DELAY_MS * (attempt + 1)));
3518
+ }
3519
+ }
3520
+ throw new Error("unreachable");
3521
+ }
3522
+ async function initStore(options) {
3523
+ if (_flushTimer !== null) {
3524
+ clearInterval(_flushTimer);
3525
+ _flushTimer = null;
3526
+ }
3527
+ _pendingRecords = [];
3528
+ _flushing = false;
3529
+ _batchSize = options?.batchSize ?? 20;
3530
+ _flushIntervalMs = options?.flushIntervalMs ?? 1e4;
3531
+ let dbPath = options?.dbPath;
3532
+ if (!dbPath) {
3533
+ const config = await loadConfig();
3534
+ dbPath = config.dbPath;
3535
+ }
3536
+ let masterKey = options?.masterKey ?? null;
3537
+ if (!masterKey) {
3538
+ masterKey = await getMasterKey();
3539
+ if (!masterKey) {
3540
+ throw new Error(
3541
+ "No encryption key found. Run /exe-setup to generate one."
3542
+ );
3543
+ }
3544
+ }
3545
+ const hexKey = masterKey.toString("hex");
3546
+ await initTurso({
3547
+ dbPath,
3548
+ encryptionKey: hexKey
3549
+ });
3550
+ await retryOnBusy2(() => ensureSchema(), "ensureSchema");
3551
+ try {
3552
+ const { initDaemonClient: initDaemonClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
3553
+ await initDaemonClient2();
3554
+ } catch {
3555
+ }
3556
+ if (!options?.lightweight) {
3557
+ try {
3558
+ const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
3559
+ initShardManager2(hexKey);
3560
+ } catch {
3561
+ }
3562
+ const client = getClient();
3563
+ const vResult = await retryOnBusy2(
3564
+ () => client.execute("SELECT MAX(version) as max_v FROM memories"),
3565
+ "version-query"
3566
+ );
3567
+ _nextVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
3568
+ try {
3569
+ const { loadGlobalProcedures: loadGlobalProcedures2 } = await Promise.resolve().then(() => (init_global_procedures(), global_procedures_exports));
3570
+ await loadGlobalProcedures2();
3571
+ } catch {
3572
+ }
3573
+ }
3574
+ }
3575
+ function classifyTier(record) {
3576
+ if (record.tool_name === "commit_to_long_term_memory" && (record.importance ?? 0) >= 8) return 1;
3577
+ if (["store_memory", "manual"].includes(record.tool_name ?? "") && (record.importance ?? 0) >= 5) return 2;
3578
+ return 3;
3579
+ }
3580
+ function inferFilePaths(record) {
3581
+ if (!["Read", "Write", "Edit"].includes(record.tool_name)) return null;
3582
+ const firstLine = record.raw_text.split("\n")[0] ?? "";
3583
+ const match = firstLine.match(/(\/[\w./-]+\.\w+)/);
3584
+ return match ? JSON.stringify([match[1]]) : null;
3585
+ }
3586
+ function inferCommitHash(record) {
3587
+ if (record.tool_name !== "Bash") return null;
3588
+ const match = record.raw_text.match(/\b([a-f0-9]{7,40})\b/);
3589
+ return match ? match[1] : null;
3590
+ }
3591
+ function inferLanguageType(record) {
3592
+ const text = record.raw_text;
3593
+ if (!text || text.length < 10) return null;
3594
+ const trimmed = text.trimStart();
3595
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) return "json";
3596
+ if (/\b(SELECT|INSERT|UPDATE|DELETE|CREATE TABLE|ALTER TABLE)\b/i.test(text)) return "sql";
3597
+ if (/\b(function |const |import |export |class |def |async |=>)\b/.test(text)) return "code";
3598
+ if (trimmed.startsWith("#") || trimmed.startsWith("*")) return "prose";
3599
+ return "mixed";
3600
+ }
3601
+ function inferDomain(record) {
3602
+ const proj = (record.project_name ?? "").toLowerCase();
3603
+ if (proj.includes("marketing") || proj.includes("content")) return "marketing";
3604
+ if (proj.includes("crm") || proj.includes("customer")) return "customer";
3605
+ return null;
3606
+ }
3607
+ async function writeMemory(record) {
3608
+ if (record.vector !== null && record.vector.length !== EMBEDDING_DIM) {
3609
+ throw new Error(
3610
+ `Expected ${EMBEDDING_DIM}-dim vector, got ${record.vector.length}`
3611
+ );
3612
+ }
3613
+ const contentHash = createHash("md5").update(record.raw_text).digest("hex");
3614
+ if (_pendingRecords.some((r) => r.content_hash === contentHash && r.agent_id === record.agent_id)) {
3615
+ return;
3616
+ }
3617
+ try {
3618
+ const client = getClient();
3619
+ const existing = await client.execute({
3620
+ sql: "SELECT id FROM memories WHERE content_hash = ? AND agent_id = ? LIMIT 1",
3621
+ args: [contentHash, record.agent_id]
3622
+ });
3623
+ if (existing.rows.length > 0) return;
3624
+ } catch {
3625
+ }
3626
+ const dbRow = {
3627
+ id: record.id,
3628
+ agent_id: record.agent_id,
3629
+ agent_role: record.agent_role,
3630
+ session_id: record.session_id,
3631
+ timestamp: record.timestamp,
3632
+ tool_name: record.tool_name,
3633
+ project_name: record.project_name,
3634
+ has_error: record.has_error ? 1 : 0,
3635
+ raw_text: record.raw_text,
3636
+ vector: record.vector,
3637
+ version: 0,
3638
+ // Placeholder — assigned atomically at flush time
3639
+ task_id: record.task_id ?? null,
3640
+ importance: record.importance ?? 5,
3641
+ status: record.status ?? "active",
3642
+ confidence: record.confidence ?? 0.7,
3643
+ last_accessed: record.last_accessed ?? record.timestamp,
3644
+ workspace_id: record.workspace_id ?? null,
3645
+ document_id: record.document_id ?? null,
3646
+ user_id: record.user_id ?? null,
3647
+ char_offset: record.char_offset ?? null,
3648
+ page_number: record.page_number ?? null,
3649
+ source_path: record.source_path ?? null,
3650
+ source_type: record.source_type ?? null,
3651
+ tier: record.tier ?? classifyTier(record),
3652
+ supersedes_id: record.supersedes_id ?? null,
3653
+ draft: record.draft ? 1 : 0,
3654
+ memory_type: record.memory_type ?? "raw",
3655
+ trajectory: record.trajectory ? JSON.stringify(record.trajectory) : null,
3656
+ content_hash: contentHash,
3657
+ intent: record.intent ?? null,
3658
+ outcome: record.outcome ?? null,
3659
+ domain: record.domain ?? inferDomain(record),
3660
+ referenced_entities: record.referenced_entities ?? null,
3661
+ retrieval_count: record.retrieval_count ?? 0,
3662
+ chain_position: record.chain_position ?? null,
3663
+ review_status: record.review_status ?? null,
3664
+ context_window_pct: record.context_window_pct ?? null,
3665
+ file_paths: record.file_paths ?? inferFilePaths(record),
3666
+ commit_hash: record.commit_hash ?? inferCommitHash(record),
3667
+ duration_ms: record.duration_ms ?? null,
3668
+ token_cost: record.token_cost ?? null,
3669
+ audience: record.audience ?? null,
3670
+ language_type: record.language_type ?? inferLanguageType(record),
3671
+ parent_memory_id: record.parent_memory_id ?? null
3672
+ };
3673
+ _pendingRecords.push(dbRow);
3674
+ orgBus.emit({
3675
+ type: "memory_stored",
3676
+ agentId: record.agent_id,
3677
+ project: record.project_name,
3678
+ timestamp: record.timestamp
3679
+ });
3680
+ const MAX_PENDING = 1e3;
3681
+ if (_pendingRecords.length > MAX_PENDING) {
3682
+ const dropped = _pendingRecords.length - MAX_PENDING;
3683
+ _pendingRecords = _pendingRecords.slice(-MAX_PENDING);
3684
+ console.warn(`[store] Dropped ${dropped} oldest pending records (overflow)`);
3685
+ }
3686
+ if (_flushTimer === null) {
3687
+ _flushTimer = setInterval(() => {
3688
+ void flushBatch();
3689
+ }, _flushIntervalMs);
3690
+ if (_flushTimer && typeof _flushTimer === "object" && "unref" in _flushTimer) {
3691
+ _flushTimer.unref();
3692
+ }
3693
+ }
3694
+ if (_pendingRecords.length >= _batchSize) {
3695
+ await flushBatch();
3696
+ }
3697
+ }
3698
+ async function flushBatch() {
3699
+ if (_flushing || _pendingRecords.length === 0) return 0;
3700
+ _flushing = true;
3701
+ try {
3702
+ const batch = _pendingRecords.slice(0);
3703
+ const client = getClient();
3704
+ const vResult = await client.execute("SELECT MAX(version) as max_v FROM memories");
3705
+ let baseVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
3706
+ for (const row of batch) {
3707
+ row.version = baseVersion++;
3708
+ }
3709
+ _nextVersion = baseVersion;
3710
+ const buildStmt = (row) => {
3711
+ const hasVector = row.vector !== null;
3712
+ const taskId = row.task_id ?? null;
3713
+ const importance = row.importance ?? 5;
3714
+ const status2 = row.status ?? "active";
3715
+ const confidence = row.confidence ?? 0.7;
3716
+ const lastAccessed = row.last_accessed ?? row.timestamp;
3717
+ const workspaceId = row.workspace_id ?? null;
3718
+ const documentId = row.document_id ?? null;
3719
+ const userId = row.user_id ?? null;
3720
+ const charOffset = row.char_offset ?? null;
3721
+ const pageNumber = row.page_number ?? null;
3722
+ const sourcePath = row.source_path ?? null;
3723
+ const sourceType = row.source_type ?? null;
3724
+ const tier = row.tier ?? 3;
3725
+ const supersedesId = row.supersedes_id ?? null;
3726
+ const draft = row.draft ? 1 : 0;
3727
+ const memoryType = row.memory_type ?? "raw";
3728
+ const trajectory = row.trajectory ?? null;
3729
+ const contentHash = row.content_hash ?? null;
3730
+ const intent = row.intent ?? null;
3731
+ const outcome = row.outcome ?? null;
3732
+ const domain = row.domain ?? null;
3733
+ const referencedEntities = row.referenced_entities ?? null;
3734
+ const retrievalCount = row.retrieval_count ?? 0;
3735
+ const chainPosition = row.chain_position ?? null;
3736
+ const reviewStatus = row.review_status ?? null;
3737
+ const contextWindowPct = row.context_window_pct ?? null;
3738
+ const filePaths = row.file_paths ?? null;
3739
+ const commitHash = row.commit_hash ?? null;
3740
+ const durationMs = row.duration_ms ?? null;
3741
+ const tokenCost = row.token_cost ?? null;
3742
+ const audience = row.audience ?? null;
3743
+ const languageType = row.language_type ?? null;
3744
+ const parentMemoryId = row.parent_memory_id ?? null;
3745
+ const cols = `id, agent_id, agent_role, session_id, timestamp,
3746
+ tool_name, project_name,
3747
+ has_error, raw_text, vector, version, task_id, importance, status,
3748
+ confidence, last_accessed,
3749
+ workspace_id, document_id, user_id, char_offset, page_number,
3750
+ source_path, source_type, tier, supersedes_id, draft, memory_type, trajectory, content_hash,
3751
+ intent, outcome, domain, referenced_entities, retrieval_count,
3752
+ chain_position, review_status, context_window_pct, file_paths, commit_hash,
3753
+ duration_ms, token_cost, audience, language_type, parent_memory_id`;
3754
+ const metaArgs = [
3755
+ intent,
3756
+ outcome,
3757
+ domain,
3758
+ referencedEntities,
3759
+ retrievalCount,
3760
+ chainPosition,
3761
+ reviewStatus,
3762
+ contextWindowPct,
3763
+ filePaths,
3764
+ commitHash,
3765
+ durationMs,
3766
+ tokenCost,
3767
+ audience,
3768
+ languageType,
3769
+ parentMemoryId
3770
+ ];
3771
+ const baseArgs = [
3772
+ row.id,
3773
+ row.agent_id,
3774
+ row.agent_role,
3775
+ row.session_id,
3776
+ row.timestamp,
3777
+ row.tool_name,
3778
+ row.project_name,
3779
+ row.has_error,
3780
+ row.raw_text
3781
+ ];
3782
+ const sharedArgs = [
3783
+ row.version,
3784
+ taskId,
3785
+ importance,
3786
+ status2,
3787
+ confidence,
3788
+ lastAccessed,
3789
+ workspaceId,
3790
+ documentId,
3791
+ userId,
3792
+ charOffset,
3793
+ pageNumber,
3794
+ sourcePath,
3795
+ sourceType,
3796
+ tier,
3797
+ supersedesId,
3798
+ draft,
3799
+ memoryType,
3800
+ trajectory,
3801
+ contentHash
3802
+ ];
3803
+ return {
3804
+ sql: hasVector ? `INSERT OR IGNORE INTO memories (${cols})
3805
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, vector32(?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` : `INSERT OR IGNORE INTO memories (${cols})
3806
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
3807
+ args: hasVector ? [...baseArgs, vectorToBlob(row.vector), ...sharedArgs, ...metaArgs] : [...baseArgs, ...sharedArgs, ...metaArgs]
3808
+ };
3809
+ };
3810
+ const globalClient = getClient();
3811
+ const globalStmts = batch.map(buildStmt);
3812
+ await globalClient.batch(globalStmts, "write");
3813
+ _pendingRecords.splice(0, batch.length);
3814
+ try {
3815
+ const { isShardingEnabled: isShardingEnabled2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
3816
+ if (isShardingEnabled2()) {
3817
+ const byProject = /* @__PURE__ */ new Map();
3818
+ for (const row of batch) {
3819
+ const proj = row.project_name || "unknown";
3820
+ if (!byProject.has(proj)) byProject.set(proj, []);
3821
+ byProject.get(proj).push(row);
3822
+ }
3823
+ for (const [project, rows] of byProject) {
3824
+ try {
3825
+ const shardClient = await getReadyShardClient2(project);
3826
+ const shardStmts = rows.map(buildStmt);
3827
+ await shardClient.batch(shardStmts, "write");
3828
+ } catch (err) {
3829
+ process.stderr.write(
3830
+ `[store] Shard write failed for ${project}: ${err instanceof Error ? err.message : String(err)}
3831
+ `
3832
+ );
3833
+ }
3834
+ }
2462
3835
  }
2463
- ];
2464
- PLATFORM_PROCEDURE_TITLES = new Set(
2465
- PLATFORM_PROCEDURES.map((p) => p.title)
2466
- );
3836
+ } catch {
3837
+ }
3838
+ return batch.length;
3839
+ } finally {
3840
+ _flushing = false;
2467
3841
  }
2468
- });
2469
-
2470
- // src/lib/global-procedures.ts
2471
- var global_procedures_exports = {};
2472
- __export(global_procedures_exports, {
2473
- deactivateGlobalProcedure: () => deactivateGlobalProcedure,
2474
- getGlobalProceduresBlock: () => getGlobalProceduresBlock,
2475
- loadGlobalProcedures: () => loadGlobalProcedures,
2476
- storeGlobalProcedure: () => storeGlobalProcedure
2477
- });
2478
- import { randomUUID } from "crypto";
2479
- async function loadGlobalProcedures() {
3842
+ }
3843
+ function buildWikiScopeFilter(options, columnPrefix) {
3844
+ const args = [];
3845
+ let clause = "";
3846
+ if (options?.workspaceId !== void 0) {
3847
+ clause += ` AND ${columnPrefix}workspace_id = ?`;
3848
+ args.push(options.workspaceId);
3849
+ }
3850
+ if (options?.userId === void 0) {
3851
+ clause += ` AND ${columnPrefix}user_id IS NULL`;
3852
+ } else if (options.userId === null) {
3853
+ clause += ` AND ${columnPrefix}user_id IS NULL`;
3854
+ } else {
3855
+ clause += ` AND (${columnPrefix}user_id = ? OR ${columnPrefix}user_id IS NULL)`;
3856
+ args.push(options.userId);
3857
+ }
3858
+ return { clause, args };
3859
+ }
3860
+ function buildRawVisibilityFilter(options, columnPrefix) {
3861
+ if (options?.includeRaw === false) {
3862
+ return {
3863
+ clause: ` AND COALESCE(${columnPrefix}memory_type, 'raw') != 'raw'`,
3864
+ args: []
3865
+ };
3866
+ }
3867
+ return { clause: "", args: [] };
3868
+ }
3869
+ async function searchMemories(queryVector, agentId, options) {
3870
+ let client;
3871
+ try {
3872
+ const { isShardingEnabled: isShardingEnabled2, shardExists: shardExists2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
3873
+ if (isShardingEnabled2() && options?.projectName && shardExists2(options.projectName)) {
3874
+ client = await getReadyShardClient2(options.projectName);
3875
+ } else {
3876
+ client = getClient();
3877
+ }
3878
+ } catch {
3879
+ client = getClient();
3880
+ }
3881
+ const limit = options?.limit ?? 10;
3882
+ const statusFilter = options?.includeArchived ? "" : `
3883
+ AND COALESCE(status, 'active') = 'active'`;
3884
+ const draftFilter = options?.includeDrafts ? "" : `
3885
+ AND (draft = 0 OR draft IS NULL)`;
3886
+ let sql = `SELECT id, agent_id, agent_role, session_id, timestamp,
3887
+ tool_name, project_name,
3888
+ has_error, raw_text, vector, importance, status,
3889
+ confidence, last_accessed,
3890
+ workspace_id, document_id, user_id,
3891
+ char_offset, page_number,
3892
+ source_path, source_type
3893
+ FROM memories
3894
+ WHERE agent_id = ?
3895
+ AND vector IS NOT NULL${statusFilter}${draftFilter}
3896
+ AND COALESCE(confidence, 0.7) >= 0.3`;
3897
+ const args = [agentId];
3898
+ const scope = buildWikiScopeFilter(options, "");
3899
+ sql += scope.clause;
3900
+ args.push(...scope.args);
3901
+ const rawVisibility = buildRawVisibilityFilter(options, "");
3902
+ sql += rawVisibility.clause;
3903
+ args.push(...rawVisibility.args);
3904
+ if (options?.projectName) {
3905
+ sql += ` AND project_name = ?`;
3906
+ args.push(options.projectName);
3907
+ }
3908
+ if (options?.toolName) {
3909
+ sql += ` AND tool_name = ?`;
3910
+ args.push(options.toolName);
3911
+ }
3912
+ if (options?.hasError !== void 0) {
3913
+ sql += ` AND has_error = ?`;
3914
+ args.push(options.hasError ? 1 : 0);
3915
+ }
3916
+ if (options?.since) {
3917
+ sql += ` AND timestamp >= ?`;
3918
+ args.push(options.since);
3919
+ }
3920
+ if (options?.memoryType) {
3921
+ sql += ` AND memory_type = ?`;
3922
+ args.push(options.memoryType);
3923
+ }
3924
+ sql += ` ORDER BY vector_distance_cos(vector, vector32(?))`;
3925
+ args.push(vectorToBlob(queryVector));
3926
+ sql += ` LIMIT ?`;
3927
+ args.push(limit);
3928
+ const result = await client.execute({ sql, args });
3929
+ return result.rows.map((row) => ({
3930
+ id: row.id,
3931
+ agent_id: row.agent_id,
3932
+ agent_role: row.agent_role,
3933
+ session_id: row.session_id,
3934
+ timestamp: row.timestamp,
3935
+ tool_name: row.tool_name,
3936
+ project_name: row.project_name,
3937
+ has_error: row.has_error === 1,
3938
+ raw_text: row.raw_text,
3939
+ vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
3940
+ importance: row.importance ?? 5,
3941
+ status: row.status ?? "active",
3942
+ confidence: row.confidence ?? 0.7,
3943
+ last_accessed: row.last_accessed ?? row.timestamp,
3944
+ workspace_id: row.workspace_id ?? null,
3945
+ document_id: row.document_id ?? null,
3946
+ user_id: row.user_id ?? null,
3947
+ char_offset: row.char_offset ?? null,
3948
+ page_number: row.page_number ?? null,
3949
+ source_path: row.source_path ?? null,
3950
+ source_type: row.source_type ?? null
3951
+ }));
3952
+ }
3953
+ async function attachDocumentMetadata(records) {
3954
+ const docIds = [
3955
+ ...new Set(
3956
+ records.map((r) => r.document_id).filter((id) => typeof id === "string" && id.length > 0)
3957
+ )
3958
+ ];
3959
+ if (docIds.length === 0) return records;
3960
+ try {
3961
+ const client = getClient();
3962
+ const placeholders = docIds.map(() => "?").join(",");
3963
+ const result = await client.execute({
3964
+ sql: `SELECT id, filename, mime, source_type, uploaded_at
3965
+ FROM documents
3966
+ WHERE id IN (${placeholders})`,
3967
+ args: docIds
3968
+ });
3969
+ const byId = /* @__PURE__ */ new Map();
3970
+ for (const row of result.rows) {
3971
+ const id = row.id;
3972
+ byId.set(id, {
3973
+ document_id: id,
3974
+ filename: row.filename,
3975
+ mime: row.mime ?? null,
3976
+ source_type: row.source_type ?? null,
3977
+ uploaded_at: row.uploaded_at
3978
+ });
3979
+ }
3980
+ for (const record of records) {
3981
+ if (!record.document_id) continue;
3982
+ record.document_metadata = byId.get(record.document_id) ?? null;
3983
+ }
3984
+ } catch {
3985
+ }
3986
+ return records;
3987
+ }
3988
+ async function flushTier3(agentId, options) {
2480
3989
  const client = getClient();
3990
+ const maxAge = options?.maxAgeHours ?? 72;
3991
+ const cutoff = new Date(Date.now() - maxAge * 36e5).toISOString();
3992
+ if (options?.dryRun) {
3993
+ const result2 = await client.execute({
3994
+ sql: `SELECT COUNT(*) as cnt FROM memories
3995
+ WHERE agent_id = ? AND tier = 3 AND status = 'active' AND timestamp < ?`,
3996
+ args: [agentId, cutoff]
3997
+ });
3998
+ return { archived: Number(result2.rows[0]?.cnt ?? 0) };
3999
+ }
2481
4000
  const result = await client.execute({
2482
- sql: "SELECT * FROM global_procedures WHERE active = 1 ORDER BY priority ASC, created_at ASC",
2483
- args: []
4001
+ sql: `UPDATE memories SET status = 'archived'
4002
+ WHERE agent_id = ? AND tier = 3 AND status = 'active' AND timestamp < ?`,
4003
+ args: [agentId, cutoff]
2484
4004
  });
2485
- const allRows = result.rows;
2486
- const customerOnly = allRows.filter((p) => !PLATFORM_PROCEDURE_TITLES.has(p.title));
2487
- if (customerOnly.length > 0) {
2488
- _customerCache = customerOnly.map((p) => `### ${p.title}
2489
- ${p.content}`).join("\n\n");
2490
- } else {
2491
- _customerCache = "";
4005
+ return { archived: result.rowsAffected };
4006
+ }
4007
+ async function disposeStore() {
4008
+ if (_flushTimer !== null) {
4009
+ clearInterval(_flushTimer);
4010
+ _flushTimer = null;
2492
4011
  }
2493
- _cacheLoaded = true;
2494
- return customerOnly;
4012
+ if (_pendingRecords.length > 0) {
4013
+ await flushBatch();
4014
+ }
4015
+ await disposeTurso();
4016
+ _pendingRecords = [];
4017
+ _nextVersion = 1;
2495
4018
  }
2496
- function getGlobalProceduresBlock() {
2497
- const sections = [];
2498
- if (_platformCache) sections.push(_platformCache);
2499
- if (_cacheLoaded && _customerCache) sections.push(_customerCache);
2500
- if (sections.length === 0) return "";
2501
- return `## Organization-Wide Procedures (MANDATORY \u2014 supersedes all other rules)
2502
-
2503
- ${sections.join("\n\n")}
2504
- `;
4019
+ function vectorToBlob(vector) {
4020
+ const f32 = vector instanceof Float32Array ? vector : new Float32Array(vector);
4021
+ return JSON.stringify(Array.from(f32));
2505
4022
  }
2506
- async function storeGlobalProcedure(input) {
2507
- const id = randomUUID();
2508
- const now = (/* @__PURE__ */ new Date()).toISOString();
4023
+ async function updateMemoryStatus(id, status2) {
2509
4024
  const client = getClient();
2510
4025
  await client.execute({
2511
- sql: `INSERT INTO global_procedures (id, title, content, priority, domain, active, created_at, updated_at)
2512
- VALUES (?, ?, ?, ?, ?, 1, ?, ?)`,
2513
- args: [id, input.title, input.content, input.priority ?? "p0", input.domain ?? null, now, now]
4026
+ sql: `UPDATE memories SET status = ? WHERE id = ?`,
4027
+ args: [status2, id]
2514
4028
  });
2515
- await loadGlobalProcedures();
2516
- return id;
2517
4029
  }
2518
- async function deactivateGlobalProcedure(id) {
2519
- const now = (/* @__PURE__ */ new Date()).toISOString();
2520
- const client = getClient();
2521
- const result = await client.execute({
2522
- sql: "UPDATE global_procedures SET active = 0, updated_at = ? WHERE id = ?",
2523
- args: [now, id]
2524
- });
2525
- await loadGlobalProcedures();
2526
- return result.rowsAffected > 0;
4030
+ function reserveVersions(count) {
4031
+ const reserved = [];
4032
+ for (let i = 0; i < count; i++) {
4033
+ reserved.push(_nextVersion++);
4034
+ }
4035
+ return reserved;
2527
4036
  }
2528
- var _customerCache, _cacheLoaded, _platformCache;
2529
- var init_global_procedures = __esm({
2530
- "src/lib/global-procedures.ts"() {
4037
+ async function getMemoryCardinality(agentId) {
4038
+ try {
4039
+ const client = getClient();
4040
+ const result = await client.execute({
4041
+ sql: `SELECT COUNT(*) as cnt FROM memories WHERE agent_id = ? AND COALESCE(status, 'active') = 'active'`,
4042
+ args: [agentId]
4043
+ });
4044
+ return Number(result.rows[0]?.cnt) || 0;
4045
+ } catch {
4046
+ return 0;
4047
+ }
4048
+ }
4049
+ var INIT_MAX_RETRIES, INIT_RETRY_DELAY_MS, _pendingRecords, _batchSize, _flushIntervalMs, _flushTimer, _flushing, _nextVersion;
4050
+ var init_store = __esm({
4051
+ "src/lib/store.ts"() {
2531
4052
  "use strict";
4053
+ init_memory();
2532
4054
  init_database();
2533
- init_platform_procedures();
2534
- _customerCache = "";
2535
- _cacheLoaded = false;
2536
- _platformCache = PLATFORM_PROCEDURES.map((p) => `### ${p.title}
2537
- ${p.content}`).join("\n\n");
4055
+ init_keychain();
4056
+ init_config();
4057
+ init_state_bus();
4058
+ INIT_MAX_RETRIES = 3;
4059
+ INIT_RETRY_DELAY_MS = 1e3;
4060
+ _pendingRecords = [];
4061
+ _batchSize = 20;
4062
+ _flushIntervalMs = 1e4;
4063
+ _flushTimer = null;
4064
+ _flushing = false;
4065
+ _nextVersion = 1;
2538
4066
  }
2539
4067
  });
2540
4068
 
2541
4069
  // src/lib/session-registry.ts
2542
- import path6 from "path";
2543
- import os5 from "os";
4070
+ import path8 from "path";
4071
+ import os6 from "os";
2544
4072
  var REGISTRY_PATH;
2545
4073
  var init_session_registry = __esm({
2546
4074
  "src/lib/session-registry.ts"() {
2547
4075
  "use strict";
2548
- REGISTRY_PATH = path6.join(os5.homedir(), ".exe-os", "session-registry.json");
4076
+ REGISTRY_PATH = path8.join(os6.homedir(), ".exe-os", "session-registry.json");
2549
4077
  }
2550
4078
  });
2551
4079
 
@@ -2790,8 +4318,8 @@ var init_runtime_table = __esm({
2790
4318
  });
2791
4319
 
2792
4320
  // src/lib/agent-config.ts
2793
- import { readFileSync as readFileSync3, writeFileSync as writeFileSync2, existsSync as existsSync6 } from "fs";
2794
- import path7 from "path";
4321
+ import { readFileSync as readFileSync5, writeFileSync as writeFileSync3, existsSync as existsSync8 } from "fs";
4322
+ import path9 from "path";
2795
4323
  var AGENT_CONFIG_PATH, DEFAULT_MODELS;
2796
4324
  var init_agent_config = __esm({
2797
4325
  "src/lib/agent-config.ts"() {
@@ -2799,9 +4327,9 @@ var init_agent_config = __esm({
2799
4327
  init_config();
2800
4328
  init_runtime_table();
2801
4329
  init_secure_files();
2802
- AGENT_CONFIG_PATH = path7.join(EXE_AI_DIR, "agent-config.json");
4330
+ AGENT_CONFIG_PATH = path9.join(EXE_AI_DIR, "agent-config.json");
2803
4331
  DEFAULT_MODELS = {
2804
- claude: "claude-opus-4",
4332
+ claude: "claude-opus-4.6",
2805
4333
  codex: RUNTIME_TABLE.codex?.defaultModel ?? "gpt-5.4",
2806
4334
  opencode: RUNTIME_TABLE.opencode?.defaultModel ?? "anthropic/claude-sonnet-4-6"
2807
4335
  };
@@ -2809,41 +4337,41 @@ var init_agent_config = __esm({
2809
4337
  });
2810
4338
 
2811
4339
  // src/lib/intercom-queue.ts
2812
- import { readFileSync as readFileSync4, writeFileSync as writeFileSync3, renameSync as renameSync3, existsSync as existsSync7, mkdirSync as mkdirSync3 } from "fs";
2813
- import path8 from "path";
2814
- import os6 from "os";
4340
+ import { readFileSync as readFileSync6, writeFileSync as writeFileSync4, renameSync as renameSync3, existsSync as existsSync9, mkdirSync as mkdirSync3 } from "fs";
4341
+ import path10 from "path";
4342
+ import os7 from "os";
2815
4343
  var QUEUE_PATH, TTL_MS, INTERCOM_LOG;
2816
4344
  var init_intercom_queue = __esm({
2817
4345
  "src/lib/intercom-queue.ts"() {
2818
4346
  "use strict";
2819
- QUEUE_PATH = path8.join(os6.homedir(), ".exe-os", "intercom-queue.json");
4347
+ QUEUE_PATH = path10.join(os7.homedir(), ".exe-os", "intercom-queue.json");
2820
4348
  TTL_MS = 60 * 60 * 1e3;
2821
- INTERCOM_LOG = path8.join(os6.homedir(), ".exe-os", "intercom.log");
4349
+ INTERCOM_LOG = path10.join(os7.homedir(), ".exe-os", "intercom.log");
2822
4350
  }
2823
4351
  });
2824
4352
 
2825
4353
  // src/lib/license.ts
2826
- import { readFileSync as readFileSync5, writeFileSync as writeFileSync4, existsSync as existsSync8, mkdirSync as mkdirSync4 } from "fs";
2827
- import { randomUUID as randomUUID2 } from "crypto";
4354
+ import { readFileSync as readFileSync7, writeFileSync as writeFileSync5, existsSync as existsSync10, mkdirSync as mkdirSync4 } from "fs";
4355
+ import { randomUUID as randomUUID3 } from "crypto";
2828
4356
  import { createRequire as createRequire2 } from "module";
2829
4357
  import { pathToFileURL as pathToFileURL2 } from "url";
2830
- import os7 from "os";
2831
- import path9 from "path";
4358
+ import os8 from "os";
4359
+ import path11 from "path";
2832
4360
  import { jwtVerify, importSPKI } from "jose";
2833
4361
  var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH;
2834
4362
  var init_license = __esm({
2835
4363
  "src/lib/license.ts"() {
2836
4364
  "use strict";
2837
4365
  init_config();
2838
- LICENSE_PATH = path9.join(EXE_AI_DIR, "license.key");
2839
- CACHE_PATH = path9.join(EXE_AI_DIR, "license-cache.json");
2840
- DEVICE_ID_PATH = path9.join(EXE_AI_DIR, "device-id");
4366
+ LICENSE_PATH = path11.join(EXE_AI_DIR, "license.key");
4367
+ CACHE_PATH = path11.join(EXE_AI_DIR, "license-cache.json");
4368
+ DEVICE_ID_PATH = path11.join(EXE_AI_DIR, "device-id");
2841
4369
  }
2842
4370
  });
2843
4371
 
2844
4372
  // src/lib/plan-limits.ts
2845
- import { readFileSync as readFileSync6, existsSync as existsSync9 } from "fs";
2846
- import path10 from "path";
4373
+ import { readFileSync as readFileSync8, existsSync as existsSync11 } from "fs";
4374
+ import path12 from "path";
2847
4375
  var CACHE_PATH2;
2848
4376
  var init_plan_limits = __esm({
2849
4377
  "src/lib/plan-limits.ts"() {
@@ -2852,15 +4380,15 @@ var init_plan_limits = __esm({
2852
4380
  init_employees();
2853
4381
  init_license();
2854
4382
  init_config();
2855
- CACHE_PATH2 = path10.join(EXE_AI_DIR, "license-cache.json");
4383
+ CACHE_PATH2 = path12.join(EXE_AI_DIR, "license-cache.json");
2856
4384
  }
2857
4385
  });
2858
4386
 
2859
4387
  // src/lib/tmux-routing.ts
2860
- import { readFileSync as readFileSync7, writeFileSync as writeFileSync5, mkdirSync as mkdirSync5, existsSync as existsSync10, appendFileSync, readdirSync as readdirSync2 } from "fs";
2861
- import path11 from "path";
2862
- import os8 from "os";
2863
- import { fileURLToPath as fileURLToPath2 } from "url";
4388
+ import { readFileSync as readFileSync9, writeFileSync as writeFileSync6, mkdirSync as mkdirSync5, existsSync as existsSync12, appendFileSync, readdirSync as readdirSync2 } from "fs";
4389
+ import path13 from "path";
4390
+ import os9 from "os";
4391
+ import { fileURLToPath as fileURLToPath3 } from "url";
2864
4392
  function getMySession() {
2865
4393
  return getTransport().getMySession();
2866
4394
  }
@@ -2872,7 +4400,7 @@ function extractRootExe(name) {
2872
4400
  }
2873
4401
  function getParentExe(sessionKey) {
2874
4402
  try {
2875
- const data = JSON.parse(readFileSync7(path11.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
4403
+ const data = JSON.parse(readFileSync9(path13.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
2876
4404
  return data.parentExe || null;
2877
4405
  } catch {
2878
4406
  return null;
@@ -2915,10 +4443,10 @@ var init_tmux_routing = __esm({
2915
4443
  init_intercom_queue();
2916
4444
  init_plan_limits();
2917
4445
  init_employees();
2918
- SPAWN_LOCK_DIR = path11.join(os8.homedir(), ".exe-os", "spawn-locks");
2919
- SESSION_CACHE = path11.join(os8.homedir(), ".exe-os", "session-cache");
2920
- INTERCOM_LOG2 = path11.join(os8.homedir(), ".exe-os", "intercom.log");
2921
- DEBOUNCE_FILE = path11.join(SESSION_CACHE, "intercom-debounce.json");
4446
+ SPAWN_LOCK_DIR = path13.join(os9.homedir(), ".exe-os", "spawn-locks");
4447
+ SESSION_CACHE = path13.join(os9.homedir(), ".exe-os", "session-cache");
4448
+ INTERCOM_LOG2 = path13.join(os9.homedir(), ".exe-os", "intercom.log");
4449
+ DEBOUNCE_FILE = path13.join(SESSION_CACHE, "intercom-debounce.json");
2922
4450
  DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
2923
4451
  }
2924
4452
  });
@@ -2950,141 +4478,66 @@ var init_task_scope = __esm({
2950
4478
  // src/bin/exe-status.ts
2951
4479
  init_employees();
2952
4480
 
2953
- // src/lib/store.ts
2954
- import { createHash } from "crypto";
2955
- init_database();
2956
-
2957
- // src/lib/keychain.ts
2958
- import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
2959
- import { existsSync as existsSync4 } from "fs";
2960
- import path4 from "path";
2961
- import os4 from "os";
2962
- var SERVICE = "exe-mem";
2963
- var ACCOUNT = "master-key";
2964
- function getKeyDir() {
2965
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
2966
- }
2967
- function getKeyPath() {
2968
- return path4.join(getKeyDir(), "master.key");
2969
- }
2970
- async function tryKeytar() {
2971
- try {
2972
- return await import("keytar");
2973
- } catch {
2974
- return null;
2975
- }
2976
- }
2977
- async function getMasterKey() {
2978
- const keytar = await tryKeytar();
2979
- if (keytar) {
2980
- try {
2981
- const stored = await keytar.getPassword(SERVICE, ACCOUNT);
2982
- if (stored) {
2983
- return Buffer.from(stored, "base64");
2984
- }
2985
- } catch {
2986
- }
2987
- }
2988
- const keyPath = getKeyPath();
2989
- if (!existsSync4(keyPath)) {
2990
- process.stderr.write(
2991
- `[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
2992
- `
2993
- );
2994
- return null;
4481
+ // src/bin/fast-db-init.ts
4482
+ async function fastDbInit() {
4483
+ const { isInitialized: isInitialized2, getClient: getClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
4484
+ if (isInitialized2()) {
4485
+ return getClient2();
2995
4486
  }
2996
4487
  try {
2997
- const content = await readFile3(keyPath, "utf-8");
2998
- return Buffer.from(content.trim(), "base64");
2999
- } catch (err) {
3000
- process.stderr.write(
3001
- `[keychain] Key read failed at ${keyPath}: ${err instanceof Error ? err.message : String(err)}
3002
- `
3003
- );
3004
- return null;
3005
- }
3006
- }
3007
-
3008
- // src/lib/store.ts
3009
- init_config();
3010
- init_state_bus();
3011
- var INIT_MAX_RETRIES = 3;
3012
- var INIT_RETRY_DELAY_MS = 1e3;
3013
- function isBusyError2(err) {
3014
- if (err instanceof Error) {
3015
- const msg = err.message.toLowerCase();
3016
- return msg.includes("sqlite_busy") || msg.includes("database is locked");
3017
- }
3018
- return false;
3019
- }
3020
- async function retryOnBusy2(fn, label) {
3021
- for (let attempt = 0; attempt <= INIT_MAX_RETRIES; attempt++) {
3022
- try {
3023
- return await fn();
3024
- } catch (err) {
3025
- if (!isBusyError2(err) || attempt === INIT_MAX_RETRIES) throw err;
3026
- process.stderr.write(
3027
- `[store] SQLITE_BUSY during ${label}, retry ${attempt + 1}/${INIT_MAX_RETRIES}
3028
- `
3029
- );
3030
- await new Promise((r) => setTimeout(r, INIT_RETRY_DELAY_MS * (attempt + 1)));
3031
- }
3032
- }
3033
- throw new Error("unreachable");
3034
- }
3035
- var _pendingRecords = [];
3036
- var _batchSize = 20;
3037
- var _flushIntervalMs = 1e4;
3038
- var _flushTimer = null;
3039
- var _flushing = false;
3040
- var _nextVersion = 1;
3041
- async function initStore(options) {
3042
- if (_flushTimer !== null) {
3043
- clearInterval(_flushTimer);
3044
- _flushTimer = null;
3045
- }
3046
- _pendingRecords = [];
3047
- _flushing = false;
3048
- _batchSize = options?.batchSize ?? 20;
3049
- _flushIntervalMs = options?.flushIntervalMs ?? 1e4;
3050
- let dbPath = options?.dbPath;
3051
- if (!dbPath) {
3052
- const config = await loadConfig();
3053
- dbPath = config.dbPath;
3054
- }
3055
- let masterKey = options?.masterKey ?? null;
3056
- if (!masterKey) {
3057
- masterKey = await getMasterKey();
3058
- if (!masterKey) {
3059
- throw new Error(
3060
- "No encryption key found. Run /exe-setup to generate one."
3061
- );
3062
- }
3063
- }
3064
- const hexKey = masterKey.toString("hex");
3065
- await initTurso({
3066
- dbPath,
3067
- encryptionKey: hexKey
3068
- });
3069
- await retryOnBusy2(() => ensureSchema(), "ensureSchema");
3070
- if (!options?.lightweight) {
3071
- try {
3072
- const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
3073
- initShardManager2(hexKey);
3074
- } catch {
3075
- }
3076
- const client = getClient();
3077
- const vResult = await retryOnBusy2(
3078
- () => client.execute("SELECT MAX(version) as max_v FROM memories"),
3079
- "version-query"
3080
- );
3081
- _nextVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
3082
- try {
3083
- const { loadGlobalProcedures: loadGlobalProcedures2 } = await Promise.resolve().then(() => (init_global_procedures(), global_procedures_exports));
3084
- await loadGlobalProcedures2();
3085
- } catch {
4488
+ const { connectEmbedDaemon: connectEmbedDaemon2, sendDaemonRequest: sendDaemonRequest2, isClientConnected: isClientConnected2 } = await Promise.resolve().then(() => (init_exe_daemon_client(), exe_daemon_client_exports));
4489
+ const { deserializeResultSet: deserializeResultSet2 } = await Promise.resolve().then(() => (init_daemon_protocol(), daemon_protocol_exports));
4490
+ await connectEmbedDaemon2();
4491
+ if (isClientConnected2()) {
4492
+ const daemonClient = {
4493
+ async execute(stmt) {
4494
+ const sql = typeof stmt === "string" ? stmt : stmt.sql;
4495
+ const args = typeof stmt === "string" ? [] : Array.isArray(stmt.args) ? stmt.args : [];
4496
+ const resp = await sendDaemonRequest2({ type: "db-execute", sql, args });
4497
+ if (resp.error) throw new Error(String(resp.error));
4498
+ if (resp.db) return deserializeResultSet2(resp.db);
4499
+ throw new Error("Unexpected daemon response");
4500
+ },
4501
+ async batch(stmts, mode) {
4502
+ const statements = stmts.map((s) => {
4503
+ const sql = typeof s === "string" ? s : s.sql;
4504
+ const args = typeof s === "string" ? [] : Array.isArray(s.args) ? s.args : [];
4505
+ return { sql, args };
4506
+ });
4507
+ const resp = await sendDaemonRequest2({ type: "db-batch", statements, mode: mode ?? "deferred" });
4508
+ if (resp.error) throw new Error(String(resp.error));
4509
+ const batchResults = resp["db-batch"];
4510
+ if (batchResults) return batchResults.map(deserializeResultSet2);
4511
+ throw new Error("Unexpected daemon batch response");
4512
+ },
4513
+ async transaction(_mode) {
4514
+ throw new Error("Transactions not supported via daemon socket");
4515
+ },
4516
+ async executeMultiple(_sql) {
4517
+ throw new Error("executeMultiple not supported via daemon socket");
4518
+ },
4519
+ async migrate(_stmts) {
4520
+ throw new Error("migrate not supported via daemon socket");
4521
+ },
4522
+ sync() {
4523
+ return Promise.resolve(void 0);
4524
+ },
4525
+ close() {
4526
+ },
4527
+ get closed() {
4528
+ return false;
4529
+ },
4530
+ get protocol() {
4531
+ return "file";
4532
+ }
4533
+ };
4534
+ return daemonClient;
3086
4535
  }
4536
+ } catch {
3087
4537
  }
4538
+ const { initStore: initStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
4539
+ await initStore2({ lightweight: true });
4540
+ return getClient2();
3088
4541
  }
3089
4542
 
3090
4543
  // src/bin/exe-status.ts
@@ -3313,13 +4766,13 @@ function formatStatusDeep(status2, task, role) {
3313
4766
 
3314
4767
  // src/lib/is-main.ts
3315
4768
  import { realpathSync } from "fs";
3316
- import { fileURLToPath } from "url";
4769
+ import { fileURLToPath as fileURLToPath2 } from "url";
3317
4770
  function isMainModule(importMetaUrl) {
3318
4771
  if (process.argv[1] == null) return false;
3319
4772
  if (process.argv[1].includes("mcp/server")) return false;
3320
4773
  try {
3321
4774
  const scriptPath = realpathSync(process.argv[1]);
3322
- const modulePath = realpathSync(fileURLToPath(importMetaUrl));
4775
+ const modulePath = realpathSync(fileURLToPath2(importMetaUrl));
3323
4776
  return scriptPath === modulePath;
3324
4777
  } catch {
3325
4778
  return importMetaUrl === `file://${process.argv[1]}` || importMetaUrl === new URL(process.argv[1], "file://").href;
@@ -3335,7 +4788,7 @@ async function status(targetEmployee) {
3335
4788
  const employees = await loadEmployees();
3336
4789
  const names = employees.filter((e) => !isCoordinatorRole(e.role)).map((e) => e.name);
3337
4790
  const roles = new Map(employees.map((e) => [e.name, e.role ?? ""]));
3338
- await initStore();
4791
+ await fastDbInit();
3339
4792
  const client = getClient();
3340
4793
  const taskMap = /* @__PURE__ */ new Map();
3341
4794
  try {